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 -- * Parsing Haddock comments
46 -- * Inspecting the module structure of the program
47 ModuleGraph, ModSummary(..), ms_mod_name, ModLocation(..),
52 -- * Inspecting modules
57 modInfoPrintUnqualified,
60 modInfoIsExportedName,
65 PrintUnqualified, alwaysQualify,
67 -- * Interactive evaluation
68 getBindings, getPrintUnqual,
71 setContext, getContext,
82 compileExpr, HValue, dynCompileExpr,
86 -- * Abstract syntax elements
92 Module, mkModule, pprModule, moduleName, modulePackageId,
93 ModuleName, mkModuleName, moduleNameString,
97 nameModule, nameParent_maybe, pprParenSymName, nameSrcLoc,
103 isImplicitId, isDeadBinder,
104 isExportedId, isLocalId, isGlobalId,
106 isPrimOpId, isFCallId, isClassOpId_maybe,
107 isDataConWorkId, idDataCon,
108 isBottomingId, isDictonaryId,
109 recordSelectorFieldLabel,
111 -- ** Type constructors
113 tyConTyVars, tyConDataCons, tyConArity,
114 isClassTyCon, isSynTyCon, isNewTyCon, isPrimTyCon, isFunTyCon,
116 synTyConDefn, synTyConType, synTyConResKind,
122 -- ** Data constructors
124 dataConSig, dataConType, dataConTyCon, dataConFieldLabels,
125 dataConIsInfix, isVanillaDataCon,
127 StrictnessMark(..), isMarkedStrict,
131 classMethods, classSCTheta, classTvsFds,
136 instanceDFunId, pprInstance, pprInstanceHdr,
138 -- ** Types and Kinds
139 Type, dropForAlls, splitForAllTys, funResultTy, pprParendType,
142 ThetaType, pprThetaArrow,
148 module HsSyn, -- ToDo: remove extraneous bits
152 defaultFixity, maxPrecedence,
156 -- ** Source locations
160 GhcException(..), showGhcException,
170 * inline bits of HscMain here to simplify layering: hscTcExpr, hscStmt.
171 * what StaticFlags should we expose, if any?
174 #include "HsVersions.h"
177 import qualified Linker
178 import Data.Dynamic ( Dynamic )
179 import Linker ( HValue, extendLinkEnv )
180 import TcRnDriver ( tcRnLookupRdrName, tcRnGetInfo,
181 tcRnLookupName, getModuleExports )
182 import RdrName ( plusGlobalRdrEnv, Provenance(..),
183 ImportSpec(..), ImpDeclSpec(..), ImpItemSpec(..),
185 import HscMain ( hscParseIdentifier, hscStmt, hscTcExpr, hscKcType )
186 import Name ( nameOccName )
187 import Type ( tidyType )
188 import VarEnv ( emptyTidyEnv )
189 import GHC.Exts ( unsafeCoerce# )
192 import Packages ( initPackages )
193 import NameSet ( NameSet, nameSetToList, elemNameSet )
194 import RdrName ( GlobalRdrEnv, GlobalRdrElt(..), RdrName(..),
195 globalRdrEnvElts, extendGlobalRdrEnv,
198 import Type ( Kind, Type, dropForAlls, PredType, ThetaType,
199 pprThetaArrow, pprParendType, splitForAllTys,
201 import Id ( Id, idType, isImplicitId, isDeadBinder,
202 isExportedId, isLocalId, isGlobalId,
203 isRecordSelector, recordSelectorFieldLabel,
204 isPrimOpId, isFCallId, isClassOpId_maybe,
205 isDataConWorkId, idDataCon,
208 import TysPrim ( alphaTyVars )
209 import TyCon ( TyCon, isClassTyCon, isSynTyCon, isNewTyCon,
210 isPrimTyCon, isFunTyCon, isOpenTyCon, tyConArity,
211 tyConTyVars, tyConDataCons, synTyConDefn,
212 synTyConType, synTyConResKind )
213 import Class ( Class, classSCTheta, classTvsFds, classMethods )
214 import FunDeps ( pprFundeps )
215 import DataCon ( DataCon, dataConWrapId, dataConSig, dataConTyCon,
216 dataConFieldLabels, dataConStrictMarks,
217 dataConIsInfix, isVanillaDataCon )
218 import Name ( Name, nameModule, NamedThing(..), nameParent_maybe,
220 import OccName ( parenSymOcc )
221 import NameEnv ( nameEnvElts )
222 import InstEnv ( Instance, instanceDFunId, pprInstance, pprInstanceHdr )
224 import DriverPipeline
225 import DriverPhases ( Phase(..), isHaskellSrcFilename, startPhase )
226 import HeaderInfo ( getImports, getOptions )
228 import HscMain ( newHscEnv, hscFileCheck, HscChecked(..) )
231 import SysTools ( initSysTools, cleanTempFiles, cleanTempFilesExcept,
235 import PackageConfig ( PackageId, stringToPackageId )
239 import Bag ( unitBag, listToBag )
240 import ErrUtils ( Severity(..), showPass, fatalErrorMsg, debugTraceMsg,
241 mkPlainErrMsg, printBagOfErrors, printBagOfWarnings,
243 import qualified ErrUtils
245 import StringBuffer ( StringBuffer, hGetStringBuffer )
248 import TcType ( tcSplitSigmaTy, isDictTy )
249 import Maybes ( expectJust, mapCatMaybes )
250 import HaddockParse ( parseHaddockParagraphs, parseHaddockString )
251 import HaddockLex ( tokenise )
253 import Control.Concurrent
254 import System.Directory ( getModificationTime, doesFileExist )
255 import Data.Maybe ( isJust, isNothing )
256 import Data.List ( partition, nub )
257 import qualified Data.List as List
258 import Control.Monad ( unless, when )
259 import System.Exit ( exitWith, ExitCode(..) )
260 import System.Time ( ClockTime )
261 import Control.Exception as Exception hiding (handle)
264 import System.IO.Error ( isDoesNotExistError )
265 import Prelude hiding (init)
267 #if __GLASGOW_HASKELL__ < 600
268 import System.IO as System.IO.Error ( try )
270 import System.IO.Error ( try )
273 -- -----------------------------------------------------------------------------
274 -- Exception handlers
276 -- | Install some default exception handlers and run the inner computation.
277 -- Unless you want to handle exceptions yourself, you should wrap this around
278 -- the top level of your program. The default handlers output the error
279 -- message(s) to stderr and exit cleanly.
280 defaultErrorHandler :: DynFlags -> IO a -> IO a
281 defaultErrorHandler dflags inner =
282 -- top-level exception handler: any unrecognised exception is a compiler bug.
283 handle (\exception -> do
286 -- an IO exception probably isn't our fault, so don't panic
288 fatalErrorMsg dflags (text (show exception))
289 AsyncException StackOverflow ->
290 fatalErrorMsg dflags (text "stack overflow: use +RTS -K<size> to increase it")
292 fatalErrorMsg dflags (text (show (Panic (show exception))))
293 exitWith (ExitFailure 1)
296 -- program errors: messages with locations attached. Sometimes it is
297 -- convenient to just throw these as exceptions.
298 handleDyn (\dyn -> do printBagOfErrors dflags (unitBag dyn)
299 exitWith (ExitFailure 1)) $
301 -- error messages propagated as exceptions
302 handleDyn (\dyn -> do
305 PhaseFailed _ code -> exitWith code
306 Interrupted -> exitWith (ExitFailure 1)
307 _ -> do fatalErrorMsg dflags (text (show (dyn :: GhcException)))
308 exitWith (ExitFailure 1)
312 -- | Install a default cleanup handler to remove temporary files
313 -- deposited by a GHC run. This is seperate from
314 -- 'defaultErrorHandler', because you might want to override the error
315 -- handling, but still get the ordinary cleanup behaviour.
316 defaultCleanupHandler :: DynFlags -> IO a -> IO a
317 defaultCleanupHandler dflags inner =
318 -- make sure we clean up after ourselves
319 later (unless (dopt Opt_KeepTmpFiles dflags) $
320 do cleanTempFiles dflags
323 -- exceptions will be blocked while we clean the temporary files,
324 -- so there shouldn't be any difficulty if we receive further
329 -- | Starts a new session. A session consists of a set of loaded
330 -- modules, a set of options (DynFlags), and an interactive context.
331 -- ToDo: GhcMode should say "keep typechecked code" and\/or "keep renamed
333 newSession :: GhcMode -> Maybe FilePath -> IO Session
334 newSession mode mb_top_dir = do
336 main_thread <- myThreadId
337 putMVar interruptTargetThread [main_thread]
338 installSignalHandlers
340 dflags0 <- initSysTools mb_top_dir defaultDynFlags
341 dflags <- initDynFlags dflags0
342 env <- newHscEnv dflags{ ghcMode=mode }
346 -- tmp: this breaks the abstraction, but required because DriverMkDepend
347 -- needs to call the Finder. ToDo: untangle this.
348 sessionHscEnv :: Session -> IO HscEnv
349 sessionHscEnv (Session ref) = readIORef ref
351 withSession :: Session -> (HscEnv -> IO a) -> IO a
352 withSession (Session ref) f = do h <- readIORef ref; f h
354 modifySession :: Session -> (HscEnv -> HscEnv) -> IO ()
355 modifySession (Session ref) f = do h <- readIORef ref; writeIORef ref $! f h
357 -- -----------------------------------------------------------------------------
360 -- | Grabs the DynFlags from the Session
361 getSessionDynFlags :: Session -> IO DynFlags
362 getSessionDynFlags s = withSession s (return . hsc_dflags)
364 -- | Updates the DynFlags in a Session. This also reads
365 -- the package database (unless it has already been read),
366 -- and prepares the compilers knowledge about packages. It
367 -- can be called again to load new packages: just add new
368 -- package flags to (packageFlags dflags).
370 -- Returns a list of new packages that may need to be linked in using
371 -- the dynamic linker (see 'linkPackages') as a result of new package
372 -- flags. If you are not doing linking or doing static linking, you
373 -- can ignore the list of packages returned.
375 setSessionDynFlags :: Session -> DynFlags -> IO [PackageId]
376 setSessionDynFlags (Session ref) dflags = do
377 hsc_env <- readIORef ref
378 (dflags', preload) <- initPackages dflags
379 writeIORef ref $! hsc_env{ hsc_dflags = dflags' }
382 -- | If there is no -o option, guess the name of target executable
383 -- by using top-level source file name as a base.
384 guessOutputFile :: Session -> IO ()
385 guessOutputFile s = modifySession s $ \env ->
386 let dflags = hsc_dflags env
387 mod_graph = hsc_mod_graph env
388 mainModuleSrcPath, guessedName :: Maybe String
389 mainModuleSrcPath = do
390 let isMain = (== mainModIs dflags) . ms_mod
391 [ms] <- return (filter isMain mod_graph)
392 ml_hs_file (ms_location ms)
393 guessedName = fmap basenameOf mainModuleSrcPath
395 case outputFile dflags of
397 Nothing -> env { hsc_dflags = dflags { outputFile = guessedName } }
399 -- -----------------------------------------------------------------------------
402 -- ToDo: think about relative vs. absolute file paths. And what
403 -- happens when the current directory changes.
405 -- | Sets the targets for this session. Each target may be a module name
406 -- or a filename. The targets correspond to the set of root modules for
407 -- the program\/library. Unloading the current program is achieved by
408 -- setting the current set of targets to be empty, followed by load.
409 setTargets :: Session -> [Target] -> IO ()
410 setTargets s targets = modifySession s (\h -> h{ hsc_targets = targets })
412 -- | returns the current set of targets
413 getTargets :: Session -> IO [Target]
414 getTargets s = withSession s (return . hsc_targets)
416 -- | Add another target
417 addTarget :: Session -> Target -> IO ()
419 = modifySession s (\h -> h{ hsc_targets = target : hsc_targets h })
422 removeTarget :: Session -> TargetId -> IO ()
423 removeTarget s target_id
424 = modifySession s (\h -> h{ hsc_targets = filter (hsc_targets h) })
426 filter targets = [ t | t@(Target id _) <- targets, id /= target_id ]
428 -- Attempts to guess what Target a string refers to. This function implements
429 -- the --make/GHCi command-line syntax for filenames:
431 -- - if the string looks like a Haskell source filename, then interpret
433 -- - if adding a .hs or .lhs suffix yields the name of an existing file,
435 -- - otherwise interpret the string as a module name
437 guessTarget :: String -> Maybe Phase -> IO Target
438 guessTarget file (Just phase)
439 = return (Target (TargetFile file (Just phase)) Nothing)
440 guessTarget file Nothing
441 | isHaskellSrcFilename file
442 = return (Target (TargetFile file Nothing) Nothing)
444 = do exists <- doesFileExist hs_file
446 then return (Target (TargetFile hs_file Nothing) Nothing)
448 exists <- doesFileExist lhs_file
450 then return (Target (TargetFile lhs_file Nothing) Nothing)
452 return (Target (TargetModule (mkModuleName file)) Nothing)
454 hs_file = file `joinFileExt` "hs"
455 lhs_file = file `joinFileExt` "lhs"
457 -- -----------------------------------------------------------------------------
458 -- Extending the program scope
460 extendGlobalRdrScope :: Session -> [GlobalRdrElt] -> IO ()
461 extendGlobalRdrScope session rdrElts
462 = modifySession session $ \hscEnv ->
463 let global_rdr = hsc_global_rdr_env hscEnv
464 in hscEnv{ hsc_global_rdr_env = foldl extendGlobalRdrEnv global_rdr rdrElts }
466 setGlobalRdrScope :: Session -> [GlobalRdrElt] -> IO ()
467 setGlobalRdrScope session rdrElts
468 = modifySession session $ \hscEnv ->
469 hscEnv{ hsc_global_rdr_env = foldl extendGlobalRdrEnv emptyGlobalRdrEnv rdrElts }
471 extendGlobalTypeScope :: Session -> [Id] -> IO ()
472 extendGlobalTypeScope session ids
473 = modifySession session $ \hscEnv ->
474 let global_type = hsc_global_type_env hscEnv
475 in hscEnv{ hsc_global_type_env = extendTypeEnvWithIds global_type ids }
477 setGlobalTypeScope :: Session -> [Id] -> IO ()
478 setGlobalTypeScope session ids
479 = modifySession session $ \hscEnv ->
480 hscEnv{ hsc_global_type_env = extendTypeEnvWithIds emptyTypeEnv ids }
482 -- -----------------------------------------------------------------------------
483 -- Parsing Haddock comments
485 parseHaddockComment :: String -> Either String (HsDoc RdrName)
486 parseHaddockComment string = parseHaddockParagraphs (tokenise string)
488 -- -----------------------------------------------------------------------------
489 -- Loading the program
491 -- Perform a dependency analysis starting from the current targets
492 -- and update the session with the new module graph.
493 depanal :: Session -> [ModuleName] -> Bool -> IO (Maybe ModuleGraph)
494 depanal (Session ref) excluded_mods allow_dup_roots = do
495 hsc_env <- readIORef ref
497 dflags = hsc_dflags hsc_env
498 gmode = ghcMode (hsc_dflags hsc_env)
499 targets = hsc_targets hsc_env
500 old_graph = hsc_mod_graph hsc_env
502 showPass dflags "Chasing dependencies"
503 when (gmode == BatchCompile) $
504 debugTraceMsg dflags 2 (hcat [
505 text "Chasing modules from: ",
506 hcat (punctuate comma (map pprTarget targets))])
508 r <- downsweep hsc_env old_graph excluded_mods allow_dup_roots
510 Just mod_graph -> writeIORef ref hsc_env{ hsc_mod_graph = mod_graph }
515 -- | The result of load.
517 = LoadOk Errors -- ^ all specified targets were loaded successfully.
518 | LoadFailed Errors -- ^ not all modules were loaded.
520 type Errors = [String]
522 data ErrMsg = ErrMsg {
523 errMsgSeverity :: Severity, -- warning, error, etc.
524 errMsgSpans :: [SrcSpan],
525 errMsgShortDoc :: Doc,
526 errMsgExtraInfo :: Doc
532 | LoadUpTo ModuleName
533 | LoadDependenciesOf ModuleName
535 -- | Try to load the program. If a Module is supplied, then just
536 -- attempt to load up to this target. If no Module is supplied,
537 -- then try to load all targets.
538 load :: Session -> LoadHowMuch -> IO SuccessFlag
539 load s@(Session ref) how_much
541 -- Dependency analysis first. Note that this fixes the module graph:
542 -- even if we don't get a fully successful upsweep, the full module
543 -- graph is still retained in the Session. We can tell which modules
544 -- were successfully loaded by inspecting the Session's HPT.
545 mb_graph <- depanal s [] False
547 Just mod_graph -> load2 s how_much mod_graph
548 Nothing -> return Failed
550 load2 s@(Session ref) how_much mod_graph = do
552 hsc_env <- readIORef ref
554 let hpt1 = hsc_HPT hsc_env
555 let dflags = hsc_dflags hsc_env
556 let ghci_mode = ghcMode dflags -- this never changes
558 -- The "bad" boot modules are the ones for which we have
559 -- B.hs-boot in the module graph, but no B.hs
560 -- The downsweep should have ensured this does not happen
562 let all_home_mods = [ms_mod_name s
563 | s <- mod_graph, not (isBootSummary s)]
565 bad_boot_mods = [s | s <- mod_graph, isBootSummary s,
566 not (ms_mod_name s `elem` all_home_mods)]
568 ASSERT( null bad_boot_mods ) return ()
570 -- mg2_with_srcimps drops the hi-boot nodes, returning a
571 -- graph with cycles. Among other things, it is used for
572 -- backing out partially complete cycles following a failed
573 -- upsweep, and for removing from hpt all the modules
574 -- not in strict downwards closure, during calls to compile.
575 let mg2_with_srcimps :: [SCC ModSummary]
576 mg2_with_srcimps = topSortModuleGraph True mod_graph Nothing
578 -- If we can determine that any of the {-# SOURCE #-} imports
579 -- are definitely unnecessary, then emit a warning.
580 warnUnnecessarySourceImports dflags mg2_with_srcimps
583 -- check the stability property for each module.
584 stable_mods@(stable_obj,stable_bco)
585 | BatchCompile <- ghci_mode = ([],[])
586 | otherwise = checkStability hpt1 mg2_with_srcimps all_home_mods
588 -- prune bits of the HPT which are definitely redundant now,
590 pruned_hpt = pruneHomePackageTable hpt1
591 (flattenSCCs mg2_with_srcimps)
596 debugTraceMsg dflags 2 (text "Stable obj:" <+> ppr stable_obj $$
597 text "Stable BCO:" <+> ppr stable_bco)
599 -- Unload any modules which are going to be re-linked this time around.
600 let stable_linkables = [ linkable
601 | m <- stable_obj++stable_bco,
602 Just hmi <- [lookupUFM pruned_hpt m],
603 Just linkable <- [hm_linkable hmi] ]
604 unload hsc_env stable_linkables
606 -- We could at this point detect cycles which aren't broken by
607 -- a source-import, and complain immediately, but it seems better
608 -- to let upsweep_mods do this, so at least some useful work gets
609 -- done before the upsweep is abandoned.
610 --hPutStrLn stderr "after tsort:\n"
611 --hPutStrLn stderr (showSDoc (vcat (map ppr mg2)))
613 -- Now do the upsweep, calling compile for each module in
614 -- turn. Final result is version 3 of everything.
616 -- Topologically sort the module graph, this time including hi-boot
617 -- nodes, and possibly just including the portion of the graph
618 -- reachable from the module specified in the 2nd argument to load.
619 -- This graph should be cycle-free.
620 -- If we're restricting the upsweep to a portion of the graph, we
621 -- also want to retain everything that is still stable.
622 let full_mg :: [SCC ModSummary]
623 full_mg = topSortModuleGraph False mod_graph Nothing
625 maybe_top_mod = case how_much of
627 LoadDependenciesOf m -> Just m
630 partial_mg0 :: [SCC ModSummary]
631 partial_mg0 = topSortModuleGraph False mod_graph maybe_top_mod
633 -- LoadDependenciesOf m: we want the upsweep to stop just
634 -- short of the specified module (unless the specified module
637 | LoadDependenciesOf mod <- how_much
638 = ASSERT( case last partial_mg0 of
639 AcyclicSCC ms -> ms_mod_name ms == mod; _ -> False )
640 List.init partial_mg0
646 | AcyclicSCC ms <- full_mg,
647 ms_mod_name ms `elem` stable_obj++stable_bco,
648 ms_mod_name ms `notElem` [ ms_mod_name ms' |
649 AcyclicSCC ms' <- partial_mg ] ]
651 mg = stable_mg ++ partial_mg
653 -- clean up between compilations
654 let cleanup = cleanTempFilesExcept dflags
655 (ppFilesFromSummaries (flattenSCCs mg2_with_srcimps))
657 (upsweep_ok, hsc_env1, modsUpswept)
658 <- upsweep (hsc_env { hsc_HPT = emptyHomePackageTable })
659 pruned_hpt stable_mods cleanup mg
661 -- Make modsDone be the summaries for each home module now
662 -- available; this should equal the domain of hpt3.
663 -- Get in in a roughly top .. bottom order (hence reverse).
665 let modsDone = reverse modsUpswept
667 -- Try and do linking in some form, depending on whether the
668 -- upsweep was completely or only partially successful.
670 if succeeded upsweep_ok
673 -- Easy; just relink it all.
674 do debugTraceMsg dflags 2 (text "Upsweep completely successful.")
676 -- Clean up after ourselves
677 cleanTempFilesExcept dflags (ppFilesFromSummaries modsDone)
679 -- Issue a warning for the confusing case where the user
680 -- said '-o foo' but we're not going to do any linking.
681 -- We attempt linking if either (a) one of the modules is
682 -- called Main, or (b) the user said -no-hs-main, indicating
683 -- that main() is going to come from somewhere else.
685 let ofile = outputFile dflags
686 let no_hs_main = dopt Opt_NoHsMain dflags
688 main_mod = mainModIs dflags
689 a_root_is_Main = any ((==main_mod).ms_mod) mod_graph
690 do_linking = a_root_is_Main || no_hs_main
692 when (ghci_mode == BatchCompile && isJust ofile && not do_linking) $
693 debugTraceMsg dflags 1 (text ("Warning: output was redirected with -o, " ++
694 "but no output will be generated\n" ++
695 "because there is no " ++ moduleNameString (moduleName main_mod) ++ " module."))
697 -- link everything together
698 linkresult <- link ghci_mode dflags do_linking (hsc_HPT hsc_env1)
700 loadFinish Succeeded linkresult ref hsc_env1
703 -- Tricky. We need to back out the effects of compiling any
704 -- half-done cycles, both so as to clean up the top level envs
705 -- and to avoid telling the interactive linker to link them.
706 do debugTraceMsg dflags 2 (text "Upsweep partially successful.")
709 = map ms_mod modsDone
710 let mods_to_zap_names
711 = findPartiallyCompletedCycles modsDone_names
714 = filter ((`notElem` mods_to_zap_names).ms_mod)
717 let hpt4 = retainInTopLevelEnvs (map ms_mod_name mods_to_keep)
720 -- Clean up after ourselves
721 cleanTempFilesExcept dflags (ppFilesFromSummaries mods_to_keep)
723 -- there should be no Nothings where linkables should be, now
724 ASSERT(all (isJust.hm_linkable)
725 (eltsUFM (hsc_HPT hsc_env))) do
727 -- Link everything together
728 linkresult <- link ghci_mode dflags False hpt4
730 let hsc_env4 = hsc_env1{ hsc_HPT = hpt4 }
731 loadFinish Failed linkresult ref hsc_env4
733 -- Finish up after a load.
735 -- If the link failed, unload everything and return.
736 loadFinish all_ok Failed ref hsc_env
737 = do unload hsc_env []
738 writeIORef ref $! discardProg hsc_env
741 -- Empty the interactive context and set the module context to the topmost
742 -- newly loaded module, or the Prelude if none were loaded.
743 loadFinish all_ok Succeeded ref hsc_env
744 = do writeIORef ref $! hsc_env{ hsc_IC = emptyInteractiveContext }
748 -- Forget the current program, but retain the persistent info in HscEnv
749 discardProg :: HscEnv -> HscEnv
751 = hsc_env { hsc_mod_graph = emptyMG,
752 hsc_IC = emptyInteractiveContext,
753 hsc_HPT = emptyHomePackageTable }
755 -- used to fish out the preprocess output files for the purposes of
756 -- cleaning up. The preprocessed file *might* be the same as the
757 -- source file, but that doesn't do any harm.
758 ppFilesFromSummaries summaries = map ms_hspp_file summaries
760 -- -----------------------------------------------------------------------------
764 CheckedModule { parsedSource :: ParsedSource,
765 renamedSource :: Maybe RenamedSource,
766 typecheckedSource :: Maybe TypecheckedSource,
767 checkedModuleInfo :: Maybe ModuleInfo
769 -- ToDo: improvements that could be made here:
770 -- if the module succeeded renaming but not typechecking,
771 -- we can still get back the GlobalRdrEnv and exports, so
772 -- perhaps the ModuleInfo should be split up into separate
773 -- fields within CheckedModule.
775 type ParsedSource = Located (HsModule RdrName)
776 type RenamedSource = (HsGroup Name, [LImportDecl Name], Maybe [LIE Name],
777 Maybe (HsDoc Name), HaddockModInfo Name)
778 type TypecheckedSource = LHsBinds Id
781 -- - things that aren't in the output of the typechecker right now:
785 -- - type/data/newtype declarations
786 -- - class declarations
788 -- - extra things in the typechecker's output:
789 -- - default methods are turned into top-level decls.
790 -- - dictionary bindings
793 -- | This is the way to get access to parsed and typechecked source code
794 -- for a module. 'checkModule' loads all the dependencies of the specified
795 -- module in the Session, and then attempts to typecheck the module. If
796 -- successful, it returns the abstract syntax for the module.
797 checkModule :: Session -> ModuleName -> IO (Maybe CheckedModule)
798 checkModule session@(Session ref) mod = do
799 -- load up the dependencies first
800 r <- load session (LoadDependenciesOf mod)
801 if (failed r) then return Nothing else do
803 -- now parse & typecheck the module
804 hsc_env <- readIORef ref
805 let mg = hsc_mod_graph hsc_env
806 case [ ms | ms <- mg, ms_mod_name ms == mod ] of
809 mbChecked <- hscFileCheck hsc_env{hsc_dflags=ms_hspp_opts ms} ms
811 Nothing -> return Nothing
812 Just (HscChecked parsed renamed Nothing) ->
813 return (Just (CheckedModule {
814 parsedSource = parsed,
815 renamedSource = renamed,
816 typecheckedSource = Nothing,
817 checkedModuleInfo = Nothing }))
818 Just (HscChecked parsed renamed
819 (Just (tc_binds, rdr_env, details))) -> do
820 let minf = ModuleInfo {
821 minf_type_env = md_types details,
822 minf_exports = md_exports details,
823 minf_rdr_env = Just rdr_env,
824 minf_instances = md_insts details
826 return (Just (CheckedModule {
827 parsedSource = parsed,
828 renamedSource = renamed,
829 typecheckedSource = Just tc_binds,
830 checkedModuleInfo = Just minf }))
832 -- ---------------------------------------------------------------------------
835 unload :: HscEnv -> [Linkable] -> IO ()
836 unload hsc_env stable_linkables -- Unload everthing *except* 'stable_linkables'
837 = case ghcMode (hsc_dflags hsc_env) of
838 BatchCompile -> return ()
839 JustTypecheck -> return ()
841 Interactive -> Linker.unload (hsc_dflags hsc_env) stable_linkables
843 Interactive -> panic "unload: no interpreter"
845 other -> panic "unload: strange mode"
847 -- -----------------------------------------------------------------------------
851 Stability tells us which modules definitely do not need to be recompiled.
852 There are two main reasons for having stability:
854 - avoid doing a complete upsweep of the module graph in GHCi when
855 modules near the bottom of the tree have not changed.
857 - to tell GHCi when it can load object code: we can only load object code
858 for a module when we also load object code fo all of the imports of the
859 module. So we need to know that we will definitely not be recompiling
860 any of these modules, and we can use the object code.
862 NB. stability is of no importance to BatchCompile at all, only Interactive.
863 (ToDo: what about JustTypecheck?)
865 The stability check is as follows. Both stableObject and
866 stableBCO are used during the upsweep phase later.
869 stable m = stableObject m || stableBCO m
872 all stableObject (imports m)
873 && old linkable does not exist, or is == on-disk .o
874 && date(on-disk .o) > date(.hs)
877 all stable (imports m)
878 && date(BCO) > date(.hs)
881 These properties embody the following ideas:
883 - if a module is stable:
884 - if it has been compiled in a previous pass (present in HPT)
885 then it does not need to be compiled or re-linked.
886 - if it has not been compiled in a previous pass,
887 then we only need to read its .hi file from disk and
888 link it to produce a ModDetails.
890 - if a modules is not stable, we will definitely be at least
891 re-linking, and possibly re-compiling it during the upsweep.
892 All non-stable modules can (and should) therefore be unlinked
895 - Note that objects are only considered stable if they only depend
896 on other objects. We can't link object code against byte code.
900 :: HomePackageTable -- HPT from last compilation
901 -> [SCC ModSummary] -- current module graph (cyclic)
902 -> [ModuleName] -- all home modules
903 -> ([ModuleName], -- stableObject
904 [ModuleName]) -- stableBCO
906 checkStability hpt sccs all_home_mods = foldl checkSCC ([],[]) sccs
908 checkSCC (stable_obj, stable_bco) scc0
909 | stableObjects = (scc_mods ++ stable_obj, stable_bco)
910 | stableBCOs = (stable_obj, scc_mods ++ stable_bco)
911 | otherwise = (stable_obj, stable_bco)
913 scc = flattenSCC scc0
914 scc_mods = map ms_mod_name scc
915 home_module m = m `elem` all_home_mods && m `notElem` scc_mods
917 scc_allimps = nub (filter home_module (concatMap ms_allimps scc))
918 -- all imports outside the current SCC, but in the home pkg
920 stable_obj_imps = map (`elem` stable_obj) scc_allimps
921 stable_bco_imps = map (`elem` stable_bco) scc_allimps
928 and (zipWith (||) stable_obj_imps stable_bco_imps)
932 | Just t <- ms_obj_date ms = t >= ms_hs_date ms
936 same_as_prev t = case lookupUFM hpt (ms_mod_name ms) of
937 Just hmi | Just l <- hm_linkable hmi
938 -> isObjectLinkable l && t == linkableTime l
940 -- why '>=' rather than '>' above? If the filesystem stores
941 -- times to the nearset second, we may occasionally find that
942 -- the object & source have the same modification time,
943 -- especially if the source was automatically generated
944 -- and compiled. Using >= is slightly unsafe, but it matches
948 = case lookupUFM hpt (ms_mod_name ms) of
949 Just hmi | Just l <- hm_linkable hmi ->
950 not (isObjectLinkable l) &&
951 linkableTime l >= ms_hs_date ms
954 ms_allimps :: ModSummary -> [ModuleName]
955 ms_allimps ms = map unLoc (ms_srcimps ms ++ ms_imps ms)
957 -- -----------------------------------------------------------------------------
958 -- Prune the HomePackageTable
960 -- Before doing an upsweep, we can throw away:
962 -- - For non-stable modules:
963 -- - all ModDetails, all linked code
964 -- - all unlinked code that is out of date with respect to
967 -- This is VERY IMPORTANT otherwise we'll end up requiring 2x the
968 -- space at the end of the upsweep, because the topmost ModDetails of the
969 -- old HPT holds on to the entire type environment from the previous
972 pruneHomePackageTable
975 -> ([ModuleName],[ModuleName])
978 pruneHomePackageTable hpt summ (stable_obj, stable_bco)
981 | is_stable modl = hmi'
982 | otherwise = hmi'{ hm_details = emptyModDetails }
984 modl = moduleName (mi_module (hm_iface hmi))
985 hmi' | Just l <- hm_linkable hmi, linkableTime l < ms_hs_date ms
986 = hmi{ hm_linkable = Nothing }
989 where ms = expectJust "prune" (lookupUFM ms_map modl)
991 ms_map = listToUFM [(ms_mod_name ms, ms) | ms <- summ]
993 is_stable m = m `elem` stable_obj || m `elem` stable_bco
995 -- -----------------------------------------------------------------------------
997 -- Return (names of) all those in modsDone who are part of a cycle
998 -- as defined by theGraph.
999 findPartiallyCompletedCycles :: [Module] -> [SCC ModSummary] -> [Module]
1000 findPartiallyCompletedCycles modsDone theGraph
1004 chew ((AcyclicSCC v):rest) = chew rest -- acyclic? not interesting.
1005 chew ((CyclicSCC vs):rest)
1006 = let names_in_this_cycle = nub (map ms_mod vs)
1008 = nub ([done | done <- modsDone,
1009 done `elem` names_in_this_cycle])
1010 chewed_rest = chew rest
1012 if notNull mods_in_this_cycle
1013 && length mods_in_this_cycle < length names_in_this_cycle
1014 then mods_in_this_cycle ++ chewed_rest
1017 -- -----------------------------------------------------------------------------
1020 -- This is where we compile each module in the module graph, in a pass
1021 -- from the bottom to the top of the graph.
1023 -- There better had not be any cyclic groups here -- we check for them.
1026 :: HscEnv -- Includes initially-empty HPT
1027 -> HomePackageTable -- HPT from last time round (pruned)
1028 -> ([ModuleName],[ModuleName]) -- stable modules (see checkStability)
1029 -> IO () -- How to clean up unwanted tmp files
1030 -> [SCC ModSummary] -- Mods to do (the worklist)
1032 HscEnv, -- With an updated HPT
1033 [ModSummary]) -- Mods which succeeded
1035 upsweep hsc_env old_hpt stable_mods cleanup mods
1036 = upsweep' hsc_env old_hpt stable_mods cleanup mods 1 (length mods)
1038 upsweep' hsc_env old_hpt stable_mods cleanup
1040 = return (Succeeded, hsc_env, [])
1042 upsweep' hsc_env old_hpt stable_mods cleanup
1043 (CyclicSCC ms:_) _ _
1044 = do fatalErrorMsg (hsc_dflags hsc_env) (cyclicModuleErr ms)
1045 return (Failed, hsc_env, [])
1047 upsweep' hsc_env old_hpt stable_mods cleanup
1048 (AcyclicSCC mod:mods) mod_index nmods
1049 = do -- putStrLn ("UPSWEEP_MOD: hpt = " ++
1050 -- show (map (moduleUserString.moduleName.mi_module.hm_iface)
1051 -- (moduleEnvElts (hsc_HPT hsc_env)))
1053 mb_mod_info <- upsweep_mod hsc_env old_hpt stable_mods mod
1056 cleanup -- Remove unwanted tmp files between compilations
1059 Nothing -> return (Failed, hsc_env, [])
1061 { let this_mod = ms_mod_name mod
1063 -- Add new info to hsc_env
1064 hpt1 = addToUFM (hsc_HPT hsc_env) this_mod mod_info
1065 hsc_env1 = hsc_env { hsc_HPT = hpt1 }
1067 -- Space-saving: delete the old HPT entry
1068 -- for mod BUT if mod is a hs-boot
1069 -- node, don't delete it. For the
1070 -- interface, the HPT entry is probaby for the
1071 -- main Haskell source file. Deleting it
1072 -- would force .. (what?? --SDM)
1073 old_hpt1 | isBootSummary mod = old_hpt
1074 | otherwise = delFromUFM old_hpt this_mod
1076 ; (restOK, hsc_env2, modOKs)
1077 <- upsweep' hsc_env1 old_hpt1 stable_mods cleanup
1078 mods (mod_index+1) nmods
1079 ; return (restOK, hsc_env2, mod:modOKs)
1083 -- Compile a single module. Always produce a Linkable for it if
1084 -- successful. If no compilation happened, return the old Linkable.
1085 upsweep_mod :: HscEnv
1087 -> ([ModuleName],[ModuleName])
1089 -> Int -- index of module
1090 -> Int -- total number of modules
1091 -> IO (Maybe HomeModInfo) -- Nothing => Failed
1093 upsweep_mod hsc_env old_hpt (stable_obj, stable_bco) summary mod_index nmods
1096 this_mod_name = ms_mod_name summary
1097 this_mod = ms_mod summary
1098 mb_obj_date = ms_obj_date summary
1099 obj_fn = ml_obj_file (ms_location summary)
1100 hs_date = ms_hs_date summary
1102 compile_it :: Maybe Linkable -> IO (Maybe HomeModInfo)
1103 compile_it = upsweep_compile hsc_env old_hpt this_mod_name
1104 summary mod_index nmods
1106 case ghcMode (hsc_dflags hsc_env) of
1109 -- Batch-compilating is easy: just check whether we have
1110 -- an up-to-date object file. If we do, then the compiler
1111 -- needs to do a recompilation check.
1112 _ | Just obj_date <- mb_obj_date, obj_date >= hs_date -> do
1114 findObjectLinkable this_mod obj_fn obj_date
1115 compile_it (Just linkable)
1122 _ | is_stable_obj, isJust old_hmi ->
1124 -- object is stable, and we have an entry in the
1125 -- old HPT: nothing to do
1127 | is_stable_obj, isNothing old_hmi -> do
1129 findObjectLinkable this_mod obj_fn
1130 (expectJust "upseep1" mb_obj_date)
1131 compile_it (Just linkable)
1132 -- object is stable, but we need to load the interface
1133 -- off disk to make a HMI.
1136 ASSERT(isJust old_hmi) -- must be in the old_hpt
1138 -- BCO is stable: nothing to do
1140 | Just hmi <- old_hmi,
1141 Just l <- hm_linkable hmi, not (isObjectLinkable l),
1142 linkableTime l >= ms_hs_date summary ->
1144 -- we have an old BCO that is up to date with respect
1145 -- to the source: do a recompilation check as normal.
1149 -- no existing code at all: we must recompile.
1151 is_stable_obj = this_mod_name `elem` stable_obj
1152 is_stable_bco = this_mod_name `elem` stable_bco
1154 old_hmi = lookupUFM old_hpt this_mod_name
1156 -- Run hsc to compile a module
1157 upsweep_compile hsc_env old_hpt this_mod summary
1159 mb_old_linkable = do
1161 -- The old interface is ok if it's in the old HPT
1162 -- a) we're compiling a source file, and the old HPT
1163 -- entry is for a source file
1164 -- b) we're compiling a hs-boot file
1165 -- Case (b) allows an hs-boot file to get the interface of its
1166 -- real source file on the second iteration of the compilation
1167 -- manager, but that does no harm. Otherwise the hs-boot file
1168 -- will always be recompiled
1171 = case lookupUFM old_hpt this_mod of
1173 Just hm_info | isBootSummary summary -> Just iface
1174 | not (mi_boot iface) -> Just iface
1175 | otherwise -> Nothing
1177 iface = hm_iface hm_info
1179 compresult <- compile hsc_env summary mb_old_linkable mb_old_iface
1183 -- Compilation failed. Compile may still have updated the PCS, tho.
1184 CompErrs -> return Nothing
1186 -- Compilation "succeeded", and may or may not have returned a new
1187 -- linkable (depending on whether compilation was actually performed
1189 CompOK new_details new_iface new_linkable
1190 -> do let new_info = HomeModInfo { hm_iface = new_iface,
1191 hm_details = new_details,
1192 hm_linkable = new_linkable }
1193 return (Just new_info)
1196 -- Filter modules in the HPT
1197 retainInTopLevelEnvs :: [ModuleName] -> HomePackageTable -> HomePackageTable
1198 retainInTopLevelEnvs keep_these hpt
1199 = listToUFM [ (mod, expectJust "retain" mb_mod_info)
1201 , let mb_mod_info = lookupUFM hpt mod
1202 , isJust mb_mod_info ]
1204 -- ---------------------------------------------------------------------------
1205 -- Topological sort of the module graph
1208 :: Bool -- Drop hi-boot nodes? (see below)
1212 -- Calculate SCCs of the module graph, possibly dropping the hi-boot nodes
1213 -- The resulting list of strongly-connected-components is in topologically
1214 -- sorted order, starting with the module(s) at the bottom of the
1215 -- dependency graph (ie compile them first) and ending with the ones at
1218 -- Drop hi-boot nodes (first boolean arg)?
1220 -- False: treat the hi-boot summaries as nodes of the graph,
1221 -- so the graph must be acyclic
1223 -- True: eliminate the hi-boot nodes, and instead pretend
1224 -- the a source-import of Foo is an import of Foo
1225 -- The resulting graph has no hi-boot nodes, but can by cyclic
1227 topSortModuleGraph drop_hs_boot_nodes summaries Nothing
1228 = stronglyConnComp (fst (moduleGraphNodes drop_hs_boot_nodes summaries))
1229 topSortModuleGraph drop_hs_boot_nodes summaries (Just mod)
1230 = stronglyConnComp (map vertex_fn (reachable graph root))
1232 -- restrict the graph to just those modules reachable from
1233 -- the specified module. We do this by building a graph with
1234 -- the full set of nodes, and determining the reachable set from
1235 -- the specified node.
1236 (nodes, lookup_key) = moduleGraphNodes drop_hs_boot_nodes summaries
1237 (graph, vertex_fn, key_fn) = graphFromEdges' nodes
1239 | Just key <- lookup_key HsSrcFile mod, Just v <- key_fn key = v
1240 | otherwise = throwDyn (ProgramError "module does not exist")
1242 moduleGraphNodes :: Bool -> [ModSummary]
1243 -> ([(ModSummary, Int, [Int])], HscSource -> ModuleName -> Maybe Int)
1244 moduleGraphNodes drop_hs_boot_nodes summaries = (nodes, lookup_key)
1246 -- Drop hs-boot nodes by using HsSrcFile as the key
1247 hs_boot_key | drop_hs_boot_nodes = HsSrcFile
1248 | otherwise = HsBootFile
1250 -- We use integers as the keys for the SCC algorithm
1251 nodes :: [(ModSummary, Int, [Int])]
1252 nodes = [(s, expectJust "topSort" $
1253 lookup_key (ms_hsc_src s) (ms_mod_name s),
1254 out_edge_keys hs_boot_key (map unLoc (ms_srcimps s)) ++
1255 out_edge_keys HsSrcFile (map unLoc (ms_imps s)) ++
1256 (-- see [boot-edges] below
1257 if drop_hs_boot_nodes || ms_hsc_src s == HsBootFile
1259 else case lookup_key HsBootFile (ms_mod_name s) of
1264 , not (isBootSummary s && drop_hs_boot_nodes) ]
1265 -- Drop the hi-boot ones if told to do so
1267 -- [boot-edges] if this is a .hs and there is an equivalent
1268 -- .hs-boot, add a link from the former to the latter. This
1269 -- has the effect of detecting bogus cases where the .hs-boot
1270 -- depends on the .hs, by introducing a cycle. Additionally,
1271 -- it ensures that we will always process the .hs-boot before
1272 -- the .hs, and so the HomePackageTable will always have the
1273 -- most up to date information.
1275 key_map :: NodeMap Int
1276 key_map = listToFM ([(moduleName (ms_mod s), ms_hsc_src s)
1280 lookup_key :: HscSource -> ModuleName -> Maybe Int
1281 lookup_key hs_src mod = lookupFM key_map (mod, hs_src)
1283 out_edge_keys :: HscSource -> [ModuleName] -> [Int]
1284 out_edge_keys hi_boot ms = mapCatMaybes (lookup_key hi_boot) ms
1285 -- If we want keep_hi_boot_nodes, then we do lookup_key with
1286 -- the IsBootInterface parameter True; else False
1289 type NodeKey = (ModuleName, HscSource) -- The nodes of the graph are
1290 type NodeMap a = FiniteMap NodeKey a -- keyed by (mod, src_file_type) pairs
1292 msKey :: ModSummary -> NodeKey
1293 msKey (ModSummary { ms_mod = mod, ms_hsc_src = boot }) = (moduleName mod,boot)
1295 mkNodeMap :: [ModSummary] -> NodeMap ModSummary
1296 mkNodeMap summaries = listToFM [ (msKey s, s) | s <- summaries]
1298 nodeMapElts :: NodeMap a -> [a]
1299 nodeMapElts = eltsFM
1301 ms_mod_name :: ModSummary -> ModuleName
1302 ms_mod_name = moduleName . ms_mod
1304 -- If there are {-# SOURCE #-} imports between strongly connected
1305 -- components in the topological sort, then those imports can
1306 -- definitely be replaced by ordinary non-SOURCE imports: if SOURCE
1307 -- were necessary, then the edge would be part of a cycle.
1308 warnUnnecessarySourceImports :: DynFlags -> [SCC ModSummary] -> IO ()
1309 warnUnnecessarySourceImports dflags sccs =
1310 printBagOfWarnings dflags (listToBag (concat (map (check.flattenSCC) sccs)))
1312 let mods_in_this_cycle = map ms_mod_name ms in
1313 [ warn m i | m <- ms, i <- ms_srcimps m,
1314 unLoc i `notElem` mods_in_this_cycle ]
1316 warn :: ModSummary -> Located ModuleName -> WarnMsg
1317 warn ms (L loc mod) =
1319 (ptext SLIT("Warning: {-# SOURCE #-} unnecessary in import of ")
1320 <+> quotes (ppr mod))
1322 -----------------------------------------------------------------------------
1323 -- Downsweep (dependency analysis)
1325 -- Chase downwards from the specified root set, returning summaries
1326 -- for all home modules encountered. Only follow source-import
1329 -- We pass in the previous collection of summaries, which is used as a
1330 -- cache to avoid recalculating a module summary if the source is
1333 -- The returned list of [ModSummary] nodes has one node for each home-package
1334 -- module, plus one for any hs-boot files. The imports of these nodes
1335 -- are all there, including the imports of non-home-package modules.
1338 -> [ModSummary] -- Old summaries
1339 -> [ModuleName] -- Ignore dependencies on these; treat
1340 -- them as if they were package modules
1341 -> Bool -- True <=> allow multiple targets to have
1342 -- the same module name; this is
1343 -- very useful for ghc -M
1344 -> IO (Maybe [ModSummary])
1345 -- The elts of [ModSummary] all have distinct
1346 -- (Modules, IsBoot) identifiers, unless the Bool is true
1347 -- in which case there can be repeats
1348 downsweep hsc_env old_summaries excl_mods allow_dup_roots
1349 = -- catch error messages and return them
1350 handleDyn (\err_msg -> printBagOfErrors (hsc_dflags hsc_env) (unitBag err_msg) >> return Nothing) $ do
1351 rootSummaries <- mapM getRootSummary roots
1352 let root_map = mkRootMap rootSummaries
1353 checkDuplicates root_map
1354 summs <- loop (concatMap msDeps rootSummaries) root_map
1357 roots = hsc_targets hsc_env
1359 old_summary_map :: NodeMap ModSummary
1360 old_summary_map = mkNodeMap old_summaries
1362 getRootSummary :: Target -> IO ModSummary
1363 getRootSummary (Target (TargetFile file mb_phase) maybe_buf)
1364 = do exists <- doesFileExist file
1366 then summariseFile hsc_env old_summaries file mb_phase maybe_buf
1367 else throwDyn $ mkPlainErrMsg noSrcSpan $
1368 text "can't find file:" <+> text file
1369 getRootSummary (Target (TargetModule modl) maybe_buf)
1370 = do maybe_summary <- summariseModule hsc_env old_summary_map False
1371 (L rootLoc modl) maybe_buf excl_mods
1372 case maybe_summary of
1373 Nothing -> packageModErr modl
1376 rootLoc = mkGeneralSrcSpan FSLIT("<command line>")
1378 -- In a root module, the filename is allowed to diverge from the module
1379 -- name, so we have to check that there aren't multiple root files
1380 -- defining the same module (otherwise the duplicates will be silently
1381 -- ignored, leading to confusing behaviour).
1382 checkDuplicates :: NodeMap [ModSummary] -> IO ()
1383 checkDuplicates root_map
1384 | allow_dup_roots = return ()
1385 | null dup_roots = return ()
1386 | otherwise = multiRootsErr (head dup_roots)
1388 dup_roots :: [[ModSummary]] -- Each at least of length 2
1389 dup_roots = filterOut isSingleton (nodeMapElts root_map)
1391 loop :: [(Located ModuleName,IsBootInterface)]
1392 -- Work list: process these modules
1393 -> NodeMap [ModSummary]
1394 -- Visited set; the range is a list because
1395 -- the roots can have the same module names
1396 -- if allow_dup_roots is True
1398 -- The result includes the worklist, except
1399 -- for those mentioned in the visited set
1400 loop [] done = return (concat (nodeMapElts done))
1401 loop ((wanted_mod, is_boot) : ss) done
1402 | Just summs <- lookupFM done key
1403 = if isSingleton summs then
1406 do { multiRootsErr summs; return [] }
1407 | otherwise = do { mb_s <- summariseModule hsc_env old_summary_map
1408 is_boot wanted_mod Nothing excl_mods
1410 Nothing -> loop ss done
1411 Just s -> loop (msDeps s ++ ss)
1412 (addToFM done key [s]) }
1414 key = (unLoc wanted_mod, if is_boot then HsBootFile else HsSrcFile)
1416 mkRootMap :: [ModSummary] -> NodeMap [ModSummary]
1417 mkRootMap summaries = addListToFM_C (++) emptyFM
1418 [ (msKey s, [s]) | s <- summaries ]
1420 msDeps :: ModSummary -> [(Located ModuleName, IsBootInterface)]
1421 -- (msDeps s) returns the dependencies of the ModSummary s.
1422 -- A wrinkle is that for a {-# SOURCE #-} import we return
1423 -- *both* the hs-boot file
1424 -- *and* the source file
1425 -- as "dependencies". That ensures that the list of all relevant
1426 -- modules always contains B.hs if it contains B.hs-boot.
1427 -- Remember, this pass isn't doing the topological sort. It's
1428 -- just gathering the list of all relevant ModSummaries
1430 concat [ [(m,True), (m,False)] | m <- ms_srcimps s ]
1431 ++ [ (m,False) | m <- ms_imps s ]
1433 -----------------------------------------------------------------------------
1434 -- Summarising modules
1436 -- We have two types of summarisation:
1438 -- * Summarise a file. This is used for the root module(s) passed to
1439 -- cmLoadModules. The file is read, and used to determine the root
1440 -- module name. The module name may differ from the filename.
1442 -- * Summarise a module. We are given a module name, and must provide
1443 -- a summary. The finder is used to locate the file in which the module
1448 -> [ModSummary] -- old summaries
1449 -> FilePath -- source file name
1450 -> Maybe Phase -- start phase
1451 -> Maybe (StringBuffer,ClockTime)
1454 summariseFile hsc_env old_summaries file mb_phase maybe_buf
1455 -- we can use a cached summary if one is available and the
1456 -- source file hasn't changed, But we have to look up the summary
1457 -- by source file, rather than module name as we do in summarise.
1458 | Just old_summary <- findSummaryBySourceFile old_summaries file
1460 let location = ms_location old_summary
1462 -- return the cached summary if the source didn't change
1463 src_timestamp <- case maybe_buf of
1464 Just (_,t) -> return t
1465 Nothing -> getModificationTime file
1466 -- The file exists; we checked in getRootSummary above.
1467 -- If it gets removed subsequently, then this
1468 -- getModificationTime may fail, but that's the right
1471 if ms_hs_date old_summary == src_timestamp
1472 then do -- update the object-file timestamp
1473 obj_timestamp <- getObjTimestamp location False
1474 return old_summary{ ms_obj_date = obj_timestamp }
1482 let dflags = hsc_dflags hsc_env
1484 (dflags', hspp_fn, buf)
1485 <- preprocessFile dflags file mb_phase maybe_buf
1487 (srcimps,the_imps, L _ mod_name) <- getImports dflags' buf hspp_fn
1489 -- Make a ModLocation for this file
1490 location <- mkHomeModLocation dflags mod_name file
1492 -- Tell the Finder cache where it is, so that subsequent calls
1493 -- to findModule will find it, even if it's not on any search path
1494 mod <- addHomeModuleToFinder hsc_env mod_name location
1496 src_timestamp <- case maybe_buf of
1497 Just (_,t) -> return t
1498 Nothing -> getModificationTime file
1499 -- getMofificationTime may fail
1501 obj_timestamp <- modificationTimeIfExists (ml_obj_file location)
1503 return (ModSummary { ms_mod = mod, ms_hsc_src = HsSrcFile,
1504 ms_location = location,
1505 ms_hspp_file = hspp_fn,
1506 ms_hspp_opts = dflags',
1507 ms_hspp_buf = Just buf,
1508 ms_srcimps = srcimps, ms_imps = the_imps,
1509 ms_hs_date = src_timestamp,
1510 ms_obj_date = obj_timestamp })
1512 findSummaryBySourceFile :: [ModSummary] -> FilePath -> Maybe ModSummary
1513 findSummaryBySourceFile summaries file
1514 = case [ ms | ms <- summaries, HsSrcFile <- [ms_hsc_src ms],
1515 expectJust "findSummaryBySourceFile" (ml_hs_file (ms_location ms)) == file ] of
1519 -- Summarise a module, and pick up source and timestamp.
1522 -> NodeMap ModSummary -- Map of old summaries
1523 -> IsBootInterface -- True <=> a {-# SOURCE #-} import
1524 -> Located ModuleName -- Imported module to be summarised
1525 -> Maybe (StringBuffer, ClockTime)
1526 -> [ModuleName] -- Modules to exclude
1527 -> IO (Maybe ModSummary) -- Its new summary
1529 summariseModule hsc_env old_summary_map is_boot (L loc wanted_mod) maybe_buf excl_mods
1530 | wanted_mod `elem` excl_mods
1533 | Just old_summary <- lookupFM old_summary_map (wanted_mod, hsc_src)
1534 = do -- Find its new timestamp; all the
1535 -- ModSummaries in the old map have valid ml_hs_files
1536 let location = ms_location old_summary
1537 src_fn = expectJust "summariseModule" (ml_hs_file location)
1539 -- check the modification time on the source file, and
1540 -- return the cached summary if it hasn't changed. If the
1541 -- file has disappeared, we need to call the Finder again.
1543 Just (_,t) -> check_timestamp old_summary location src_fn t
1545 m <- System.IO.Error.try (getModificationTime src_fn)
1547 Right t -> check_timestamp old_summary location src_fn t
1548 Left e | isDoesNotExistError e -> find_it
1549 | otherwise -> ioError e
1551 | otherwise = find_it
1553 dflags = hsc_dflags hsc_env
1555 hsc_src = if is_boot then HsBootFile else HsSrcFile
1557 check_timestamp old_summary location src_fn src_timestamp
1558 | ms_hs_date old_summary == src_timestamp = do
1559 -- update the object-file timestamp
1560 obj_timestamp <- getObjTimestamp location is_boot
1561 return (Just old_summary{ ms_obj_date = obj_timestamp })
1563 -- source changed: re-summarise.
1564 new_summary location (ms_mod old_summary) src_fn src_timestamp
1567 -- Don't use the Finder's cache this time. If the module was
1568 -- previously a package module, it may have now appeared on the
1569 -- search path, so we want to consider it to be a home module. If
1570 -- the module was previously a home module, it may have moved.
1571 uncacheModule hsc_env wanted_mod
1572 found <- findImportedModule hsc_env wanted_mod Nothing
1575 | isJust (ml_hs_file location) ->
1577 just_found location mod
1579 -- Drop external-pkg
1580 ASSERT(modulePackageId mod /= thisPackage dflags)
1584 err -> noModError dflags loc wanted_mod err
1587 just_found location mod = do
1588 -- Adjust location to point to the hs-boot source file,
1589 -- hi file, object file, when is_boot says so
1590 let location' | is_boot = addBootSuffixLocn location
1591 | otherwise = location
1592 src_fn = expectJust "summarise2" (ml_hs_file location')
1594 -- Check that it exists
1595 -- It might have been deleted since the Finder last found it
1596 maybe_t <- modificationTimeIfExists src_fn
1598 Nothing -> noHsFileErr loc src_fn
1599 Just t -> new_summary location' mod src_fn t
1602 new_summary location mod src_fn src_timestamp
1604 -- Preprocess the source file and get its imports
1605 -- The dflags' contains the OPTIONS pragmas
1606 (dflags', hspp_fn, buf) <- preprocessFile dflags src_fn Nothing maybe_buf
1607 (srcimps, the_imps, L mod_loc mod_name) <- getImports dflags' buf hspp_fn
1609 when (mod_name /= wanted_mod) $
1610 throwDyn $ mkPlainErrMsg mod_loc $
1611 text "file name does not match module name"
1612 <+> quotes (ppr mod_name)
1614 -- Find the object timestamp, and return the summary
1615 obj_timestamp <- getObjTimestamp location is_boot
1617 return (Just ( ModSummary { ms_mod = mod,
1618 ms_hsc_src = hsc_src,
1619 ms_location = location,
1620 ms_hspp_file = hspp_fn,
1621 ms_hspp_opts = dflags',
1622 ms_hspp_buf = Just buf,
1623 ms_srcimps = srcimps,
1625 ms_hs_date = src_timestamp,
1626 ms_obj_date = obj_timestamp }))
1629 getObjTimestamp location is_boot
1630 = if is_boot then return Nothing
1631 else modificationTimeIfExists (ml_obj_file location)
1634 preprocessFile :: DynFlags -> FilePath -> Maybe Phase -> Maybe (StringBuffer,ClockTime)
1635 -> IO (DynFlags, FilePath, StringBuffer)
1636 preprocessFile dflags src_fn mb_phase Nothing
1638 (dflags', hspp_fn) <- preprocess dflags (src_fn, mb_phase)
1639 buf <- hGetStringBuffer hspp_fn
1640 return (dflags', hspp_fn, buf)
1642 preprocessFile dflags src_fn mb_phase (Just (buf, time))
1644 -- case we bypass the preprocessing stage?
1646 local_opts = getOptions buf src_fn
1648 (dflags', errs) <- parseDynamicFlags dflags (map unLoc local_opts)
1652 | Just (Unlit _) <- mb_phase = True
1653 | Nothing <- mb_phase, Unlit _ <- startPhase src_fn = True
1654 -- note: local_opts is only required if there's no Unlit phase
1655 | dopt Opt_Cpp dflags' = True
1656 | dopt Opt_Pp dflags' = True
1659 when needs_preprocessing $
1660 ghcError (ProgramError "buffer needs preprocesing; interactive check disabled")
1662 return (dflags', src_fn, buf)
1665 -----------------------------------------------------------------------------
1667 -----------------------------------------------------------------------------
1669 noModError :: DynFlags -> SrcSpan -> ModuleName -> FindResult -> IO ab
1670 -- ToDo: we don't have a proper line number for this error
1671 noModError dflags loc wanted_mod err
1672 = throwDyn $ mkPlainErrMsg loc $ cannotFindModule dflags wanted_mod err
1674 noHsFileErr loc path
1675 = throwDyn $ mkPlainErrMsg loc $ text "Can't find" <+> text path
1678 = throwDyn $ mkPlainErrMsg noSrcSpan $
1679 text "module" <+> quotes (ppr mod) <+> text "is a package module"
1681 multiRootsErr :: [ModSummary] -> IO ()
1682 multiRootsErr summs@(summ1:_)
1683 = throwDyn $ mkPlainErrMsg noSrcSpan $
1684 text "module" <+> quotes (ppr mod) <+>
1685 text "is defined in multiple files:" <+>
1686 sep (map text files)
1689 files = map (expectJust "checkDup" . ml_hs_file . ms_location) summs
1691 cyclicModuleErr :: [ModSummary] -> SDoc
1693 = hang (ptext SLIT("Module imports form a cycle for modules:"))
1694 2 (vcat (map show_one ms))
1696 show_one ms = sep [ show_mod (ms_hsc_src ms) (ms_mod ms),
1697 nest 2 $ ptext SLIT("imports:") <+>
1698 (pp_imps HsBootFile (ms_srcimps ms)
1699 $$ pp_imps HsSrcFile (ms_imps ms))]
1700 show_mod hsc_src mod = ppr mod <> text (hscSourceString hsc_src)
1701 pp_imps src mods = fsep (map (show_mod src) mods)
1704 -- | Inform GHC that the working directory has changed. GHC will flush
1705 -- its cache of module locations, since it may no longer be valid.
1706 -- Note: if you change the working directory, you should also unload
1707 -- the current program (set targets to empty, followed by load).
1708 workingDirectoryChanged :: Session -> IO ()
1709 workingDirectoryChanged s = withSession s $ flushFinderCaches
1711 -- -----------------------------------------------------------------------------
1712 -- inspecting the session
1714 -- | Get the module dependency graph.
1715 getModuleGraph :: Session -> IO ModuleGraph -- ToDo: DiGraph ModSummary
1716 getModuleGraph s = withSession s (return . hsc_mod_graph)
1718 isLoaded :: Session -> ModuleName -> IO Bool
1719 isLoaded s m = withSession s $ \hsc_env ->
1720 return $! isJust (lookupUFM (hsc_HPT hsc_env) m)
1722 getBindings :: Session -> IO [TyThing]
1723 getBindings s = withSession s (return . nameEnvElts . ic_type_env . hsc_IC)
1725 getPrintUnqual :: Session -> IO PrintUnqualified
1726 getPrintUnqual s = withSession s (return . icPrintUnqual . hsc_IC)
1728 -- | Container for information about a 'Module'.
1729 data ModuleInfo = ModuleInfo {
1730 minf_type_env :: TypeEnv,
1731 minf_exports :: NameSet,
1732 minf_rdr_env :: Maybe GlobalRdrEnv, -- Nothing for a compiled/package mod
1733 minf_instances :: [Instance]
1734 -- ToDo: this should really contain the ModIface too
1736 -- We don't want HomeModInfo here, because a ModuleInfo applies
1737 -- to package modules too.
1739 -- | Request information about a loaded 'Module'
1740 getModuleInfo :: Session -> Module -> IO (Maybe ModuleInfo)
1741 getModuleInfo s mdl = withSession s $ \hsc_env -> do
1742 let mg = hsc_mod_graph hsc_env
1743 if mdl `elem` map ms_mod mg
1744 then getHomeModuleInfo hsc_env (moduleName mdl)
1746 {- if isHomeModule (hsc_dflags hsc_env) mdl
1748 else -} getPackageModuleInfo hsc_env mdl
1749 -- getPackageModuleInfo will attempt to find the interface, so
1750 -- we don't want to call it for a home module, just in case there
1751 -- was a problem loading the module and the interface doesn't
1752 -- exist... hence the isHomeModule test here. (ToDo: reinstate)
1754 getPackageModuleInfo :: HscEnv -> Module -> IO (Maybe ModuleInfo)
1755 getPackageModuleInfo hsc_env mdl = do
1757 (_msgs, mb_names) <- getModuleExports hsc_env mdl
1759 Nothing -> return Nothing
1761 eps <- readIORef (hsc_EPS hsc_env)
1764 n_list = nameSetToList names
1765 tys = [ ty | name <- n_list,
1766 Just ty <- [lookupTypeEnv pte name] ]
1768 return (Just (ModuleInfo {
1769 minf_type_env = mkTypeEnv tys,
1770 minf_exports = names,
1771 minf_rdr_env = Just $! nameSetToGlobalRdrEnv names (moduleName mdl),
1772 minf_instances = error "getModuleInfo: instances for package module unimplemented"
1775 -- bogusly different for non-GHCI (ToDo)
1779 getHomeModuleInfo hsc_env mdl =
1780 case lookupUFM (hsc_HPT hsc_env) mdl of
1781 Nothing -> return Nothing
1783 let details = hm_details hmi
1784 return (Just (ModuleInfo {
1785 minf_type_env = md_types details,
1786 minf_exports = md_exports details,
1787 minf_rdr_env = mi_globals $! hm_iface hmi,
1788 minf_instances = md_insts details
1791 -- | The list of top-level entities defined in a module
1792 modInfoTyThings :: ModuleInfo -> [TyThing]
1793 modInfoTyThings minf = typeEnvElts (minf_type_env minf)
1795 modInfoTopLevelScope :: ModuleInfo -> Maybe [Name]
1796 modInfoTopLevelScope minf
1797 = fmap (map gre_name . globalRdrEnvElts) (minf_rdr_env minf)
1799 modInfoExports :: ModuleInfo -> [Name]
1800 modInfoExports minf = nameSetToList $! minf_exports minf
1802 -- | Returns the instances defined by the specified module.
1803 -- Warning: currently unimplemented for package modules.
1804 modInfoInstances :: ModuleInfo -> [Instance]
1805 modInfoInstances = minf_instances
1807 modInfoIsExportedName :: ModuleInfo -> Name -> Bool
1808 modInfoIsExportedName minf name = elemNameSet name (minf_exports minf)
1810 modInfoPrintUnqualified :: ModuleInfo -> Maybe PrintUnqualified
1811 modInfoPrintUnqualified minf = fmap mkPrintUnqualified (minf_rdr_env minf)
1813 modInfoLookupName :: Session -> ModuleInfo -> Name -> IO (Maybe TyThing)
1814 modInfoLookupName s minf name = withSession s $ \hsc_env -> do
1815 case lookupTypeEnv (minf_type_env minf) name of
1816 Just tyThing -> return (Just tyThing)
1818 eps <- readIORef (hsc_EPS hsc_env)
1819 return $! lookupType (hsc_dflags hsc_env)
1820 (hsc_HPT hsc_env) (eps_PTE eps) name
1822 isDictonaryId :: Id -> Bool
1824 = case tcSplitSigmaTy (idType id) of { (tvs, theta, tau) -> isDictTy tau }
1826 -- | Looks up a global name: that is, any top-level name in any
1827 -- visible module. Unlike 'lookupName', lookupGlobalName does not use
1828 -- the interactive context, and therefore does not require a preceding
1830 lookupGlobalName :: Session -> Name -> IO (Maybe TyThing)
1831 lookupGlobalName s name = withSession s $ \hsc_env -> do
1832 eps <- readIORef (hsc_EPS hsc_env)
1833 return $! lookupType (hsc_dflags hsc_env)
1834 (hsc_HPT hsc_env) (eps_PTE eps) name
1836 -- -----------------------------------------------------------------------------
1837 -- Misc exported utils
1839 dataConType :: DataCon -> Type
1840 dataConType dc = idType (dataConWrapId dc)
1842 -- | print a 'NamedThing', adding parentheses if the name is an operator.
1843 pprParenSymName :: NamedThing a => a -> SDoc
1844 pprParenSymName a = parenSymOcc (getOccName a) (ppr (getName a))
1846 -- ----------------------------------------------------------------------------
1851 -- - Data and Typeable instances for HsSyn.
1853 -- ToDo: check for small transformations that happen to the syntax in
1854 -- the typechecker (eg. -e ==> negate e, perhaps for fromIntegral)
1856 -- ToDo: maybe use TH syntax instead of IfaceSyn? There's already a way
1857 -- to get from TyCons, Ids etc. to TH syntax (reify).
1859 -- :browse will use either lm_toplev or inspect lm_interface, depending
1860 -- on whether the module is interpreted or not.
1862 -- This is for reconstructing refactored source code
1863 -- Calls the lexer repeatedly.
1864 -- ToDo: add comment tokens to token stream
1865 getTokenStream :: Session -> Module -> IO [Located Token]
1868 -- -----------------------------------------------------------------------------
1869 -- Interactive evaluation
1871 -- | Takes a 'ModuleName' and possibly a 'PackageId', and consults the
1872 -- filesystem and package database to find the corresponding 'Module',
1873 -- using the algorithm that is used for an @import@ declaration.
1874 findModule :: Session -> ModuleName -> Maybe PackageId -> IO Module
1875 findModule s mod_name maybe_pkg = withSession s $ \hsc_env ->
1876 findModule' hsc_env mod_name maybe_pkg
1878 findModule' hsc_env mod_name maybe_pkg =
1880 dflags = hsc_dflags hsc_env
1881 hpt = hsc_HPT hsc_env
1882 this_pkg = thisPackage dflags
1884 case lookupUFM hpt mod_name of
1885 Just mod_info -> return (mi_module (hm_iface mod_info))
1886 _not_a_home_module -> do
1887 res <- findImportedModule hsc_env mod_name Nothing
1889 Found _ m | modulePackageId m /= this_pkg -> return m
1890 | otherwise -> throwDyn (CmdLineError (showSDoc $
1891 text "module" <+> pprModule m <+>
1892 text "is not loaded"))
1893 err -> let msg = cannotFindModule dflags mod_name err in
1894 throwDyn (CmdLineError (showSDoc msg))
1898 -- | Set the interactive evaluation context.
1900 -- Setting the context doesn't throw away any bindings; the bindings
1901 -- we've built up in the InteractiveContext simply move to the new
1902 -- module. They always shadow anything in scope in the current context.
1903 setContext :: Session
1904 -> [Module] -- entire top level scope of these modules
1905 -> [Module] -- exports only of these modules
1907 setContext (Session ref) toplev_mods export_mods = do
1908 hsc_env <- readIORef ref
1909 let old_ic = hsc_IC hsc_env
1910 hpt = hsc_HPT hsc_env
1912 export_env <- mkExportEnv hsc_env export_mods
1913 toplev_envs <- mapM (mkTopLevEnv hpt) toplev_mods
1914 let all_env = foldr plusGlobalRdrEnv export_env toplev_envs
1915 writeIORef ref hsc_env{ hsc_IC = old_ic { ic_toplev_scope = toplev_mods,
1916 ic_exports = export_mods,
1917 ic_rn_gbl_env = all_env }}
1920 -- Make a GlobalRdrEnv based on the exports of the modules only.
1921 mkExportEnv :: HscEnv -> [Module] -> IO GlobalRdrEnv
1922 mkExportEnv hsc_env mods = do
1923 stuff <- mapM (getModuleExports hsc_env) mods
1925 (_msgs, mb_name_sets) = unzip stuff
1926 gres = [ nameSetToGlobalRdrEnv name_set (moduleName mod)
1927 | (Just name_set, mod) <- zip mb_name_sets mods ]
1929 return $! foldr plusGlobalRdrEnv emptyGlobalRdrEnv gres
1931 nameSetToGlobalRdrEnv :: NameSet -> ModuleName -> GlobalRdrEnv
1932 nameSetToGlobalRdrEnv names mod =
1933 mkGlobalRdrEnv [ GRE { gre_name = name, gre_prov = vanillaProv mod }
1934 | name <- nameSetToList names ]
1936 vanillaProv :: ModuleName -> Provenance
1937 -- We're building a GlobalRdrEnv as if the user imported
1938 -- all the specified modules into the global interactive module
1939 vanillaProv mod_name = Imported [ImpSpec { is_decl = decl, is_item = ImpAll}]
1941 decl = ImpDeclSpec { is_mod = mod_name, is_as = mod_name,
1943 is_dloc = srcLocSpan interactiveSrcLoc }
1945 mkTopLevEnv :: HomePackageTable -> Module -> IO GlobalRdrEnv
1946 mkTopLevEnv hpt modl
1947 = case lookupUFM hpt (moduleName modl) of
1948 Nothing -> throwDyn (ProgramError ("mkTopLevEnv: not a home module " ++
1949 showSDoc (ppr modl)))
1951 case mi_globals (hm_iface details) of
1953 throwDyn (ProgramError ("mkTopLevEnv: not interpreted "
1954 ++ showSDoc (ppr modl)))
1955 Just env -> return env
1957 -- | Get the interactive evaluation context, consisting of a pair of the
1958 -- set of modules from which we take the full top-level scope, and the set
1959 -- of modules from which we take just the exports respectively.
1960 getContext :: Session -> IO ([Module],[Module])
1961 getContext s = withSession s (\HscEnv{ hsc_IC=ic } ->
1962 return (ic_toplev_scope ic, ic_exports ic))
1964 -- | Returns 'True' if the specified module is interpreted, and hence has
1965 -- its full top-level scope available.
1966 moduleIsInterpreted :: Session -> Module -> IO Bool
1967 moduleIsInterpreted s modl = withSession s $ \h ->
1968 if modulePackageId modl /= thisPackage (hsc_dflags h)
1970 else case lookupUFM (hsc_HPT h) (moduleName modl) of
1971 Just details -> return (isJust (mi_globals (hm_iface details)))
1972 _not_a_home_module -> return False
1974 -- | Looks up an identifier in the current interactive context (for :info)
1975 getInfo :: Session -> Name -> IO (Maybe (TyThing,Fixity,[Instance]))
1976 getInfo s name = withSession s $ \hsc_env -> tcRnGetInfo hsc_env name
1978 -- | Returns all names in scope in the current interactive context
1979 getNamesInScope :: Session -> IO [Name]
1980 getNamesInScope s = withSession s $ \hsc_env -> do
1981 return (map gre_name (globalRdrEnvElts (ic_rn_gbl_env (hsc_IC hsc_env))))
1983 getRdrNamesInScope :: Session -> IO [RdrName]
1984 getRdrNamesInScope s = withSession s $ \hsc_env -> do
1985 let env = ic_rn_gbl_env (hsc_IC hsc_env)
1986 return (concat (map greToRdrNames (globalRdrEnvElts env)))
1988 -- ToDo: move to RdrName
1989 greToRdrNames :: GlobalRdrElt -> [RdrName]
1990 greToRdrNames GRE{ gre_name = name, gre_prov = prov }
1992 LocalDef -> [unqual]
1993 Imported specs -> concat (map do_spec (map is_decl specs))
1995 occ = nameOccName name
1998 | is_qual decl_spec = [qual]
1999 | otherwise = [unqual,qual]
2000 where qual = Qual (is_as decl_spec) occ
2002 -- | Parses a string as an identifier, and returns the list of 'Name's that
2003 -- the identifier can refer to in the current interactive context.
2004 parseName :: Session -> String -> IO [Name]
2005 parseName s str = withSession s $ \hsc_env -> do
2006 maybe_rdr_name <- hscParseIdentifier (hsc_dflags hsc_env) str
2007 case maybe_rdr_name of
2008 Nothing -> return []
2009 Just (L _ rdr_name) -> do
2010 mb_names <- tcRnLookupRdrName hsc_env rdr_name
2012 Nothing -> return []
2013 Just ns -> return ns
2014 -- ToDo: should return error messages
2016 -- | Returns the 'TyThing' for a 'Name'. The 'Name' may refer to any
2017 -- entity known to GHC, including 'Name's defined using 'runStmt'.
2018 lookupName :: Session -> Name -> IO (Maybe TyThing)
2019 lookupName s name = withSession s $ \hsc_env -> tcRnLookupName hsc_env name
2021 -- -----------------------------------------------------------------------------
2022 -- Getting the type of an expression
2024 -- | Get the type of an expression
2025 exprType :: Session -> String -> IO (Maybe Type)
2026 exprType s expr = withSession s $ \hsc_env -> do
2027 maybe_stuff <- hscTcExpr hsc_env expr
2029 Nothing -> return Nothing
2030 Just ty -> return (Just tidy_ty)
2032 tidy_ty = tidyType emptyTidyEnv ty
2034 -- -----------------------------------------------------------------------------
2035 -- Getting the kind of a type
2037 -- | Get the kind of a type
2038 typeKind :: Session -> String -> IO (Maybe Kind)
2039 typeKind s str = withSession s $ \hsc_env -> do
2040 maybe_stuff <- hscKcType hsc_env str
2042 Nothing -> return Nothing
2043 Just kind -> return (Just kind)
2045 -----------------------------------------------------------------------------
2046 -- cmCompileExpr: compile an expression and deliver an HValue
2048 compileExpr :: Session -> String -> IO (Maybe HValue)
2049 compileExpr s expr = withSession s $ \hsc_env -> do
2050 maybe_stuff <- hscStmt hsc_env ("let __cmCompileExpr = "++expr)
2052 Nothing -> return Nothing
2053 Just (new_ic, names, hval) -> do
2055 hvals <- (unsafeCoerce# hval) :: IO [HValue]
2057 case (names,hvals) of
2058 ([n],[hv]) -> return (Just hv)
2059 _ -> panic "compileExpr"
2061 -- -----------------------------------------------------------------------------
2062 -- Compile an expression into a dynamic
2064 dynCompileExpr :: Session -> String -> IO (Maybe Dynamic)
2065 dynCompileExpr ses expr = do
2066 (full,exports) <- getContext ses
2067 setContext ses full $
2069 (stringToPackageId "base") (mkModuleName "Data.Dynamic")
2071 let stmt = "let __dynCompileExpr = Data.Dynamic.toDyn (" ++ expr ++ ")"
2072 res <- withSession ses (flip hscStmt stmt)
2073 setContext ses full exports
2075 Nothing -> return Nothing
2076 Just (_, names, hvals) -> do
2077 vals <- (unsafeCoerce# hvals :: IO [Dynamic])
2078 case (names,vals) of
2079 (_:[], v:[]) -> return (Just v)
2080 _ -> panic "dynCompileExpr"
2082 -- -----------------------------------------------------------------------------
2083 -- running a statement interactively
2086 = RunOk [Name] -- ^ names bound by this evaluation
2087 | RunFailed -- ^ statement failed compilation
2088 | RunException Exception -- ^ statement raised an exception
2090 -- | Run a statement in the current interactive context. Statemenet
2091 -- may bind multple values.
2092 runStmt :: Session -> String -> IO RunResult
2093 runStmt (Session ref) expr
2095 hsc_env <- readIORef ref
2097 -- Turn off -fwarn-unused-bindings when running a statement, to hide
2098 -- warnings about the implicit bindings we introduce.
2099 let dflags' = dopt_unset (hsc_dflags hsc_env) Opt_WarnUnusedBinds
2100 hsc_env' = hsc_env{ hsc_dflags = dflags' }
2102 maybe_stuff <- hscStmt hsc_env' expr
2105 Nothing -> return RunFailed
2106 Just (new_hsc_env, names, hval) -> do
2108 let thing_to_run = unsafeCoerce# hval :: IO [HValue]
2109 either_hvals <- sandboxIO thing_to_run
2111 case either_hvals of
2113 -- on error, keep the *old* interactive context,
2114 -- so that 'it' is not bound to something
2115 -- that doesn't exist.
2116 return (RunException e)
2119 -- Get the newly bound things, and bind them.
2120 -- Don't need to delete any shadowed bindings;
2121 -- the new ones override the old ones.
2122 extendLinkEnv (zip names hvals)
2124 writeIORef ref new_hsc_env
2125 return (RunOk names)
2127 -- When running a computation, we redirect ^C exceptions to the running
2128 -- thread. ToDo: we might want a way to continue even if the target
2129 -- thread doesn't die when it receives the exception... "this thread
2130 -- is not responding".
2131 sandboxIO :: IO a -> IO (Either Exception a)
2132 sandboxIO thing = do
2134 ts <- takeMVar interruptTargetThread
2135 child <- forkIO (do res <- Exception.try thing; putMVar m res)
2136 putMVar interruptTargetThread (child:ts)
2137 takeMVar m `finally` modifyMVar_ interruptTargetThread (return.tail)
2140 -- This version of sandboxIO runs the expression in a completely new
2141 -- RTS main thread. It is disabled for now because ^C exceptions
2142 -- won't be delivered to the new thread, instead they'll be delivered
2143 -- to the (blocked) GHCi main thread.
2145 -- SLPJ: when re-enabling this, reflect a wrong-stat error as an exception
2147 sandboxIO :: IO a -> IO (Either Int (Either Exception a))
2148 sandboxIO thing = do
2149 st_thing <- newStablePtr (Exception.try thing)
2150 alloca $ \ p_st_result -> do
2151 stat <- rts_evalStableIO st_thing p_st_result
2152 freeStablePtr st_thing
2154 then do st_result <- peek p_st_result
2155 result <- deRefStablePtr st_result
2156 freeStablePtr st_result
2157 return (Right result)
2159 return (Left (fromIntegral stat))
2161 foreign import "rts_evalStableIO" {- safe -}
2162 rts_evalStableIO :: StablePtr (IO a) -> Ptr (StablePtr a) -> IO CInt
2163 -- more informative than the C type!
2166 -----------------------------------------------------------------------------
2167 -- show a module and it's source/object filenames
2169 showModule :: Session -> ModSummary -> IO String
2170 showModule s mod_summary = withSession s $ \hsc_env -> do
2171 case lookupUFM (hsc_HPT hsc_env) (ms_mod_name mod_summary) of
2172 Nothing -> panic "missing linkable"
2173 Just mod_info -> return (showModMsg (hscTarget (hsc_dflags hsc_env)) (not obj_linkable) mod_summary)
2175 obj_linkable = isObjectLinkable (expectJust "showModule" (hm_linkable mod_info))