1 -- -----------------------------------------------------------------------------
3 -- (c) The University of Glasgow, 2005
7 -- -----------------------------------------------------------------------------
13 defaultCleanupHandler,
16 -- * Flags and settings
17 DynFlags(..), DynFlag(..), Severity(..), GhcMode(..), HscTarget(..), dopt,
23 Target(..), TargetId(..), Phase,
30 -- * Extending the program scope
31 extendGlobalRdrScope, -- :: Session -> [GlobalRdrElt] -> IO ()
32 setGlobalRdrScope, -- :: Session -> [GlobalRdrElt] -> IO ()
33 extendGlobalTypeScope, -- :: Session -> [Id] -> IO ()
34 setGlobalTypeScope, -- :: Session -> [Id] -> IO ()
36 -- * Loading\/compiling the program
38 load, LoadHowMuch(..), SuccessFlag(..), -- also does depanal
39 workingDirectoryChanged,
40 checkModule, CheckedModule(..),
41 TypecheckedSource, ParsedSource, RenamedSource,
43 -- * Inspecting the module structure of the program
44 ModuleGraph, ModSummary(..), ms_mod_name, ModLocation(..),
49 -- * Inspecting modules
54 modInfoPrintUnqualified,
57 modInfoIsExportedName,
62 PrintUnqualified, alwaysQualify,
64 -- * Interactive evaluation
65 getBindings, getPrintUnqual,
68 setContext, getContext,
79 compileExpr, HValue, dynCompileExpr,
83 -- * Abstract syntax elements
89 Module, mkModule, pprModule, moduleName, modulePackageId,
90 ModuleName, mkModuleName, moduleNameString,
94 nameModule, nameParent_maybe, pprParenSymName, nameSrcLoc,
100 isImplicitId, isDeadBinder,
101 isExportedId, isLocalId, isGlobalId,
103 isPrimOpId, isFCallId, isClassOpId_maybe,
104 isDataConWorkId, idDataCon,
105 isBottomingId, isDictonaryId,
106 recordSelectorFieldLabel,
108 -- ** Type constructors
110 tyConTyVars, tyConDataCons, tyConArity,
111 isClassTyCon, isSynTyCon, isNewTyCon, isPrimTyCon, isFunTyCon,
113 synTyConDefn, synTyConType, synTyConResKind,
119 -- ** Data constructors
121 dataConSig, dataConType, dataConTyCon, dataConFieldLabels,
122 dataConIsInfix, isVanillaDataCon,
124 StrictnessMark(..), isMarkedStrict,
128 classMethods, classSCTheta, classTvsFds,
133 instanceDFunId, pprInstance, pprInstanceHdr,
135 -- ** Types and Kinds
136 Type, dropForAlls, splitForAllTys, funResultTy, pprParendType,
139 ThetaType, pprThetaArrow,
145 module HsSyn, -- ToDo: remove extraneous bits
149 defaultFixity, maxPrecedence,
153 -- ** Source locations
157 GhcException(..), showGhcException,
167 * inline bits of HscMain here to simplify layering: hscTcExpr, hscStmt.
168 * what StaticFlags should we expose, if any?
171 #include "HsVersions.h"
174 import qualified Linker
175 import Data.Dynamic ( Dynamic )
176 import Linker ( HValue, extendLinkEnv )
177 import TcRnDriver ( tcRnLookupRdrName, tcRnGetInfo,
178 tcRnLookupName, getModuleExports )
179 import RdrName ( plusGlobalRdrEnv, Provenance(..),
180 ImportSpec(..), ImpDeclSpec(..), ImpItemSpec(..),
182 import HscMain ( hscParseIdentifier, hscStmt, hscTcExpr, hscKcType )
183 import Name ( nameOccName )
184 import Type ( tidyType )
185 import VarEnv ( emptyTidyEnv )
186 import GHC.Exts ( unsafeCoerce# )
189 import Packages ( initPackages )
190 import NameSet ( NameSet, nameSetToList, elemNameSet )
191 import RdrName ( GlobalRdrEnv, GlobalRdrElt(..), RdrName(..),
192 globalRdrEnvElts, extendGlobalRdrEnv,
195 import Type ( Kind, Type, dropForAlls, PredType, ThetaType,
196 pprThetaArrow, pprParendType, splitForAllTys,
198 import Id ( Id, idType, isImplicitId, isDeadBinder,
199 isExportedId, isLocalId, isGlobalId,
200 isRecordSelector, recordSelectorFieldLabel,
201 isPrimOpId, isFCallId, isClassOpId_maybe,
202 isDataConWorkId, idDataCon,
205 import TysPrim ( alphaTyVars )
206 import TyCon ( TyCon, isClassTyCon, isSynTyCon, isNewTyCon,
207 isPrimTyCon, isFunTyCon, isOpenTyCon, tyConArity,
208 tyConTyVars, tyConDataCons, synTyConDefn,
209 synTyConType, synTyConResKind )
210 import Class ( Class, classSCTheta, classTvsFds, classMethods )
211 import FunDeps ( pprFundeps )
212 import DataCon ( DataCon, dataConWrapId, dataConSig, dataConTyCon,
213 dataConFieldLabels, dataConStrictMarks,
214 dataConIsInfix, isVanillaDataCon )
215 import Name ( Name, nameModule, NamedThing(..), nameParent_maybe,
217 import OccName ( parenSymOcc )
218 import NameEnv ( nameEnvElts )
219 import InstEnv ( Instance, instanceDFunId, pprInstance, pprInstanceHdr )
221 import DriverPipeline
222 import DriverPhases ( Phase(..), isHaskellSrcFilename, startPhase )
223 import HeaderInfo ( getImports, getOptions )
225 import HscMain ( newHscEnv, hscFileCheck, HscChecked(..) )
228 import SysTools ( initSysTools, cleanTempFiles, cleanTempFilesExcept,
232 import PackageConfig ( PackageId, stringToPackageId )
236 import Bag ( unitBag, listToBag )
237 import ErrUtils ( Severity(..), showPass, fatalErrorMsg, debugTraceMsg,
238 mkPlainErrMsg, printBagOfErrors, printBagOfWarnings,
240 import qualified ErrUtils
242 import StringBuffer ( StringBuffer, hGetStringBuffer )
245 import TcType ( tcSplitSigmaTy, isDictTy )
246 import Maybes ( expectJust, mapCatMaybes )
248 import Control.Concurrent
249 import System.Directory ( getModificationTime, doesFileExist )
250 import Data.Maybe ( isJust, isNothing )
251 import Data.List ( partition, nub )
252 import qualified Data.List as List
253 import Control.Monad ( unless, when )
254 import System.Exit ( exitWith, ExitCode(..) )
255 import System.Time ( ClockTime )
256 import Control.Exception as Exception hiding (handle)
259 import System.IO.Error ( isDoesNotExistError )
260 import Prelude hiding (init)
262 #if __GLASGOW_HASKELL__ < 600
263 import System.IO as System.IO.Error ( try )
265 import System.IO.Error ( try )
268 -- -----------------------------------------------------------------------------
269 -- Exception handlers
271 -- | Install some default exception handlers and run the inner computation.
272 -- Unless you want to handle exceptions yourself, you should wrap this around
273 -- the top level of your program. The default handlers output the error
274 -- message(s) to stderr and exit cleanly.
275 defaultErrorHandler :: DynFlags -> IO a -> IO a
276 defaultErrorHandler dflags inner =
277 -- top-level exception handler: any unrecognised exception is a compiler bug.
278 handle (\exception -> do
281 -- an IO exception probably isn't our fault, so don't panic
283 fatalErrorMsg dflags (text (show exception))
284 AsyncException StackOverflow ->
285 fatalErrorMsg dflags (text "stack overflow: use +RTS -K<size> to increase it")
287 fatalErrorMsg dflags (text (show (Panic (show exception))))
288 exitWith (ExitFailure 1)
291 -- program errors: messages with locations attached. Sometimes it is
292 -- convenient to just throw these as exceptions.
293 handleDyn (\dyn -> do printBagOfErrors dflags (unitBag dyn)
294 exitWith (ExitFailure 1)) $
296 -- error messages propagated as exceptions
297 handleDyn (\dyn -> do
300 PhaseFailed _ code -> exitWith code
301 Interrupted -> exitWith (ExitFailure 1)
302 _ -> do fatalErrorMsg dflags (text (show (dyn :: GhcException)))
303 exitWith (ExitFailure 1)
307 -- | Install a default cleanup handler to remove temporary files
308 -- deposited by a GHC run. This is seperate from
309 -- 'defaultErrorHandler', because you might want to override the error
310 -- handling, but still get the ordinary cleanup behaviour.
311 defaultCleanupHandler :: DynFlags -> IO a -> IO a
312 defaultCleanupHandler dflags inner =
313 -- make sure we clean up after ourselves
314 later (unless (dopt Opt_KeepTmpFiles dflags) $
315 do cleanTempFiles dflags
318 -- exceptions will be blocked while we clean the temporary files,
319 -- so there shouldn't be any difficulty if we receive further
324 -- | Starts a new session. A session consists of a set of loaded
325 -- modules, a set of options (DynFlags), and an interactive context.
326 -- ToDo: GhcMode should say "keep typechecked code" and\/or "keep renamed
328 newSession :: GhcMode -> Maybe FilePath -> IO Session
329 newSession mode mb_top_dir = do
331 main_thread <- myThreadId
332 putMVar interruptTargetThread [main_thread]
333 installSignalHandlers
335 dflags0 <- initSysTools mb_top_dir defaultDynFlags
336 dflags <- initDynFlags dflags0
337 env <- newHscEnv dflags{ ghcMode=mode }
341 -- tmp: this breaks the abstraction, but required because DriverMkDepend
342 -- needs to call the Finder. ToDo: untangle this.
343 sessionHscEnv :: Session -> IO HscEnv
344 sessionHscEnv (Session ref) = readIORef ref
346 withSession :: Session -> (HscEnv -> IO a) -> IO a
347 withSession (Session ref) f = do h <- readIORef ref; f h
349 modifySession :: Session -> (HscEnv -> HscEnv) -> IO ()
350 modifySession (Session ref) f = do h <- readIORef ref; writeIORef ref $! f h
352 -- -----------------------------------------------------------------------------
355 -- | Grabs the DynFlags from the Session
356 getSessionDynFlags :: Session -> IO DynFlags
357 getSessionDynFlags s = withSession s (return . hsc_dflags)
359 -- | Updates the DynFlags in a Session. This also reads
360 -- the package database (unless it has already been read),
361 -- and prepares the compilers knowledge about packages. It
362 -- can be called again to load new packages: just add new
363 -- package flags to (packageFlags dflags).
365 -- Returns a list of new packages that may need to be linked in using
366 -- the dynamic linker (see 'linkPackages') as a result of new package
367 -- flags. If you are not doing linking or doing static linking, you
368 -- can ignore the list of packages returned.
370 setSessionDynFlags :: Session -> DynFlags -> IO [PackageId]
371 setSessionDynFlags (Session ref) dflags = do
372 hsc_env <- readIORef ref
373 (dflags', preload) <- initPackages dflags
374 writeIORef ref $! hsc_env{ hsc_dflags = dflags' }
377 -- | If there is no -o option, guess the name of target executable
378 -- by using top-level source file name as a base.
379 guessOutputFile :: Session -> IO ()
380 guessOutputFile s = modifySession s $ \env ->
381 let dflags = hsc_dflags env
382 mod_graph = hsc_mod_graph env
383 mainModuleSrcPath, guessedName :: Maybe String
384 mainModuleSrcPath = do
385 let isMain = (== mainModIs dflags) . ms_mod
386 [ms] <- return (filter isMain mod_graph)
387 ml_hs_file (ms_location ms)
388 guessedName = fmap basenameOf mainModuleSrcPath
390 case outputFile dflags of
392 Nothing -> env { hsc_dflags = dflags { outputFile = guessedName } }
394 -- -----------------------------------------------------------------------------
397 -- ToDo: think about relative vs. absolute file paths. And what
398 -- happens when the current directory changes.
400 -- | Sets the targets for this session. Each target may be a module name
401 -- or a filename. The targets correspond to the set of root modules for
402 -- the program\/library. Unloading the current program is achieved by
403 -- setting the current set of targets to be empty, followed by load.
404 setTargets :: Session -> [Target] -> IO ()
405 setTargets s targets = modifySession s (\h -> h{ hsc_targets = targets })
407 -- | returns the current set of targets
408 getTargets :: Session -> IO [Target]
409 getTargets s = withSession s (return . hsc_targets)
411 -- | Add another target
412 addTarget :: Session -> Target -> IO ()
414 = modifySession s (\h -> h{ hsc_targets = target : hsc_targets h })
417 removeTarget :: Session -> TargetId -> IO ()
418 removeTarget s target_id
419 = modifySession s (\h -> h{ hsc_targets = filter (hsc_targets h) })
421 filter targets = [ t | t@(Target id _) <- targets, id /= target_id ]
423 -- Attempts to guess what Target a string refers to. This function implements
424 -- the --make/GHCi command-line syntax for filenames:
426 -- - if the string looks like a Haskell source filename, then interpret
428 -- - if adding a .hs or .lhs suffix yields the name of an existing file,
430 -- - otherwise interpret the string as a module name
432 guessTarget :: String -> Maybe Phase -> IO Target
433 guessTarget file (Just phase)
434 = return (Target (TargetFile file (Just phase)) Nothing)
435 guessTarget file Nothing
436 | isHaskellSrcFilename file
437 = return (Target (TargetFile file Nothing) Nothing)
439 = do exists <- doesFileExist hs_file
441 then return (Target (TargetFile hs_file Nothing) Nothing)
443 exists <- doesFileExist lhs_file
445 then return (Target (TargetFile lhs_file Nothing) Nothing)
447 return (Target (TargetModule (mkModuleName file)) Nothing)
449 hs_file = file `joinFileExt` "hs"
450 lhs_file = file `joinFileExt` "lhs"
452 -- -----------------------------------------------------------------------------
453 -- Extending the program scope
455 extendGlobalRdrScope :: Session -> [GlobalRdrElt] -> IO ()
456 extendGlobalRdrScope session rdrElts
457 = modifySession session $ \hscEnv ->
458 let global_rdr = hsc_global_rdr_env hscEnv
459 in hscEnv{ hsc_global_rdr_env = foldl extendGlobalRdrEnv global_rdr rdrElts }
461 setGlobalRdrScope :: Session -> [GlobalRdrElt] -> IO ()
462 setGlobalRdrScope session rdrElts
463 = modifySession session $ \hscEnv ->
464 hscEnv{ hsc_global_rdr_env = foldl extendGlobalRdrEnv emptyGlobalRdrEnv rdrElts }
466 extendGlobalTypeScope :: Session -> [Id] -> IO ()
467 extendGlobalTypeScope session ids
468 = modifySession session $ \hscEnv ->
469 let global_type = hsc_global_type_env hscEnv
470 in hscEnv{ hsc_global_type_env = extendTypeEnvWithIds global_type ids }
472 setGlobalTypeScope :: Session -> [Id] -> IO ()
473 setGlobalTypeScope session ids
474 = modifySession session $ \hscEnv ->
475 hscEnv{ hsc_global_type_env = extendTypeEnvWithIds emptyTypeEnv ids }
477 -- -----------------------------------------------------------------------------
478 -- Loading the program
480 -- Perform a dependency analysis starting from the current targets
481 -- and update the session with the new module graph.
482 depanal :: Session -> [ModuleName] -> Bool -> IO (Maybe ModuleGraph)
483 depanal (Session ref) excluded_mods allow_dup_roots = do
484 hsc_env <- readIORef ref
486 dflags = hsc_dflags hsc_env
487 gmode = ghcMode (hsc_dflags hsc_env)
488 targets = hsc_targets hsc_env
489 old_graph = hsc_mod_graph hsc_env
491 showPass dflags "Chasing dependencies"
492 when (gmode == BatchCompile) $
493 debugTraceMsg dflags 2 (hcat [
494 text "Chasing modules from: ",
495 hcat (punctuate comma (map pprTarget targets))])
497 r <- downsweep hsc_env old_graph excluded_mods allow_dup_roots
499 Just mod_graph -> writeIORef ref hsc_env{ hsc_mod_graph = mod_graph }
504 -- | The result of load.
506 = LoadOk Errors -- ^ all specified targets were loaded successfully.
507 | LoadFailed Errors -- ^ not all modules were loaded.
509 type Errors = [String]
511 data ErrMsg = ErrMsg {
512 errMsgSeverity :: Severity, -- warning, error, etc.
513 errMsgSpans :: [SrcSpan],
514 errMsgShortDoc :: Doc,
515 errMsgExtraInfo :: Doc
521 | LoadUpTo ModuleName
522 | LoadDependenciesOf ModuleName
524 -- | Try to load the program. If a Module is supplied, then just
525 -- attempt to load up to this target. If no Module is supplied,
526 -- then try to load all targets.
527 load :: Session -> LoadHowMuch -> IO SuccessFlag
528 load s@(Session ref) how_much
530 -- Dependency analysis first. Note that this fixes the module graph:
531 -- even if we don't get a fully successful upsweep, the full module
532 -- graph is still retained in the Session. We can tell which modules
533 -- were successfully loaded by inspecting the Session's HPT.
534 mb_graph <- depanal s [] False
536 Just mod_graph -> load2 s how_much mod_graph
537 Nothing -> return Failed
539 load2 s@(Session ref) how_much mod_graph = do
541 hsc_env <- readIORef ref
543 let hpt1 = hsc_HPT hsc_env
544 let dflags = hsc_dflags hsc_env
545 let ghci_mode = ghcMode dflags -- this never changes
547 -- The "bad" boot modules are the ones for which we have
548 -- B.hs-boot in the module graph, but no B.hs
549 -- The downsweep should have ensured this does not happen
551 let all_home_mods = [ms_mod_name s
552 | s <- mod_graph, not (isBootSummary s)]
554 bad_boot_mods = [s | s <- mod_graph, isBootSummary s,
555 not (ms_mod_name s `elem` all_home_mods)]
557 ASSERT( null bad_boot_mods ) return ()
559 -- mg2_with_srcimps drops the hi-boot nodes, returning a
560 -- graph with cycles. Among other things, it is used for
561 -- backing out partially complete cycles following a failed
562 -- upsweep, and for removing from hpt all the modules
563 -- not in strict downwards closure, during calls to compile.
564 let mg2_with_srcimps :: [SCC ModSummary]
565 mg2_with_srcimps = topSortModuleGraph True mod_graph Nothing
567 -- If we can determine that any of the {-# SOURCE #-} imports
568 -- are definitely unnecessary, then emit a warning.
569 warnUnnecessarySourceImports dflags mg2_with_srcimps
572 -- check the stability property for each module.
573 stable_mods@(stable_obj,stable_bco)
574 | BatchCompile <- ghci_mode = ([],[])
575 | otherwise = checkStability hpt1 mg2_with_srcimps all_home_mods
577 -- prune bits of the HPT which are definitely redundant now,
579 pruned_hpt = pruneHomePackageTable hpt1
580 (flattenSCCs mg2_with_srcimps)
585 debugTraceMsg dflags 2 (text "Stable obj:" <+> ppr stable_obj $$
586 text "Stable BCO:" <+> ppr stable_bco)
588 -- Unload any modules which are going to be re-linked this time around.
589 let stable_linkables = [ linkable
590 | m <- stable_obj++stable_bco,
591 Just hmi <- [lookupUFM pruned_hpt m],
592 Just linkable <- [hm_linkable hmi] ]
593 unload hsc_env stable_linkables
595 -- We could at this point detect cycles which aren't broken by
596 -- a source-import, and complain immediately, but it seems better
597 -- to let upsweep_mods do this, so at least some useful work gets
598 -- done before the upsweep is abandoned.
599 --hPutStrLn stderr "after tsort:\n"
600 --hPutStrLn stderr (showSDoc (vcat (map ppr mg2)))
602 -- Now do the upsweep, calling compile for each module in
603 -- turn. Final result is version 3 of everything.
605 -- Topologically sort the module graph, this time including hi-boot
606 -- nodes, and possibly just including the portion of the graph
607 -- reachable from the module specified in the 2nd argument to load.
608 -- This graph should be cycle-free.
609 -- If we're restricting the upsweep to a portion of the graph, we
610 -- also want to retain everything that is still stable.
611 let full_mg :: [SCC ModSummary]
612 full_mg = topSortModuleGraph False mod_graph Nothing
614 maybe_top_mod = case how_much of
616 LoadDependenciesOf m -> Just m
619 partial_mg0 :: [SCC ModSummary]
620 partial_mg0 = topSortModuleGraph False mod_graph maybe_top_mod
622 -- LoadDependenciesOf m: we want the upsweep to stop just
623 -- short of the specified module (unless the specified module
626 | LoadDependenciesOf mod <- how_much
627 = ASSERT( case last partial_mg0 of
628 AcyclicSCC ms -> ms_mod_name ms == mod; _ -> False )
629 List.init partial_mg0
635 | AcyclicSCC ms <- full_mg,
636 ms_mod_name ms `elem` stable_obj++stable_bco,
637 ms_mod_name ms `notElem` [ ms_mod_name ms' |
638 AcyclicSCC ms' <- partial_mg ] ]
640 mg = stable_mg ++ partial_mg
642 -- clean up between compilations
643 let cleanup = cleanTempFilesExcept dflags
644 (ppFilesFromSummaries (flattenSCCs mg2_with_srcimps))
646 (upsweep_ok, hsc_env1, modsUpswept)
647 <- upsweep (hsc_env { hsc_HPT = emptyHomePackageTable })
648 pruned_hpt stable_mods cleanup mg
650 -- Make modsDone be the summaries for each home module now
651 -- available; this should equal the domain of hpt3.
652 -- Get in in a roughly top .. bottom order (hence reverse).
654 let modsDone = reverse modsUpswept
656 -- Try and do linking in some form, depending on whether the
657 -- upsweep was completely or only partially successful.
659 if succeeded upsweep_ok
662 -- Easy; just relink it all.
663 do debugTraceMsg dflags 2 (text "Upsweep completely successful.")
665 -- Clean up after ourselves
666 cleanTempFilesExcept dflags (ppFilesFromSummaries modsDone)
668 -- Issue a warning for the confusing case where the user
669 -- said '-o foo' but we're not going to do any linking.
670 -- We attempt linking if either (a) one of the modules is
671 -- called Main, or (b) the user said -no-hs-main, indicating
672 -- that main() is going to come from somewhere else.
674 let ofile = outputFile dflags
675 let no_hs_main = dopt Opt_NoHsMain dflags
677 main_mod = mainModIs dflags
678 a_root_is_Main = any ((==main_mod).ms_mod) mod_graph
679 do_linking = a_root_is_Main || no_hs_main
681 when (ghci_mode == BatchCompile && isJust ofile && not do_linking) $
682 debugTraceMsg dflags 1 (text ("Warning: output was redirected with -o, " ++
683 "but no output will be generated\n" ++
684 "because there is no " ++ moduleNameString (moduleName main_mod) ++ " module."))
686 -- link everything together
687 linkresult <- link ghci_mode dflags do_linking (hsc_HPT hsc_env1)
689 loadFinish Succeeded linkresult ref hsc_env1
692 -- Tricky. We need to back out the effects of compiling any
693 -- half-done cycles, both so as to clean up the top level envs
694 -- and to avoid telling the interactive linker to link them.
695 do debugTraceMsg dflags 2 (text "Upsweep partially successful.")
698 = map ms_mod modsDone
699 let mods_to_zap_names
700 = findPartiallyCompletedCycles modsDone_names
703 = filter ((`notElem` mods_to_zap_names).ms_mod)
706 let hpt4 = retainInTopLevelEnvs (map ms_mod_name mods_to_keep)
709 -- Clean up after ourselves
710 cleanTempFilesExcept dflags (ppFilesFromSummaries mods_to_keep)
712 -- there should be no Nothings where linkables should be, now
713 ASSERT(all (isJust.hm_linkable)
714 (eltsUFM (hsc_HPT hsc_env))) do
716 -- Link everything together
717 linkresult <- link ghci_mode dflags False hpt4
719 let hsc_env4 = hsc_env1{ hsc_HPT = hpt4 }
720 loadFinish Failed linkresult ref hsc_env4
722 -- Finish up after a load.
724 -- If the link failed, unload everything and return.
725 loadFinish all_ok Failed ref hsc_env
726 = do unload hsc_env []
727 writeIORef ref $! discardProg hsc_env
730 -- Empty the interactive context and set the module context to the topmost
731 -- newly loaded module, or the Prelude if none were loaded.
732 loadFinish all_ok Succeeded ref hsc_env
733 = do writeIORef ref $! hsc_env{ hsc_IC = emptyInteractiveContext }
737 -- Forget the current program, but retain the persistent info in HscEnv
738 discardProg :: HscEnv -> HscEnv
740 = hsc_env { hsc_mod_graph = emptyMG,
741 hsc_IC = emptyInteractiveContext,
742 hsc_HPT = emptyHomePackageTable }
744 -- used to fish out the preprocess output files for the purposes of
745 -- cleaning up. The preprocessed file *might* be the same as the
746 -- source file, but that doesn't do any harm.
747 ppFilesFromSummaries summaries = map ms_hspp_file summaries
749 -- -----------------------------------------------------------------------------
753 CheckedModule { parsedSource :: ParsedSource,
754 renamedSource :: Maybe RenamedSource,
755 typecheckedSource :: Maybe TypecheckedSource,
756 checkedModuleInfo :: Maybe ModuleInfo
758 -- ToDo: improvements that could be made here:
759 -- if the module succeeded renaming but not typechecking,
760 -- we can still get back the GlobalRdrEnv and exports, so
761 -- perhaps the ModuleInfo should be split up into separate
762 -- fields within CheckedModule.
764 type ParsedSource = Located (HsModule RdrName)
765 type RenamedSource = (HsGroup Name, [LImportDecl Name], Maybe [LIE Name])
766 type TypecheckedSource = LHsBinds Id
769 -- - things that aren't in the output of the typechecker right now:
773 -- - type/data/newtype declarations
774 -- - class declarations
776 -- - extra things in the typechecker's output:
777 -- - default methods are turned into top-level decls.
778 -- - dictionary bindings
781 -- | This is the way to get access to parsed and typechecked source code
782 -- for a module. 'checkModule' loads all the dependencies of the specified
783 -- module in the Session, and then attempts to typecheck the module. If
784 -- successful, it returns the abstract syntax for the module.
785 checkModule :: Session -> ModuleName -> IO (Maybe CheckedModule)
786 checkModule session@(Session ref) mod = do
787 -- load up the dependencies first
788 r <- load session (LoadDependenciesOf mod)
789 if (failed r) then return Nothing else do
791 -- now parse & typecheck the module
792 hsc_env <- readIORef ref
793 let mg = hsc_mod_graph hsc_env
794 case [ ms | ms <- mg, ms_mod_name ms == mod ] of
797 mbChecked <- hscFileCheck hsc_env{hsc_dflags=ms_hspp_opts ms} ms
799 Nothing -> return Nothing
800 Just (HscChecked parsed renamed Nothing) ->
801 return (Just (CheckedModule {
802 parsedSource = parsed,
803 renamedSource = renamed,
804 typecheckedSource = Nothing,
805 checkedModuleInfo = Nothing }))
806 Just (HscChecked parsed renamed
807 (Just (tc_binds, rdr_env, details))) -> do
808 let minf = ModuleInfo {
809 minf_type_env = md_types details,
810 minf_exports = md_exports details,
811 minf_rdr_env = Just rdr_env,
812 minf_instances = md_insts details
814 return (Just (CheckedModule {
815 parsedSource = parsed,
816 renamedSource = renamed,
817 typecheckedSource = Just tc_binds,
818 checkedModuleInfo = Just minf }))
820 -- ---------------------------------------------------------------------------
823 unload :: HscEnv -> [Linkable] -> IO ()
824 unload hsc_env stable_linkables -- Unload everthing *except* 'stable_linkables'
825 = case ghcMode (hsc_dflags hsc_env) of
826 BatchCompile -> return ()
827 JustTypecheck -> return ()
829 Interactive -> Linker.unload (hsc_dflags hsc_env) stable_linkables
831 Interactive -> panic "unload: no interpreter"
833 other -> panic "unload: strange mode"
835 -- -----------------------------------------------------------------------------
839 Stability tells us which modules definitely do not need to be recompiled.
840 There are two main reasons for having stability:
842 - avoid doing a complete upsweep of the module graph in GHCi when
843 modules near the bottom of the tree have not changed.
845 - to tell GHCi when it can load object code: we can only load object code
846 for a module when we also load object code fo all of the imports of the
847 module. So we need to know that we will definitely not be recompiling
848 any of these modules, and we can use the object code.
850 NB. stability is of no importance to BatchCompile at all, only Interactive.
851 (ToDo: what about JustTypecheck?)
853 The stability check is as follows. Both stableObject and
854 stableBCO are used during the upsweep phase later.
857 stable m = stableObject m || stableBCO m
860 all stableObject (imports m)
861 && old linkable does not exist, or is == on-disk .o
862 && date(on-disk .o) > date(.hs)
865 all stable (imports m)
866 && date(BCO) > date(.hs)
869 These properties embody the following ideas:
871 - if a module is stable:
872 - if it has been compiled in a previous pass (present in HPT)
873 then it does not need to be compiled or re-linked.
874 - if it has not been compiled in a previous pass,
875 then we only need to read its .hi file from disk and
876 link it to produce a ModDetails.
878 - if a modules is not stable, we will definitely be at least
879 re-linking, and possibly re-compiling it during the upsweep.
880 All non-stable modules can (and should) therefore be unlinked
883 - Note that objects are only considered stable if they only depend
884 on other objects. We can't link object code against byte code.
888 :: HomePackageTable -- HPT from last compilation
889 -> [SCC ModSummary] -- current module graph (cyclic)
890 -> [ModuleName] -- all home modules
891 -> ([ModuleName], -- stableObject
892 [ModuleName]) -- stableBCO
894 checkStability hpt sccs all_home_mods = foldl checkSCC ([],[]) sccs
896 checkSCC (stable_obj, stable_bco) scc0
897 | stableObjects = (scc_mods ++ stable_obj, stable_bco)
898 | stableBCOs = (stable_obj, scc_mods ++ stable_bco)
899 | otherwise = (stable_obj, stable_bco)
901 scc = flattenSCC scc0
902 scc_mods = map ms_mod_name scc
903 home_module m = m `elem` all_home_mods && m `notElem` scc_mods
905 scc_allimps = nub (filter home_module (concatMap ms_allimps scc))
906 -- all imports outside the current SCC, but in the home pkg
908 stable_obj_imps = map (`elem` stable_obj) scc_allimps
909 stable_bco_imps = map (`elem` stable_bco) scc_allimps
916 and (zipWith (||) stable_obj_imps stable_bco_imps)
920 | Just t <- ms_obj_date ms = t >= ms_hs_date ms
924 same_as_prev t = case lookupUFM hpt (ms_mod_name ms) of
925 Just hmi | Just l <- hm_linkable hmi
926 -> isObjectLinkable l && t == linkableTime l
928 -- why '>=' rather than '>' above? If the filesystem stores
929 -- times to the nearset second, we may occasionally find that
930 -- the object & source have the same modification time,
931 -- especially if the source was automatically generated
932 -- and compiled. Using >= is slightly unsafe, but it matches
936 = case lookupUFM hpt (ms_mod_name ms) of
937 Just hmi | Just l <- hm_linkable hmi ->
938 not (isObjectLinkable l) &&
939 linkableTime l >= ms_hs_date ms
942 ms_allimps :: ModSummary -> [ModuleName]
943 ms_allimps ms = map unLoc (ms_srcimps ms ++ ms_imps ms)
945 -- -----------------------------------------------------------------------------
946 -- Prune the HomePackageTable
948 -- Before doing an upsweep, we can throw away:
950 -- - For non-stable modules:
951 -- - all ModDetails, all linked code
952 -- - all unlinked code that is out of date with respect to
955 -- This is VERY IMPORTANT otherwise we'll end up requiring 2x the
956 -- space at the end of the upsweep, because the topmost ModDetails of the
957 -- old HPT holds on to the entire type environment from the previous
960 pruneHomePackageTable
963 -> ([ModuleName],[ModuleName])
966 pruneHomePackageTable hpt summ (stable_obj, stable_bco)
969 | is_stable modl = hmi'
970 | otherwise = hmi'{ hm_details = emptyModDetails }
972 modl = moduleName (mi_module (hm_iface hmi))
973 hmi' | Just l <- hm_linkable hmi, linkableTime l < ms_hs_date ms
974 = hmi{ hm_linkable = Nothing }
977 where ms = expectJust "prune" (lookupUFM ms_map modl)
979 ms_map = listToUFM [(ms_mod_name ms, ms) | ms <- summ]
981 is_stable m = m `elem` stable_obj || m `elem` stable_bco
983 -- -----------------------------------------------------------------------------
985 -- Return (names of) all those in modsDone who are part of a cycle
986 -- as defined by theGraph.
987 findPartiallyCompletedCycles :: [Module] -> [SCC ModSummary] -> [Module]
988 findPartiallyCompletedCycles modsDone theGraph
992 chew ((AcyclicSCC v):rest) = chew rest -- acyclic? not interesting.
993 chew ((CyclicSCC vs):rest)
994 = let names_in_this_cycle = nub (map ms_mod vs)
996 = nub ([done | done <- modsDone,
997 done `elem` names_in_this_cycle])
998 chewed_rest = chew rest
1000 if notNull mods_in_this_cycle
1001 && length mods_in_this_cycle < length names_in_this_cycle
1002 then mods_in_this_cycle ++ chewed_rest
1005 -- -----------------------------------------------------------------------------
1008 -- This is where we compile each module in the module graph, in a pass
1009 -- from the bottom to the top of the graph.
1011 -- There better had not be any cyclic groups here -- we check for them.
1014 :: HscEnv -- Includes initially-empty HPT
1015 -> HomePackageTable -- HPT from last time round (pruned)
1016 -> ([ModuleName],[ModuleName]) -- stable modules (see checkStability)
1017 -> IO () -- How to clean up unwanted tmp files
1018 -> [SCC ModSummary] -- Mods to do (the worklist)
1020 HscEnv, -- With an updated HPT
1021 [ModSummary]) -- Mods which succeeded
1023 upsweep hsc_env old_hpt stable_mods cleanup mods
1024 = upsweep' hsc_env old_hpt stable_mods cleanup mods 1 (length mods)
1026 upsweep' hsc_env old_hpt stable_mods cleanup
1028 = return (Succeeded, hsc_env, [])
1030 upsweep' hsc_env old_hpt stable_mods cleanup
1031 (CyclicSCC ms:_) _ _
1032 = do fatalErrorMsg (hsc_dflags hsc_env) (cyclicModuleErr ms)
1033 return (Failed, hsc_env, [])
1035 upsweep' hsc_env old_hpt stable_mods cleanup
1036 (AcyclicSCC mod:mods) mod_index nmods
1037 = do -- putStrLn ("UPSWEEP_MOD: hpt = " ++
1038 -- show (map (moduleUserString.moduleName.mi_module.hm_iface)
1039 -- (moduleEnvElts (hsc_HPT hsc_env)))
1041 mb_mod_info <- upsweep_mod hsc_env old_hpt stable_mods mod
1044 cleanup -- Remove unwanted tmp files between compilations
1047 Nothing -> return (Failed, hsc_env, [])
1049 { let this_mod = ms_mod_name mod
1051 -- Add new info to hsc_env
1052 hpt1 = addToUFM (hsc_HPT hsc_env) this_mod mod_info
1053 hsc_env1 = hsc_env { hsc_HPT = hpt1 }
1055 -- Space-saving: delete the old HPT entry
1056 -- for mod BUT if mod is a hs-boot
1057 -- node, don't delete it. For the
1058 -- interface, the HPT entry is probaby for the
1059 -- main Haskell source file. Deleting it
1060 -- would force .. (what?? --SDM)
1061 old_hpt1 | isBootSummary mod = old_hpt
1062 | otherwise = delFromUFM old_hpt this_mod
1064 ; (restOK, hsc_env2, modOKs)
1065 <- upsweep' hsc_env1 old_hpt1 stable_mods cleanup
1066 mods (mod_index+1) nmods
1067 ; return (restOK, hsc_env2, mod:modOKs)
1071 -- Compile a single module. Always produce a Linkable for it if
1072 -- successful. If no compilation happened, return the old Linkable.
1073 upsweep_mod :: HscEnv
1075 -> ([ModuleName],[ModuleName])
1077 -> Int -- index of module
1078 -> Int -- total number of modules
1079 -> IO (Maybe HomeModInfo) -- Nothing => Failed
1081 upsweep_mod hsc_env old_hpt (stable_obj, stable_bco) summary mod_index nmods
1084 this_mod_name = ms_mod_name summary
1085 this_mod = ms_mod summary
1086 mb_obj_date = ms_obj_date summary
1087 obj_fn = ml_obj_file (ms_location summary)
1088 hs_date = ms_hs_date summary
1090 compile_it :: Maybe Linkable -> IO (Maybe HomeModInfo)
1091 compile_it = upsweep_compile hsc_env old_hpt this_mod_name
1092 summary mod_index nmods
1094 case ghcMode (hsc_dflags hsc_env) of
1097 -- Batch-compilating is easy: just check whether we have
1098 -- an up-to-date object file. If we do, then the compiler
1099 -- needs to do a recompilation check.
1100 _ | Just obj_date <- mb_obj_date, obj_date >= hs_date -> do
1102 findObjectLinkable this_mod obj_fn obj_date
1103 compile_it (Just linkable)
1110 _ | is_stable_obj, isJust old_hmi ->
1112 -- object is stable, and we have an entry in the
1113 -- old HPT: nothing to do
1115 | is_stable_obj, isNothing old_hmi -> do
1117 findObjectLinkable this_mod obj_fn
1118 (expectJust "upseep1" mb_obj_date)
1119 compile_it (Just linkable)
1120 -- object is stable, but we need to load the interface
1121 -- off disk to make a HMI.
1124 ASSERT(isJust old_hmi) -- must be in the old_hpt
1126 -- BCO is stable: nothing to do
1128 | Just hmi <- old_hmi,
1129 Just l <- hm_linkable hmi, not (isObjectLinkable l),
1130 linkableTime l >= ms_hs_date summary ->
1132 -- we have an old BCO that is up to date with respect
1133 -- to the source: do a recompilation check as normal.
1137 -- no existing code at all: we must recompile.
1139 is_stable_obj = this_mod_name `elem` stable_obj
1140 is_stable_bco = this_mod_name `elem` stable_bco
1142 old_hmi = lookupUFM old_hpt this_mod_name
1144 -- Run hsc to compile a module
1145 upsweep_compile hsc_env old_hpt this_mod summary
1147 mb_old_linkable = do
1149 -- The old interface is ok if it's in the old HPT
1150 -- a) we're compiling a source file, and the old HPT
1151 -- entry is for a source file
1152 -- b) we're compiling a hs-boot file
1153 -- Case (b) allows an hs-boot file to get the interface of its
1154 -- real source file on the second iteration of the compilation
1155 -- manager, but that does no harm. Otherwise the hs-boot file
1156 -- will always be recompiled
1159 = case lookupUFM old_hpt this_mod of
1161 Just hm_info | isBootSummary summary -> Just iface
1162 | not (mi_boot iface) -> Just iface
1163 | otherwise -> Nothing
1165 iface = hm_iface hm_info
1167 compresult <- compile hsc_env summary mb_old_linkable mb_old_iface
1171 -- Compilation failed. Compile may still have updated the PCS, tho.
1172 CompErrs -> return Nothing
1174 -- Compilation "succeeded", and may or may not have returned a new
1175 -- linkable (depending on whether compilation was actually performed
1177 CompOK new_details new_iface new_linkable
1178 -> do let new_info = HomeModInfo { hm_iface = new_iface,
1179 hm_details = new_details,
1180 hm_linkable = new_linkable }
1181 return (Just new_info)
1184 -- Filter modules in the HPT
1185 retainInTopLevelEnvs :: [ModuleName] -> HomePackageTable -> HomePackageTable
1186 retainInTopLevelEnvs keep_these hpt
1187 = listToUFM [ (mod, expectJust "retain" mb_mod_info)
1189 , let mb_mod_info = lookupUFM hpt mod
1190 , isJust mb_mod_info ]
1192 -- ---------------------------------------------------------------------------
1193 -- Topological sort of the module graph
1196 :: Bool -- Drop hi-boot nodes? (see below)
1200 -- Calculate SCCs of the module graph, possibly dropping the hi-boot nodes
1201 -- The resulting list of strongly-connected-components is in topologically
1202 -- sorted order, starting with the module(s) at the bottom of the
1203 -- dependency graph (ie compile them first) and ending with the ones at
1206 -- Drop hi-boot nodes (first boolean arg)?
1208 -- False: treat the hi-boot summaries as nodes of the graph,
1209 -- so the graph must be acyclic
1211 -- True: eliminate the hi-boot nodes, and instead pretend
1212 -- the a source-import of Foo is an import of Foo
1213 -- The resulting graph has no hi-boot nodes, but can by cyclic
1215 topSortModuleGraph drop_hs_boot_nodes summaries Nothing
1216 = stronglyConnComp (fst (moduleGraphNodes drop_hs_boot_nodes summaries))
1217 topSortModuleGraph drop_hs_boot_nodes summaries (Just mod)
1218 = stronglyConnComp (map vertex_fn (reachable graph root))
1220 -- restrict the graph to just those modules reachable from
1221 -- the specified module. We do this by building a graph with
1222 -- the full set of nodes, and determining the reachable set from
1223 -- the specified node.
1224 (nodes, lookup_key) = moduleGraphNodes drop_hs_boot_nodes summaries
1225 (graph, vertex_fn, key_fn) = graphFromEdges' nodes
1227 | Just key <- lookup_key HsSrcFile mod, Just v <- key_fn key = v
1228 | otherwise = throwDyn (ProgramError "module does not exist")
1230 moduleGraphNodes :: Bool -> [ModSummary]
1231 -> ([(ModSummary, Int, [Int])], HscSource -> ModuleName -> Maybe Int)
1232 moduleGraphNodes drop_hs_boot_nodes summaries = (nodes, lookup_key)
1234 -- Drop hs-boot nodes by using HsSrcFile as the key
1235 hs_boot_key | drop_hs_boot_nodes = HsSrcFile
1236 | otherwise = HsBootFile
1238 -- We use integers as the keys for the SCC algorithm
1239 nodes :: [(ModSummary, Int, [Int])]
1240 nodes = [(s, expectJust "topSort" $
1241 lookup_key (ms_hsc_src s) (ms_mod_name s),
1242 out_edge_keys hs_boot_key (map unLoc (ms_srcimps s)) ++
1243 out_edge_keys HsSrcFile (map unLoc (ms_imps s)) ++
1244 (-- see [boot-edges] below
1245 if drop_hs_boot_nodes || ms_hsc_src s == HsBootFile
1247 else case lookup_key HsBootFile (ms_mod_name s) of
1252 , not (isBootSummary s && drop_hs_boot_nodes) ]
1253 -- Drop the hi-boot ones if told to do so
1255 -- [boot-edges] if this is a .hs and there is an equivalent
1256 -- .hs-boot, add a link from the former to the latter. This
1257 -- has the effect of detecting bogus cases where the .hs-boot
1258 -- depends on the .hs, by introducing a cycle. Additionally,
1259 -- it ensures that we will always process the .hs-boot before
1260 -- the .hs, and so the HomePackageTable will always have the
1261 -- most up to date information.
1263 key_map :: NodeMap Int
1264 key_map = listToFM ([(moduleName (ms_mod s), ms_hsc_src s)
1268 lookup_key :: HscSource -> ModuleName -> Maybe Int
1269 lookup_key hs_src mod = lookupFM key_map (mod, hs_src)
1271 out_edge_keys :: HscSource -> [ModuleName] -> [Int]
1272 out_edge_keys hi_boot ms = mapCatMaybes (lookup_key hi_boot) ms
1273 -- If we want keep_hi_boot_nodes, then we do lookup_key with
1274 -- the IsBootInterface parameter True; else False
1277 type NodeKey = (ModuleName, HscSource) -- The nodes of the graph are
1278 type NodeMap a = FiniteMap NodeKey a -- keyed by (mod, src_file_type) pairs
1280 msKey :: ModSummary -> NodeKey
1281 msKey (ModSummary { ms_mod = mod, ms_hsc_src = boot }) = (moduleName mod,boot)
1283 mkNodeMap :: [ModSummary] -> NodeMap ModSummary
1284 mkNodeMap summaries = listToFM [ (msKey s, s) | s <- summaries]
1286 nodeMapElts :: NodeMap a -> [a]
1287 nodeMapElts = eltsFM
1289 ms_mod_name :: ModSummary -> ModuleName
1290 ms_mod_name = moduleName . ms_mod
1292 -- If there are {-# SOURCE #-} imports between strongly connected
1293 -- components in the topological sort, then those imports can
1294 -- definitely be replaced by ordinary non-SOURCE imports: if SOURCE
1295 -- were necessary, then the edge would be part of a cycle.
1296 warnUnnecessarySourceImports :: DynFlags -> [SCC ModSummary] -> IO ()
1297 warnUnnecessarySourceImports dflags sccs =
1298 printBagOfWarnings dflags (listToBag (concat (map (check.flattenSCC) sccs)))
1300 let mods_in_this_cycle = map ms_mod_name ms in
1301 [ warn m i | m <- ms, i <- ms_srcimps m,
1302 unLoc i `notElem` mods_in_this_cycle ]
1304 warn :: ModSummary -> Located ModuleName -> WarnMsg
1305 warn ms (L loc mod) =
1307 (ptext SLIT("Warning: {-# SOURCE #-} unnecessary in import of ")
1308 <+> quotes (ppr mod))
1310 -----------------------------------------------------------------------------
1311 -- Downsweep (dependency analysis)
1313 -- Chase downwards from the specified root set, returning summaries
1314 -- for all home modules encountered. Only follow source-import
1317 -- We pass in the previous collection of summaries, which is used as a
1318 -- cache to avoid recalculating a module summary if the source is
1321 -- The returned list of [ModSummary] nodes has one node for each home-package
1322 -- module, plus one for any hs-boot files. The imports of these nodes
1323 -- are all there, including the imports of non-home-package modules.
1326 -> [ModSummary] -- Old summaries
1327 -> [ModuleName] -- Ignore dependencies on these; treat
1328 -- them as if they were package modules
1329 -> Bool -- True <=> allow multiple targets to have
1330 -- the same module name; this is
1331 -- very useful for ghc -M
1332 -> IO (Maybe [ModSummary])
1333 -- The elts of [ModSummary] all have distinct
1334 -- (Modules, IsBoot) identifiers, unless the Bool is true
1335 -- in which case there can be repeats
1336 downsweep hsc_env old_summaries excl_mods allow_dup_roots
1337 = -- catch error messages and return them
1338 handleDyn (\err_msg -> printBagOfErrors (hsc_dflags hsc_env) (unitBag err_msg) >> return Nothing) $ do
1339 rootSummaries <- mapM getRootSummary roots
1340 let root_map = mkRootMap rootSummaries
1341 checkDuplicates root_map
1342 summs <- loop (concatMap msDeps rootSummaries) root_map
1345 roots = hsc_targets hsc_env
1347 old_summary_map :: NodeMap ModSummary
1348 old_summary_map = mkNodeMap old_summaries
1350 getRootSummary :: Target -> IO ModSummary
1351 getRootSummary (Target (TargetFile file mb_phase) maybe_buf)
1352 = do exists <- doesFileExist file
1354 then summariseFile hsc_env old_summaries file mb_phase maybe_buf
1355 else throwDyn $ mkPlainErrMsg noSrcSpan $
1356 text "can't find file:" <+> text file
1357 getRootSummary (Target (TargetModule modl) maybe_buf)
1358 = do maybe_summary <- summariseModule hsc_env old_summary_map False
1359 (L rootLoc modl) maybe_buf excl_mods
1360 case maybe_summary of
1361 Nothing -> packageModErr modl
1364 rootLoc = mkGeneralSrcSpan FSLIT("<command line>")
1366 -- In a root module, the filename is allowed to diverge from the module
1367 -- name, so we have to check that there aren't multiple root files
1368 -- defining the same module (otherwise the duplicates will be silently
1369 -- ignored, leading to confusing behaviour).
1370 checkDuplicates :: NodeMap [ModSummary] -> IO ()
1371 checkDuplicates root_map
1372 | allow_dup_roots = return ()
1373 | null dup_roots = return ()
1374 | otherwise = multiRootsErr (head dup_roots)
1376 dup_roots :: [[ModSummary]] -- Each at least of length 2
1377 dup_roots = filterOut isSingleton (nodeMapElts root_map)
1379 loop :: [(Located ModuleName,IsBootInterface)]
1380 -- Work list: process these modules
1381 -> NodeMap [ModSummary]
1382 -- Visited set; the range is a list because
1383 -- the roots can have the same module names
1384 -- if allow_dup_roots is True
1386 -- The result includes the worklist, except
1387 -- for those mentioned in the visited set
1388 loop [] done = return (concat (nodeMapElts done))
1389 loop ((wanted_mod, is_boot) : ss) done
1390 | Just summs <- lookupFM done key
1391 = if isSingleton summs then
1394 do { multiRootsErr summs; return [] }
1395 | otherwise = do { mb_s <- summariseModule hsc_env old_summary_map
1396 is_boot wanted_mod Nothing excl_mods
1398 Nothing -> loop ss done
1399 Just s -> loop (msDeps s ++ ss)
1400 (addToFM done key [s]) }
1402 key = (unLoc wanted_mod, if is_boot then HsBootFile else HsSrcFile)
1404 mkRootMap :: [ModSummary] -> NodeMap [ModSummary]
1405 mkRootMap summaries = addListToFM_C (++) emptyFM
1406 [ (msKey s, [s]) | s <- summaries ]
1408 msDeps :: ModSummary -> [(Located ModuleName, IsBootInterface)]
1409 -- (msDeps s) returns the dependencies of the ModSummary s.
1410 -- A wrinkle is that for a {-# SOURCE #-} import we return
1411 -- *both* the hs-boot file
1412 -- *and* the source file
1413 -- as "dependencies". That ensures that the list of all relevant
1414 -- modules always contains B.hs if it contains B.hs-boot.
1415 -- Remember, this pass isn't doing the topological sort. It's
1416 -- just gathering the list of all relevant ModSummaries
1418 concat [ [(m,True), (m,False)] | m <- ms_srcimps s ]
1419 ++ [ (m,False) | m <- ms_imps s ]
1421 -----------------------------------------------------------------------------
1422 -- Summarising modules
1424 -- We have two types of summarisation:
1426 -- * Summarise a file. This is used for the root module(s) passed to
1427 -- cmLoadModules. The file is read, and used to determine the root
1428 -- module name. The module name may differ from the filename.
1430 -- * Summarise a module. We are given a module name, and must provide
1431 -- a summary. The finder is used to locate the file in which the module
1436 -> [ModSummary] -- old summaries
1437 -> FilePath -- source file name
1438 -> Maybe Phase -- start phase
1439 -> Maybe (StringBuffer,ClockTime)
1442 summariseFile hsc_env old_summaries file mb_phase maybe_buf
1443 -- we can use a cached summary if one is available and the
1444 -- source file hasn't changed, But we have to look up the summary
1445 -- by source file, rather than module name as we do in summarise.
1446 | Just old_summary <- findSummaryBySourceFile old_summaries file
1448 let location = ms_location old_summary
1450 -- return the cached summary if the source didn't change
1451 src_timestamp <- case maybe_buf of
1452 Just (_,t) -> return t
1453 Nothing -> getModificationTime file
1454 -- The file exists; we checked in getRootSummary above.
1455 -- If it gets removed subsequently, then this
1456 -- getModificationTime may fail, but that's the right
1459 if ms_hs_date old_summary == src_timestamp
1460 then do -- update the object-file timestamp
1461 obj_timestamp <- getObjTimestamp location False
1462 return old_summary{ ms_obj_date = obj_timestamp }
1470 let dflags = hsc_dflags hsc_env
1472 (dflags', hspp_fn, buf)
1473 <- preprocessFile dflags file mb_phase maybe_buf
1475 (srcimps,the_imps, L _ mod_name) <- getImports dflags' buf hspp_fn
1477 -- Make a ModLocation for this file
1478 location <- mkHomeModLocation dflags mod_name file
1480 -- Tell the Finder cache where it is, so that subsequent calls
1481 -- to findModule will find it, even if it's not on any search path
1482 mod <- addHomeModuleToFinder hsc_env mod_name location
1484 src_timestamp <- case maybe_buf of
1485 Just (_,t) -> return t
1486 Nothing -> getModificationTime file
1487 -- getMofificationTime may fail
1489 obj_timestamp <- modificationTimeIfExists (ml_obj_file location)
1491 return (ModSummary { ms_mod = mod, ms_hsc_src = HsSrcFile,
1492 ms_location = location,
1493 ms_hspp_file = hspp_fn,
1494 ms_hspp_opts = dflags',
1495 ms_hspp_buf = Just buf,
1496 ms_srcimps = srcimps, ms_imps = the_imps,
1497 ms_hs_date = src_timestamp,
1498 ms_obj_date = obj_timestamp })
1500 findSummaryBySourceFile :: [ModSummary] -> FilePath -> Maybe ModSummary
1501 findSummaryBySourceFile summaries file
1502 = case [ ms | ms <- summaries, HsSrcFile <- [ms_hsc_src ms],
1503 expectJust "findSummaryBySourceFile" (ml_hs_file (ms_location ms)) == file ] of
1507 -- Summarise a module, and pick up source and timestamp.
1510 -> NodeMap ModSummary -- Map of old summaries
1511 -> IsBootInterface -- True <=> a {-# SOURCE #-} import
1512 -> Located ModuleName -- Imported module to be summarised
1513 -> Maybe (StringBuffer, ClockTime)
1514 -> [ModuleName] -- Modules to exclude
1515 -> IO (Maybe ModSummary) -- Its new summary
1517 summariseModule hsc_env old_summary_map is_boot (L loc wanted_mod) maybe_buf excl_mods
1518 | wanted_mod `elem` excl_mods
1521 | Just old_summary <- lookupFM old_summary_map (wanted_mod, hsc_src)
1522 = do -- Find its new timestamp; all the
1523 -- ModSummaries in the old map have valid ml_hs_files
1524 let location = ms_location old_summary
1525 src_fn = expectJust "summariseModule" (ml_hs_file location)
1527 -- check the modification time on the source file, and
1528 -- return the cached summary if it hasn't changed. If the
1529 -- file has disappeared, we need to call the Finder again.
1531 Just (_,t) -> check_timestamp old_summary location src_fn t
1533 m <- System.IO.Error.try (getModificationTime src_fn)
1535 Right t -> check_timestamp old_summary location src_fn t
1536 Left e | isDoesNotExistError e -> find_it
1537 | otherwise -> ioError e
1539 | otherwise = find_it
1541 dflags = hsc_dflags hsc_env
1543 hsc_src = if is_boot then HsBootFile else HsSrcFile
1545 check_timestamp old_summary location src_fn src_timestamp
1546 | ms_hs_date old_summary == src_timestamp = do
1547 -- update the object-file timestamp
1548 obj_timestamp <- getObjTimestamp location is_boot
1549 return (Just old_summary{ ms_obj_date = obj_timestamp })
1551 -- source changed: re-summarise.
1552 new_summary location (ms_mod old_summary) src_fn src_timestamp
1555 -- Don't use the Finder's cache this time. If the module was
1556 -- previously a package module, it may have now appeared on the
1557 -- search path, so we want to consider it to be a home module. If
1558 -- the module was previously a home module, it may have moved.
1559 uncacheModule hsc_env wanted_mod
1560 found <- findImportedModule hsc_env wanted_mod Nothing
1563 | isJust (ml_hs_file location) ->
1565 just_found location mod
1567 -- Drop external-pkg
1568 ASSERT(modulePackageId mod /= thisPackage dflags)
1572 err -> noModError dflags loc wanted_mod err
1575 just_found location mod = do
1576 -- Adjust location to point to the hs-boot source file,
1577 -- hi file, object file, when is_boot says so
1578 let location' | is_boot = addBootSuffixLocn location
1579 | otherwise = location
1580 src_fn = expectJust "summarise2" (ml_hs_file location')
1582 -- Check that it exists
1583 -- It might have been deleted since the Finder last found it
1584 maybe_t <- modificationTimeIfExists src_fn
1586 Nothing -> noHsFileErr loc src_fn
1587 Just t -> new_summary location' mod src_fn t
1590 new_summary location mod src_fn src_timestamp
1592 -- Preprocess the source file and get its imports
1593 -- The dflags' contains the OPTIONS pragmas
1594 (dflags', hspp_fn, buf) <- preprocessFile dflags src_fn Nothing maybe_buf
1595 (srcimps, the_imps, L mod_loc mod_name) <- getImports dflags' buf hspp_fn
1597 when (mod_name /= wanted_mod) $
1598 throwDyn $ mkPlainErrMsg mod_loc $
1599 text "file name does not match module name"
1600 <+> quotes (ppr mod_name)
1602 -- Find the object timestamp, and return the summary
1603 obj_timestamp <- getObjTimestamp location is_boot
1605 return (Just ( ModSummary { ms_mod = mod,
1606 ms_hsc_src = hsc_src,
1607 ms_location = location,
1608 ms_hspp_file = hspp_fn,
1609 ms_hspp_opts = dflags',
1610 ms_hspp_buf = Just buf,
1611 ms_srcimps = srcimps,
1613 ms_hs_date = src_timestamp,
1614 ms_obj_date = obj_timestamp }))
1617 getObjTimestamp location is_boot
1618 = if is_boot then return Nothing
1619 else modificationTimeIfExists (ml_obj_file location)
1622 preprocessFile :: DynFlags -> FilePath -> Maybe Phase -> Maybe (StringBuffer,ClockTime)
1623 -> IO (DynFlags, FilePath, StringBuffer)
1624 preprocessFile dflags src_fn mb_phase Nothing
1626 (dflags', hspp_fn) <- preprocess dflags (src_fn, mb_phase)
1627 buf <- hGetStringBuffer hspp_fn
1628 return (dflags', hspp_fn, buf)
1630 preprocessFile dflags src_fn mb_phase (Just (buf, time))
1632 -- case we bypass the preprocessing stage?
1634 local_opts = getOptions buf src_fn
1636 (dflags', errs) <- parseDynamicFlags dflags (map unLoc local_opts)
1640 | Just (Unlit _) <- mb_phase = True
1641 | Nothing <- mb_phase, Unlit _ <- startPhase src_fn = True
1642 -- note: local_opts is only required if there's no Unlit phase
1643 | dopt Opt_Cpp dflags' = True
1644 | dopt Opt_Pp dflags' = True
1647 when needs_preprocessing $
1648 ghcError (ProgramError "buffer needs preprocesing; interactive check disabled")
1650 return (dflags', src_fn, buf)
1653 -----------------------------------------------------------------------------
1655 -----------------------------------------------------------------------------
1657 noModError :: DynFlags -> SrcSpan -> ModuleName -> FindResult -> IO ab
1658 -- ToDo: we don't have a proper line number for this error
1659 noModError dflags loc wanted_mod err
1660 = throwDyn $ mkPlainErrMsg loc $ cannotFindModule dflags wanted_mod err
1662 noHsFileErr loc path
1663 = throwDyn $ mkPlainErrMsg loc $ text "Can't find" <+> text path
1666 = throwDyn $ mkPlainErrMsg noSrcSpan $
1667 text "module" <+> quotes (ppr mod) <+> text "is a package module"
1669 multiRootsErr :: [ModSummary] -> IO ()
1670 multiRootsErr summs@(summ1:_)
1671 = throwDyn $ mkPlainErrMsg noSrcSpan $
1672 text "module" <+> quotes (ppr mod) <+>
1673 text "is defined in multiple files:" <+>
1674 sep (map text files)
1677 files = map (expectJust "checkDup" . ml_hs_file . ms_location) summs
1679 cyclicModuleErr :: [ModSummary] -> SDoc
1681 = hang (ptext SLIT("Module imports form a cycle for modules:"))
1682 2 (vcat (map show_one ms))
1684 show_one ms = sep [ show_mod (ms_hsc_src ms) (ms_mod ms),
1685 nest 2 $ ptext SLIT("imports:") <+>
1686 (pp_imps HsBootFile (ms_srcimps ms)
1687 $$ pp_imps HsSrcFile (ms_imps ms))]
1688 show_mod hsc_src mod = ppr mod <> text (hscSourceString hsc_src)
1689 pp_imps src mods = fsep (map (show_mod src) mods)
1692 -- | Inform GHC that the working directory has changed. GHC will flush
1693 -- its cache of module locations, since it may no longer be valid.
1694 -- Note: if you change the working directory, you should also unload
1695 -- the current program (set targets to empty, followed by load).
1696 workingDirectoryChanged :: Session -> IO ()
1697 workingDirectoryChanged s = withSession s $ flushFinderCaches
1699 -- -----------------------------------------------------------------------------
1700 -- inspecting the session
1702 -- | Get the module dependency graph.
1703 getModuleGraph :: Session -> IO ModuleGraph -- ToDo: DiGraph ModSummary
1704 getModuleGraph s = withSession s (return . hsc_mod_graph)
1706 isLoaded :: Session -> ModuleName -> IO Bool
1707 isLoaded s m = withSession s $ \hsc_env ->
1708 return $! isJust (lookupUFM (hsc_HPT hsc_env) m)
1710 getBindings :: Session -> IO [TyThing]
1711 getBindings s = withSession s (return . nameEnvElts . ic_type_env . hsc_IC)
1713 getPrintUnqual :: Session -> IO PrintUnqualified
1714 getPrintUnqual s = withSession s (return . icPrintUnqual . hsc_IC)
1716 -- | Container for information about a 'Module'.
1717 data ModuleInfo = ModuleInfo {
1718 minf_type_env :: TypeEnv,
1719 minf_exports :: NameSet,
1720 minf_rdr_env :: Maybe GlobalRdrEnv, -- Nothing for a compiled/package mod
1721 minf_instances :: [Instance]
1722 -- ToDo: this should really contain the ModIface too
1724 -- We don't want HomeModInfo here, because a ModuleInfo applies
1725 -- to package modules too.
1727 -- | Request information about a loaded 'Module'
1728 getModuleInfo :: Session -> Module -> IO (Maybe ModuleInfo)
1729 getModuleInfo s mdl = withSession s $ \hsc_env -> do
1730 let mg = hsc_mod_graph hsc_env
1731 if mdl `elem` map ms_mod mg
1732 then getHomeModuleInfo hsc_env (moduleName mdl)
1734 {- if isHomeModule (hsc_dflags hsc_env) mdl
1736 else -} getPackageModuleInfo hsc_env mdl
1737 -- getPackageModuleInfo will attempt to find the interface, so
1738 -- we don't want to call it for a home module, just in case there
1739 -- was a problem loading the module and the interface doesn't
1740 -- exist... hence the isHomeModule test here. (ToDo: reinstate)
1742 getPackageModuleInfo :: HscEnv -> Module -> IO (Maybe ModuleInfo)
1743 getPackageModuleInfo hsc_env mdl = do
1745 (_msgs, mb_names) <- getModuleExports hsc_env mdl
1747 Nothing -> return Nothing
1749 eps <- readIORef (hsc_EPS hsc_env)
1752 n_list = nameSetToList names
1753 tys = [ ty | name <- n_list,
1754 Just ty <- [lookupTypeEnv pte name] ]
1756 return (Just (ModuleInfo {
1757 minf_type_env = mkTypeEnv tys,
1758 minf_exports = names,
1759 minf_rdr_env = Just $! nameSetToGlobalRdrEnv names (moduleName mdl),
1760 minf_instances = error "getModuleInfo: instances for package module unimplemented"
1763 -- bogusly different for non-GHCI (ToDo)
1767 getHomeModuleInfo hsc_env mdl =
1768 case lookupUFM (hsc_HPT hsc_env) mdl of
1769 Nothing -> return Nothing
1771 let details = hm_details hmi
1772 return (Just (ModuleInfo {
1773 minf_type_env = md_types details,
1774 minf_exports = md_exports details,
1775 minf_rdr_env = mi_globals $! hm_iface hmi,
1776 minf_instances = md_insts details
1779 -- | The list of top-level entities defined in a module
1780 modInfoTyThings :: ModuleInfo -> [TyThing]
1781 modInfoTyThings minf = typeEnvElts (minf_type_env minf)
1783 modInfoTopLevelScope :: ModuleInfo -> Maybe [Name]
1784 modInfoTopLevelScope minf
1785 = fmap (map gre_name . globalRdrEnvElts) (minf_rdr_env minf)
1787 modInfoExports :: ModuleInfo -> [Name]
1788 modInfoExports minf = nameSetToList $! minf_exports minf
1790 -- | Returns the instances defined by the specified module.
1791 -- Warning: currently unimplemented for package modules.
1792 modInfoInstances :: ModuleInfo -> [Instance]
1793 modInfoInstances = minf_instances
1795 modInfoIsExportedName :: ModuleInfo -> Name -> Bool
1796 modInfoIsExportedName minf name = elemNameSet name (minf_exports minf)
1798 modInfoPrintUnqualified :: ModuleInfo -> Maybe PrintUnqualified
1799 modInfoPrintUnqualified minf = fmap mkPrintUnqualified (minf_rdr_env minf)
1801 modInfoLookupName :: Session -> ModuleInfo -> Name -> IO (Maybe TyThing)
1802 modInfoLookupName s minf name = withSession s $ \hsc_env -> do
1803 case lookupTypeEnv (minf_type_env minf) name of
1804 Just tyThing -> return (Just tyThing)
1806 eps <- readIORef (hsc_EPS hsc_env)
1807 return $! lookupType (hsc_dflags hsc_env)
1808 (hsc_HPT hsc_env) (eps_PTE eps) name
1810 isDictonaryId :: Id -> Bool
1812 = case tcSplitSigmaTy (idType id) of { (tvs, theta, tau) -> isDictTy tau }
1814 -- | Looks up a global name: that is, any top-level name in any
1815 -- visible module. Unlike 'lookupName', lookupGlobalName does not use
1816 -- the interactive context, and therefore does not require a preceding
1818 lookupGlobalName :: Session -> Name -> IO (Maybe TyThing)
1819 lookupGlobalName s name = withSession s $ \hsc_env -> do
1820 eps <- readIORef (hsc_EPS hsc_env)
1821 return $! lookupType (hsc_dflags hsc_env)
1822 (hsc_HPT hsc_env) (eps_PTE eps) name
1824 -- -----------------------------------------------------------------------------
1825 -- Misc exported utils
1827 dataConType :: DataCon -> Type
1828 dataConType dc = idType (dataConWrapId dc)
1830 -- | print a 'NamedThing', adding parentheses if the name is an operator.
1831 pprParenSymName :: NamedThing a => a -> SDoc
1832 pprParenSymName a = parenSymOcc (getOccName a) (ppr (getName a))
1834 -- ----------------------------------------------------------------------------
1839 -- - Data and Typeable instances for HsSyn.
1841 -- ToDo: check for small transformations that happen to the syntax in
1842 -- the typechecker (eg. -e ==> negate e, perhaps for fromIntegral)
1844 -- ToDo: maybe use TH syntax instead of IfaceSyn? There's already a way
1845 -- to get from TyCons, Ids etc. to TH syntax (reify).
1847 -- :browse will use either lm_toplev or inspect lm_interface, depending
1848 -- on whether the module is interpreted or not.
1850 -- This is for reconstructing refactored source code
1851 -- Calls the lexer repeatedly.
1852 -- ToDo: add comment tokens to token stream
1853 getTokenStream :: Session -> Module -> IO [Located Token]
1856 -- -----------------------------------------------------------------------------
1857 -- Interactive evaluation
1859 -- | Takes a 'ModuleName' and possibly a 'PackageId', and consults the
1860 -- filesystem and package database to find the corresponding 'Module',
1861 -- using the algorithm that is used for an @import@ declaration.
1862 findModule :: Session -> ModuleName -> Maybe PackageId -> IO Module
1863 findModule s mod_name maybe_pkg = withSession s $ \hsc_env ->
1864 findModule' hsc_env mod_name maybe_pkg
1866 findModule' hsc_env mod_name maybe_pkg =
1868 dflags = hsc_dflags hsc_env
1869 hpt = hsc_HPT hsc_env
1870 this_pkg = thisPackage dflags
1872 case lookupUFM hpt mod_name of
1873 Just mod_info -> return (mi_module (hm_iface mod_info))
1874 _not_a_home_module -> do
1875 res <- findImportedModule hsc_env mod_name Nothing
1877 Found _ m | modulePackageId m /= this_pkg -> return m
1878 | otherwise -> throwDyn (CmdLineError (showSDoc $
1879 text "module" <+> pprModule m <+>
1880 text "is not loaded"))
1881 err -> let msg = cannotFindModule dflags mod_name err in
1882 throwDyn (CmdLineError (showSDoc msg))
1886 -- | Set the interactive evaluation context.
1888 -- Setting the context doesn't throw away any bindings; the bindings
1889 -- we've built up in the InteractiveContext simply move to the new
1890 -- module. They always shadow anything in scope in the current context.
1891 setContext :: Session
1892 -> [Module] -- entire top level scope of these modules
1893 -> [Module] -- exports only of these modules
1895 setContext (Session ref) toplev_mods export_mods = do
1896 hsc_env <- readIORef ref
1897 let old_ic = hsc_IC hsc_env
1898 hpt = hsc_HPT hsc_env
1900 export_env <- mkExportEnv hsc_env export_mods
1901 toplev_envs <- mapM (mkTopLevEnv hpt) toplev_mods
1902 let all_env = foldr plusGlobalRdrEnv export_env toplev_envs
1903 writeIORef ref hsc_env{ hsc_IC = old_ic { ic_toplev_scope = toplev_mods,
1904 ic_exports = export_mods,
1905 ic_rn_gbl_env = all_env }}
1908 -- Make a GlobalRdrEnv based on the exports of the modules only.
1909 mkExportEnv :: HscEnv -> [Module] -> IO GlobalRdrEnv
1910 mkExportEnv hsc_env mods = do
1911 stuff <- mapM (getModuleExports hsc_env) mods
1913 (_msgs, mb_name_sets) = unzip stuff
1914 gres = [ nameSetToGlobalRdrEnv name_set (moduleName mod)
1915 | (Just name_set, mod) <- zip mb_name_sets mods ]
1917 return $! foldr plusGlobalRdrEnv emptyGlobalRdrEnv gres
1919 nameSetToGlobalRdrEnv :: NameSet -> ModuleName -> GlobalRdrEnv
1920 nameSetToGlobalRdrEnv names mod =
1921 mkGlobalRdrEnv [ GRE { gre_name = name, gre_prov = vanillaProv mod }
1922 | name <- nameSetToList names ]
1924 vanillaProv :: ModuleName -> Provenance
1925 -- We're building a GlobalRdrEnv as if the user imported
1926 -- all the specified modules into the global interactive module
1927 vanillaProv mod_name = Imported [ImpSpec { is_decl = decl, is_item = ImpAll}]
1929 decl = ImpDeclSpec { is_mod = mod_name, is_as = mod_name,
1931 is_dloc = srcLocSpan interactiveSrcLoc }
1933 mkTopLevEnv :: HomePackageTable -> Module -> IO GlobalRdrEnv
1934 mkTopLevEnv hpt modl
1935 = case lookupUFM hpt (moduleName modl) of
1936 Nothing -> throwDyn (ProgramError ("mkTopLevEnv: not a home module " ++
1937 showSDoc (ppr modl)))
1939 case mi_globals (hm_iface details) of
1941 throwDyn (ProgramError ("mkTopLevEnv: not interpreted "
1942 ++ showSDoc (ppr modl)))
1943 Just env -> return env
1945 -- | Get the interactive evaluation context, consisting of a pair of the
1946 -- set of modules from which we take the full top-level scope, and the set
1947 -- of modules from which we take just the exports respectively.
1948 getContext :: Session -> IO ([Module],[Module])
1949 getContext s = withSession s (\HscEnv{ hsc_IC=ic } ->
1950 return (ic_toplev_scope ic, ic_exports ic))
1952 -- | Returns 'True' if the specified module is interpreted, and hence has
1953 -- its full top-level scope available.
1954 moduleIsInterpreted :: Session -> Module -> IO Bool
1955 moduleIsInterpreted s modl = withSession s $ \h ->
1956 if modulePackageId modl /= thisPackage (hsc_dflags h)
1958 else case lookupUFM (hsc_HPT h) (moduleName modl) of
1959 Just details -> return (isJust (mi_globals (hm_iface details)))
1960 _not_a_home_module -> return False
1962 -- | Looks up an identifier in the current interactive context (for :info)
1963 getInfo :: Session -> Name -> IO (Maybe (TyThing,Fixity,[Instance]))
1964 getInfo s name = withSession s $ \hsc_env -> tcRnGetInfo hsc_env name
1966 -- | Returns all names in scope in the current interactive context
1967 getNamesInScope :: Session -> IO [Name]
1968 getNamesInScope s = withSession s $ \hsc_env -> do
1969 return (map gre_name (globalRdrEnvElts (ic_rn_gbl_env (hsc_IC hsc_env))))
1971 getRdrNamesInScope :: Session -> IO [RdrName]
1972 getRdrNamesInScope s = withSession s $ \hsc_env -> do
1973 let env = ic_rn_gbl_env (hsc_IC hsc_env)
1974 return (concat (map greToRdrNames (globalRdrEnvElts env)))
1976 -- ToDo: move to RdrName
1977 greToRdrNames :: GlobalRdrElt -> [RdrName]
1978 greToRdrNames GRE{ gre_name = name, gre_prov = prov }
1980 LocalDef -> [unqual]
1981 Imported specs -> concat (map do_spec (map is_decl specs))
1983 occ = nameOccName name
1986 | is_qual decl_spec = [qual]
1987 | otherwise = [unqual,qual]
1988 where qual = Qual (is_as decl_spec) occ
1990 -- | Parses a string as an identifier, and returns the list of 'Name's that
1991 -- the identifier can refer to in the current interactive context.
1992 parseName :: Session -> String -> IO [Name]
1993 parseName s str = withSession s $ \hsc_env -> do
1994 maybe_rdr_name <- hscParseIdentifier (hsc_dflags hsc_env) str
1995 case maybe_rdr_name of
1996 Nothing -> return []
1997 Just (L _ rdr_name) -> do
1998 mb_names <- tcRnLookupRdrName hsc_env rdr_name
2000 Nothing -> return []
2001 Just ns -> return ns
2002 -- ToDo: should return error messages
2004 -- | Returns the 'TyThing' for a 'Name'. The 'Name' may refer to any
2005 -- entity known to GHC, including 'Name's defined using 'runStmt'.
2006 lookupName :: Session -> Name -> IO (Maybe TyThing)
2007 lookupName s name = withSession s $ \hsc_env -> tcRnLookupName hsc_env name
2009 -- -----------------------------------------------------------------------------
2010 -- Getting the type of an expression
2012 -- | Get the type of an expression
2013 exprType :: Session -> String -> IO (Maybe Type)
2014 exprType s expr = withSession s $ \hsc_env -> do
2015 maybe_stuff <- hscTcExpr hsc_env expr
2017 Nothing -> return Nothing
2018 Just ty -> return (Just tidy_ty)
2020 tidy_ty = tidyType emptyTidyEnv ty
2022 -- -----------------------------------------------------------------------------
2023 -- Getting the kind of a type
2025 -- | Get the kind of a type
2026 typeKind :: Session -> String -> IO (Maybe Kind)
2027 typeKind s str = withSession s $ \hsc_env -> do
2028 maybe_stuff <- hscKcType hsc_env str
2030 Nothing -> return Nothing
2031 Just kind -> return (Just kind)
2033 -----------------------------------------------------------------------------
2034 -- cmCompileExpr: compile an expression and deliver an HValue
2036 compileExpr :: Session -> String -> IO (Maybe HValue)
2037 compileExpr s expr = withSession s $ \hsc_env -> do
2038 maybe_stuff <- hscStmt hsc_env ("let __cmCompileExpr = "++expr)
2040 Nothing -> return Nothing
2041 Just (new_ic, names, hval) -> do
2043 hvals <- (unsafeCoerce# hval) :: IO [HValue]
2045 case (names,hvals) of
2046 ([n],[hv]) -> return (Just hv)
2047 _ -> panic "compileExpr"
2049 -- -----------------------------------------------------------------------------
2050 -- Compile an expression into a dynamic
2052 dynCompileExpr :: Session -> String -> IO (Maybe Dynamic)
2053 dynCompileExpr ses expr = do
2054 (full,exports) <- getContext ses
2055 setContext ses full $
2057 (stringToPackageId "base") (mkModuleName "Data.Dynamic")
2059 let stmt = "let __dynCompileExpr = Data.Dynamic.toDyn (" ++ expr ++ ")"
2060 res <- withSession ses (flip hscStmt stmt)
2061 setContext ses full exports
2063 Nothing -> return Nothing
2064 Just (_, names, hvals) -> do
2065 vals <- (unsafeCoerce# hvals :: IO [Dynamic])
2066 case (names,vals) of
2067 (_:[], v:[]) -> return (Just v)
2068 _ -> panic "dynCompileExpr"
2070 -- -----------------------------------------------------------------------------
2071 -- running a statement interactively
2074 = RunOk [Name] -- ^ names bound by this evaluation
2075 | RunFailed -- ^ statement failed compilation
2076 | RunException Exception -- ^ statement raised an exception
2078 -- | Run a statement in the current interactive context. Statemenet
2079 -- may bind multple values.
2080 runStmt :: Session -> String -> IO RunResult
2081 runStmt (Session ref) expr
2083 hsc_env <- readIORef ref
2085 -- Turn off -fwarn-unused-bindings when running a statement, to hide
2086 -- warnings about the implicit bindings we introduce.
2087 let dflags' = dopt_unset (hsc_dflags hsc_env) Opt_WarnUnusedBinds
2088 hsc_env' = hsc_env{ hsc_dflags = dflags' }
2090 maybe_stuff <- hscStmt hsc_env' expr
2093 Nothing -> return RunFailed
2094 Just (new_hsc_env, names, hval) -> do
2096 let thing_to_run = unsafeCoerce# hval :: IO [HValue]
2097 either_hvals <- sandboxIO thing_to_run
2099 case either_hvals of
2101 -- on error, keep the *old* interactive context,
2102 -- so that 'it' is not bound to something
2103 -- that doesn't exist.
2104 return (RunException e)
2107 -- Get the newly bound things, and bind them.
2108 -- Don't need to delete any shadowed bindings;
2109 -- the new ones override the old ones.
2110 extendLinkEnv (zip names hvals)
2112 writeIORef ref new_hsc_env
2113 return (RunOk names)
2115 -- When running a computation, we redirect ^C exceptions to the running
2116 -- thread. ToDo: we might want a way to continue even if the target
2117 -- thread doesn't die when it receives the exception... "this thread
2118 -- is not responding".
2119 sandboxIO :: IO a -> IO (Either Exception a)
2120 sandboxIO thing = do
2122 ts <- takeMVar interruptTargetThread
2123 child <- forkIO (do res <- Exception.try thing; putMVar m res)
2124 putMVar interruptTargetThread (child:ts)
2125 takeMVar m `finally` modifyMVar_ interruptTargetThread (return.tail)
2128 -- This version of sandboxIO runs the expression in a completely new
2129 -- RTS main thread. It is disabled for now because ^C exceptions
2130 -- won't be delivered to the new thread, instead they'll be delivered
2131 -- to the (blocked) GHCi main thread.
2133 -- SLPJ: when re-enabling this, reflect a wrong-stat error as an exception
2135 sandboxIO :: IO a -> IO (Either Int (Either Exception a))
2136 sandboxIO thing = do
2137 st_thing <- newStablePtr (Exception.try thing)
2138 alloca $ \ p_st_result -> do
2139 stat <- rts_evalStableIO st_thing p_st_result
2140 freeStablePtr st_thing
2142 then do st_result <- peek p_st_result
2143 result <- deRefStablePtr st_result
2144 freeStablePtr st_result
2145 return (Right result)
2147 return (Left (fromIntegral stat))
2149 foreign import "rts_evalStableIO" {- safe -}
2150 rts_evalStableIO :: StablePtr (IO a) -> Ptr (StablePtr a) -> IO CInt
2151 -- more informative than the C type!
2154 -----------------------------------------------------------------------------
2155 -- show a module and it's source/object filenames
2157 showModule :: Session -> ModSummary -> IO String
2158 showModule s mod_summary = withSession s $ \hsc_env -> do
2159 case lookupUFM (hsc_HPT hsc_env) (ms_mod_name mod_summary) of
2160 Nothing -> panic "missing linkable"
2161 Just mod_info -> return (showModMsg (hscTarget (hsc_dflags hsc_env)) (not obj_linkable) mod_summary)
2163 obj_linkable = isObjectLinkable (expectJust "showModule" (hm_linkable mod_info))