Breakpoint code instrumentation
[ghc.git] / compiler / main / GHC.hs
1 -- -----------------------------------------------------------------------------
2 --
3 -- (c) The University of Glasgow, 2005
4 --
5 -- The GHC API
6 --
7 -- -----------------------------------------------------------------------------
8
9 module GHC (
10 -- * Initialisation
11 Session,
12 defaultErrorHandler,
13 defaultCleanupHandler,
14 newSession,
15
16 -- * Flags and settings
17 DynFlags(..), DynFlag(..), Severity(..), GhcMode(..), HscTarget(..), dopt,
18 parseDynamicFlags,
19 getSessionDynFlags,
20 setSessionDynFlags,
21
22 -- * Targets
23 Target(..), TargetId(..), Phase,
24 setTargets,
25 getTargets,
26 addTarget,
27 removeTarget,
28 guessTarget,
29
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 ()
35
36 -- * Loading\/compiling the program
37 depanal,
38 load, LoadHowMuch(..), SuccessFlag(..), -- also does depanal
39 workingDirectoryChanged,
40 checkModule, CheckedModule(..),
41 TypecheckedSource, ParsedSource, RenamedSource,
42
43 -- * Parsing Haddock comments
44 parseHaddockComment,
45
46 -- * Inspecting the module structure of the program
47 ModuleGraph, ModSummary(..), ms_mod_name, ModLocation(..),
48 getModuleGraph,
49 isLoaded,
50 topSortModuleGraph,
51
52 -- * Inspecting modules
53 ModuleInfo,
54 getModuleInfo,
55 modInfoTyThings,
56 modInfoTopLevelScope,
57 modInfoPrintUnqualified,
58 modInfoExports,
59 modInfoInstances,
60 modInfoIsExportedName,
61 modInfoLookupName,
62 #if defined(GHCI)
63 modInfoBkptSites,
64 #endif
65 lookupGlobalName,
66
67 -- * Printing
68 PrintUnqualified, alwaysQualify,
69
70 -- * Interactive evaluation
71 getBindings, getPrintUnqual,
72 findModule,
73 #ifdef GHCI
74 setContext, getContext,
75 getNamesInScope,
76 getRdrNamesInScope,
77 moduleIsInterpreted,
78 getInfo,
79 exprType,
80 typeKind,
81 parseName,
82 RunResult(..),
83 runStmt,
84 showModule,
85 compileExpr, HValue, dynCompileExpr,
86 lookupName,
87
88 getBreakpointHandler, setBreakpointHandler,
89 obtainTerm,
90 #endif
91
92 -- * Abstract syntax elements
93
94 -- ** Packages
95 PackageId,
96
97 -- ** Modules
98 Module, mkModule, pprModule, moduleName, modulePackageId,
99 ModuleName, mkModuleName, moduleNameString,
100
101 -- ** Names
102 Name,
103 nameModule, pprParenSymName, nameSrcLoc,
104 NamedThing(..),
105 RdrName(Qual,Unqual),
106
107 -- ** Identifiers
108 Id, idType,
109 isImplicitId, isDeadBinder,
110 isExportedId, isLocalId, isGlobalId,
111 isRecordSelector,
112 isPrimOpId, isFCallId, isClassOpId_maybe,
113 isDataConWorkId, idDataCon,
114 isBottomingId, isDictonaryId,
115 recordSelectorFieldLabel,
116
117 -- ** Type constructors
118 TyCon,
119 tyConTyVars, tyConDataCons, tyConArity,
120 isClassTyCon, isSynTyCon, isNewTyCon, isPrimTyCon, isFunTyCon,
121 isOpenTyCon,
122 synTyConDefn, synTyConType, synTyConResKind,
123
124 -- ** Type variables
125 TyVar,
126 alphaTyVars,
127
128 -- ** Data constructors
129 DataCon,
130 dataConSig, dataConType, dataConTyCon, dataConFieldLabels,
131 dataConIsInfix, isVanillaDataCon,
132 dataConStrictMarks,
133 StrictnessMark(..), isMarkedStrict,
134
135 -- ** Classes
136 Class,
137 classMethods, classSCTheta, classTvsFds,
138 pprFundeps,
139
140 -- ** Instances
141 Instance,
142 instanceDFunId, pprInstance, pprInstanceHdr,
143
144 -- ** Types and Kinds
145 Type, dropForAlls, splitForAllTys, funResultTy, pprParendType,
146 Kind,
147 PredType,
148 ThetaType, pprThetaArrow,
149
150 -- ** Entities
151 TyThing(..),
152
153 -- ** Syntax
154 module HsSyn, -- ToDo: remove extraneous bits
155
156 -- ** Fixities
157 FixityDirection(..),
158 defaultFixity, maxPrecedence,
159 negateFixity,
160 compareFixity,
161
162 -- ** Source locations
163 SrcLoc, pprDefnLoc,
164
165 -- * Exceptions
166 GhcException(..), showGhcException,
167
168 -- * Miscellaneous
169 sessionHscEnv,
170 cyclicModuleErr,
171 ) where
172
173 {-
174 ToDo:
175
176 * inline bits of HscMain here to simplify layering: hscTcExpr, hscStmt.
177 * what StaticFlags should we expose, if any?
178 -}
179
180 #include "HsVersions.h"
181
182 #ifdef GHCI
183 import TcRnDriver ( tcRnLookupRdrName, tcRnGetInfo,
184 tcRnLookupName, getModuleExports )
185 import RdrName ( plusGlobalRdrEnv, Provenance(..),
186 ImportSpec(..), ImpDeclSpec(..), ImpItemSpec(..),
187 mkGlobalRdrEnv )
188 import HscMain ( hscParseIdentifier, hscStmt, hscTcExpr, hscKcType )
189 import Name ( nameOccName )
190 import Type ( tidyType )
191 import VarEnv ( emptyTidyEnv )
192 import GHC.Exts ( unsafeCoerce# )
193
194 -- For breakpoints
195 import Breakpoints ( SiteNumber, Coord, nullBkptHandler,
196 BkptHandler(..), BkptLocation, noDbgSites )
197 import Linker ( initDynLinker )
198 import PrelNames ( breakpointJumpName, breakpointCondJumpName,
199 breakpointAutoJumpName )
200
201 import GHC.Exts ( Int(..), Ptr(..), int2Addr#, indexArray# )
202 import GHC.Base ( Opaque(..) )
203 import Foreign.StablePtr( deRefStablePtr, castPtrToStablePtr )
204 import Foreign ( unsafePerformIO )
205 import Data.Maybe ( fromMaybe)
206 import qualified Linker
207
208 import Data.Dynamic ( Dynamic )
209 import RtClosureInspect ( cvObtainTerm, Term )
210 import Linker ( HValue, getHValue, extendLinkEnv )
211 #endif
212
213 import Packages ( initPackages )
214 import NameSet ( NameSet, nameSetToList, elemNameSet )
215 import RdrName ( GlobalRdrEnv, GlobalRdrElt(..), RdrName(..),
216 globalRdrEnvElts, extendGlobalRdrEnv,
217 emptyGlobalRdrEnv )
218 import HsSyn
219 import Type ( Kind, Type, dropForAlls, PredType, ThetaType,
220 pprThetaArrow, pprParendType, splitForAllTys,
221 funResultTy )
222 import Id ( Id, idType, isImplicitId, isDeadBinder,
223 isExportedId, isLocalId, isGlobalId,
224 isRecordSelector, recordSelectorFieldLabel,
225 isPrimOpId, isFCallId, isClassOpId_maybe,
226 isDataConWorkId, idDataCon,
227 isBottomingId )
228 import Var ( TyVar, varName )
229 import TysPrim ( alphaTyVars )
230 import TyCon ( TyCon, isClassTyCon, isSynTyCon, isNewTyCon,
231 isPrimTyCon, isFunTyCon, isOpenTyCon, tyConArity,
232 tyConTyVars, tyConDataCons, synTyConDefn,
233 synTyConType, synTyConResKind )
234 import Class ( Class, classSCTheta, classTvsFds, classMethods )
235 import FunDeps ( pprFundeps )
236 import DataCon ( DataCon, dataConWrapId, dataConSig, dataConTyCon,
237 dataConFieldLabels, dataConStrictMarks,
238 dataConIsInfix, isVanillaDataCon )
239 import Name ( Name, nameModule, NamedThing(..), nameSrcLoc )
240 import OccName ( parenSymOcc )
241 import NameEnv ( nameEnvElts )
242 import InstEnv ( Instance, instanceDFunId, pprInstance, pprInstanceHdr )
243 import SrcLoc
244 import DriverPipeline
245 import DriverPhases ( Phase(..), isHaskellSrcFilename, startPhase )
246 import HeaderInfo ( getImports, getOptions )
247 import Finder
248 import HscMain ( newHscEnv, hscFileCheck, HscChecked(..) )
249 import HscTypes
250 import DynFlags
251 import SysTools ( initSysTools, cleanTempFiles, cleanTempFilesExcept,
252 cleanTempDirs )
253 import Module
254 import UniqFM
255 import PackageConfig ( PackageId, stringToPackageId )
256 import FiniteMap
257 import Panic
258 import Digraph
259 import Bag ( unitBag, listToBag )
260 import ErrUtils ( Severity(..), showPass, fatalErrorMsg, debugTraceMsg,
261 mkPlainErrMsg, printBagOfErrors, printBagOfWarnings,
262 WarnMsg )
263 import qualified ErrUtils
264 import Util
265 import StringBuffer ( StringBuffer, hGetStringBuffer )
266 import Outputable
267 import BasicTypes
268 import TcType ( tcSplitSigmaTy, isDictTy )
269 import Maybes ( expectJust, mapCatMaybes )
270 import HaddockParse ( parseHaddockParagraphs, parseHaddockString )
271 import HaddockLex ( tokenise )
272
273 import Control.Concurrent
274 import System.Directory ( getModificationTime, doesFileExist )
275 import Data.Maybe ( isJust, isNothing )
276 import Data.List ( partition, nub )
277 import qualified Data.List as List
278 import Control.Monad ( unless, when )
279 import System.Exit ( exitWith, ExitCode(..) )
280 import System.Time ( ClockTime )
281 import Control.Exception as Exception hiding (handle)
282 import Data.IORef
283 import Data.Traversable ( traverse )
284 import System.IO
285 import System.IO.Error ( isDoesNotExistError )
286 import Prelude hiding (init)
287
288 #if __GLASGOW_HASKELL__ < 600
289 import System.IO as System.IO.Error ( try )
290 #else
291 import System.IO.Error ( try )
292 #endif
293
294 -- -----------------------------------------------------------------------------
295 -- Exception handlers
296
297 -- | Install some default exception handlers and run the inner computation.
298 -- Unless you want to handle exceptions yourself, you should wrap this around
299 -- the top level of your program. The default handlers output the error
300 -- message(s) to stderr and exit cleanly.
301 defaultErrorHandler :: DynFlags -> IO a -> IO a
302 defaultErrorHandler dflags inner =
303 -- top-level exception handler: any unrecognised exception is a compiler bug.
304 handle (\exception -> do
305 hFlush stdout
306 case exception of
307 -- an IO exception probably isn't our fault, so don't panic
308 IOException _ ->
309 fatalErrorMsg dflags (text (show exception))
310 AsyncException StackOverflow ->
311 fatalErrorMsg dflags (text "stack overflow: use +RTS -K<size> to increase it")
312 _other ->
313 fatalErrorMsg dflags (text (show (Panic (show exception))))
314 exitWith (ExitFailure 1)
315 ) $
316
317 -- program errors: messages with locations attached. Sometimes it is
318 -- convenient to just throw these as exceptions.
319 handleDyn (\dyn -> do printBagOfErrors dflags (unitBag dyn)
320 exitWith (ExitFailure 1)) $
321
322 -- error messages propagated as exceptions
323 handleDyn (\dyn -> do
324 hFlush stdout
325 case dyn of
326 PhaseFailed _ code -> exitWith code
327 Interrupted -> exitWith (ExitFailure 1)
328 _ -> do fatalErrorMsg dflags (text (show (dyn :: GhcException)))
329 exitWith (ExitFailure 1)
330 ) $
331 inner
332
333 -- | Install a default cleanup handler to remove temporary files
334 -- deposited by a GHC run. This is seperate from
335 -- 'defaultErrorHandler', because you might want to override the error
336 -- handling, but still get the ordinary cleanup behaviour.
337 defaultCleanupHandler :: DynFlags -> IO a -> IO a
338 defaultCleanupHandler dflags inner =
339 -- make sure we clean up after ourselves
340 later (unless (dopt Opt_KeepTmpFiles dflags) $
341 do cleanTempFiles dflags
342 cleanTempDirs dflags
343 )
344 -- exceptions will be blocked while we clean the temporary files,
345 -- so there shouldn't be any difficulty if we receive further
346 -- signals.
347 inner
348
349
350 #if defined(GHCI)
351 GLOBAL_VAR(v_bkptLinkEnv, [], [(Name, HValue)])
352 -- stores the current breakpoint handler to help setContext to
353 -- restore it after a context change
354 #endif
355
356 -- | Starts a new session. A session consists of a set of loaded
357 -- modules, a set of options (DynFlags), and an interactive context.
358 -- ToDo: GhcMode should say "keep typechecked code" and\/or "keep renamed
359 -- code".
360 newSession :: GhcMode -> Maybe FilePath -> IO Session
361 newSession mode mb_top_dir = do
362 -- catch ^C
363 main_thread <- myThreadId
364 modifyMVar_ interruptTargetThread (return . (main_thread :))
365 installSignalHandlers
366
367 dflags0 <- initSysTools mb_top_dir defaultDynFlags
368 dflags <- initDynFlags dflags0
369 env <- newHscEnv dflags{ ghcMode=mode }
370 ref <- newIORef env
371 return (Session ref)
372
373 -- tmp: this breaks the abstraction, but required because DriverMkDepend
374 -- needs to call the Finder. ToDo: untangle this.
375 sessionHscEnv :: Session -> IO HscEnv
376 sessionHscEnv (Session ref) = readIORef ref
377
378 withSession :: Session -> (HscEnv -> IO a) -> IO a
379 withSession (Session ref) f = do h <- readIORef ref; f h
380
381 modifySession :: Session -> (HscEnv -> HscEnv) -> IO ()
382 modifySession (Session ref) f = do h <- readIORef ref; writeIORef ref $! f h
383
384 -- -----------------------------------------------------------------------------
385 -- Flags & settings
386
387 -- | Grabs the DynFlags from the Session
388 getSessionDynFlags :: Session -> IO DynFlags
389 getSessionDynFlags s = withSession s (return . hsc_dflags)
390
391 -- | Updates the DynFlags in a Session. This also reads
392 -- the package database (unless it has already been read),
393 -- and prepares the compilers knowledge about packages. It
394 -- can be called again to load new packages: just add new
395 -- package flags to (packageFlags dflags).
396 --
397 -- Returns a list of new packages that may need to be linked in using
398 -- the dynamic linker (see 'linkPackages') as a result of new package
399 -- flags. If you are not doing linking or doing static linking, you
400 -- can ignore the list of packages returned.
401 --
402 setSessionDynFlags :: Session -> DynFlags -> IO [PackageId]
403 setSessionDynFlags (Session ref) dflags = do
404 hsc_env <- readIORef ref
405 (dflags', preload) <- initPackages dflags
406 writeIORef ref $! hsc_env{ hsc_dflags = dflags' }
407 return preload
408
409 -- | If there is no -o option, guess the name of target executable
410 -- by using top-level source file name as a base.
411 guessOutputFile :: Session -> IO ()
412 guessOutputFile s = modifySession s $ \env ->
413 let dflags = hsc_dflags env
414 mod_graph = hsc_mod_graph env
415 mainModuleSrcPath, guessedName :: Maybe String
416 mainModuleSrcPath = do
417 let isMain = (== mainModIs dflags) . ms_mod
418 [ms] <- return (filter isMain mod_graph)
419 ml_hs_file (ms_location ms)
420 guessedName = fmap basenameOf mainModuleSrcPath
421 in
422 case outputFile dflags of
423 Just _ -> env
424 Nothing -> env { hsc_dflags = dflags { outputFile = guessedName } }
425
426 -- -----------------------------------------------------------------------------
427 -- Targets
428
429 -- ToDo: think about relative vs. absolute file paths. And what
430 -- happens when the current directory changes.
431
432 -- | Sets the targets for this session. Each target may be a module name
433 -- or a filename. The targets correspond to the set of root modules for
434 -- the program\/library. Unloading the current program is achieved by
435 -- setting the current set of targets to be empty, followed by load.
436 setTargets :: Session -> [Target] -> IO ()
437 setTargets s targets = modifySession s (\h -> h{ hsc_targets = targets })
438
439 -- | returns the current set of targets
440 getTargets :: Session -> IO [Target]
441 getTargets s = withSession s (return . hsc_targets)
442
443 -- | Add another target
444 addTarget :: Session -> Target -> IO ()
445 addTarget s target
446 = modifySession s (\h -> h{ hsc_targets = target : hsc_targets h })
447
448 -- | Remove a target
449 removeTarget :: Session -> TargetId -> IO ()
450 removeTarget s target_id
451 = modifySession s (\h -> h{ hsc_targets = filter (hsc_targets h) })
452 where
453 filter targets = [ t | t@(Target id _) <- targets, id /= target_id ]
454
455 -- Attempts to guess what Target a string refers to. This function implements
456 -- the --make/GHCi command-line syntax for filenames:
457 --
458 -- - if the string looks like a Haskell source filename, then interpret
459 -- it as such
460 -- - if adding a .hs or .lhs suffix yields the name of an existing file,
461 -- then use that
462 -- - otherwise interpret the string as a module name
463 --
464 guessTarget :: String -> Maybe Phase -> IO Target
465 guessTarget file (Just phase)
466 = return (Target (TargetFile file (Just phase)) Nothing)
467 guessTarget file Nothing
468 | isHaskellSrcFilename file
469 = return (Target (TargetFile file Nothing) Nothing)
470 | otherwise
471 = do exists <- doesFileExist hs_file
472 if exists
473 then return (Target (TargetFile hs_file Nothing) Nothing)
474 else do
475 exists <- doesFileExist lhs_file
476 if exists
477 then return (Target (TargetFile lhs_file Nothing) Nothing)
478 else do
479 return (Target (TargetModule (mkModuleName file)) Nothing)
480 where
481 hs_file = file `joinFileExt` "hs"
482 lhs_file = file `joinFileExt` "lhs"
483
484 -- -----------------------------------------------------------------------------
485 -- Extending the program scope
486
487 extendGlobalRdrScope :: Session -> [GlobalRdrElt] -> IO ()
488 extendGlobalRdrScope session rdrElts
489 = modifySession session $ \hscEnv ->
490 let global_rdr = hsc_global_rdr_env hscEnv
491 in hscEnv{ hsc_global_rdr_env = foldl extendGlobalRdrEnv global_rdr rdrElts }
492
493 setGlobalRdrScope :: Session -> [GlobalRdrElt] -> IO ()
494 setGlobalRdrScope session rdrElts
495 = modifySession session $ \hscEnv ->
496 hscEnv{ hsc_global_rdr_env = foldl extendGlobalRdrEnv emptyGlobalRdrEnv rdrElts }
497
498 extendGlobalTypeScope :: Session -> [Id] -> IO ()
499 extendGlobalTypeScope session ids
500 = modifySession session $ \hscEnv ->
501 let global_type = hsc_global_type_env hscEnv
502 in hscEnv{ hsc_global_type_env = extendTypeEnvWithIds global_type ids }
503
504 setGlobalTypeScope :: Session -> [Id] -> IO ()
505 setGlobalTypeScope session ids
506 = modifySession session $ \hscEnv ->
507 hscEnv{ hsc_global_type_env = extendTypeEnvWithIds emptyTypeEnv ids }
508
509 -- -----------------------------------------------------------------------------
510 -- Parsing Haddock comments
511
512 parseHaddockComment :: String -> Either String (HsDoc RdrName)
513 parseHaddockComment string = parseHaddockParagraphs (tokenise string)
514
515 -- -----------------------------------------------------------------------------
516 -- Loading the program
517
518 -- Perform a dependency analysis starting from the current targets
519 -- and update the session with the new module graph.
520 depanal :: Session -> [ModuleName] -> Bool -> IO (Maybe ModuleGraph)
521 depanal (Session ref) excluded_mods allow_dup_roots = do
522 hsc_env <- readIORef ref
523 let
524 dflags = hsc_dflags hsc_env
525 gmode = ghcMode (hsc_dflags hsc_env)
526 targets = hsc_targets hsc_env
527 old_graph = hsc_mod_graph hsc_env
528
529 showPass dflags "Chasing dependencies"
530 when (gmode == BatchCompile) $
531 debugTraceMsg dflags 2 (hcat [
532 text "Chasing modules from: ",
533 hcat (punctuate comma (map pprTarget targets))])
534
535 r <- downsweep hsc_env old_graph excluded_mods allow_dup_roots
536 case r of
537 Just mod_graph -> writeIORef ref hsc_env{ hsc_mod_graph = mod_graph }
538 _ -> return ()
539 return r
540
541 {-
542 -- | The result of load.
543 data LoadResult
544 = LoadOk Errors -- ^ all specified targets were loaded successfully.
545 | LoadFailed Errors -- ^ not all modules were loaded.
546
547 type Errors = [String]
548
549 data ErrMsg = ErrMsg {
550 errMsgSeverity :: Severity, -- warning, error, etc.
551 errMsgSpans :: [SrcSpan],
552 errMsgShortDoc :: Doc,
553 errMsgExtraInfo :: Doc
554 }
555 -}
556
557 data LoadHowMuch
558 = LoadAllTargets
559 | LoadUpTo ModuleName
560 | LoadDependenciesOf ModuleName
561
562 -- | Try to load the program. If a Module is supplied, then just
563 -- attempt to load up to this target. If no Module is supplied,
564 -- then try to load all targets.
565 load :: Session -> LoadHowMuch -> IO SuccessFlag
566 load s@(Session ref) how_much
567 = do
568 -- Dependency analysis first. Note that this fixes the module graph:
569 -- even if we don't get a fully successful upsweep, the full module
570 -- graph is still retained in the Session. We can tell which modules
571 -- were successfully loaded by inspecting the Session's HPT.
572 mb_graph <- depanal s [] False
573 case mb_graph of
574 Just mod_graph -> load2 s how_much mod_graph
575 Nothing -> return Failed
576
577 load2 s@(Session ref) how_much mod_graph = do
578 guessOutputFile s
579 hsc_env <- readIORef ref
580
581 let hpt1 = hsc_HPT hsc_env
582 let dflags = hsc_dflags hsc_env
583 let ghci_mode = ghcMode dflags -- this never changes
584
585 -- The "bad" boot modules are the ones for which we have
586 -- B.hs-boot in the module graph, but no B.hs
587 -- The downsweep should have ensured this does not happen
588 -- (see msDeps)
589 let all_home_mods = [ms_mod_name s
590 | s <- mod_graph, not (isBootSummary s)]
591 #ifdef DEBUG
592 bad_boot_mods = [s | s <- mod_graph, isBootSummary s,
593 not (ms_mod_name s `elem` all_home_mods)]
594 #endif
595 ASSERT( null bad_boot_mods ) return ()
596
597 -- mg2_with_srcimps drops the hi-boot nodes, returning a
598 -- graph with cycles. Among other things, it is used for
599 -- backing out partially complete cycles following a failed
600 -- upsweep, and for removing from hpt all the modules
601 -- not in strict downwards closure, during calls to compile.
602 let mg2_with_srcimps :: [SCC ModSummary]
603 mg2_with_srcimps = topSortModuleGraph True mod_graph Nothing
604
605 -- If we can determine that any of the {-# SOURCE #-} imports
606 -- are definitely unnecessary, then emit a warning.
607 warnUnnecessarySourceImports dflags mg2_with_srcimps
608
609 let
610 -- check the stability property for each module.
611 stable_mods@(stable_obj,stable_bco)
612 | BatchCompile <- ghci_mode = ([],[])
613 | otherwise = checkStability hpt1 mg2_with_srcimps all_home_mods
614
615 -- prune bits of the HPT which are definitely redundant now,
616 -- to save space.
617 pruned_hpt = pruneHomePackageTable hpt1
618 (flattenSCCs mg2_with_srcimps)
619 stable_mods
620
621 evaluate pruned_hpt
622
623 debugTraceMsg dflags 2 (text "Stable obj:" <+> ppr stable_obj $$
624 text "Stable BCO:" <+> ppr stable_bco)
625
626 -- Unload any modules which are going to be re-linked this time around.
627 let stable_linkables = [ linkable
628 | m <- stable_obj++stable_bco,
629 Just hmi <- [lookupUFM pruned_hpt m],
630 Just linkable <- [hm_linkable hmi] ]
631 unload hsc_env stable_linkables
632
633 -- We could at this point detect cycles which aren't broken by
634 -- a source-import, and complain immediately, but it seems better
635 -- to let upsweep_mods do this, so at least some useful work gets
636 -- done before the upsweep is abandoned.
637 --hPutStrLn stderr "after tsort:\n"
638 --hPutStrLn stderr (showSDoc (vcat (map ppr mg2)))
639
640 -- Now do the upsweep, calling compile for each module in
641 -- turn. Final result is version 3 of everything.
642
643 -- Topologically sort the module graph, this time including hi-boot
644 -- nodes, and possibly just including the portion of the graph
645 -- reachable from the module specified in the 2nd argument to load.
646 -- This graph should be cycle-free.
647 -- If we're restricting the upsweep to a portion of the graph, we
648 -- also want to retain everything that is still stable.
649 let full_mg :: [SCC ModSummary]
650 full_mg = topSortModuleGraph False mod_graph Nothing
651
652 maybe_top_mod = case how_much of
653 LoadUpTo m -> Just m
654 LoadDependenciesOf m -> Just m
655 _ -> Nothing
656
657 partial_mg0 :: [SCC ModSummary]
658 partial_mg0 = topSortModuleGraph False mod_graph maybe_top_mod
659
660 -- LoadDependenciesOf m: we want the upsweep to stop just
661 -- short of the specified module (unless the specified module
662 -- is stable).
663 partial_mg
664 | LoadDependenciesOf mod <- how_much
665 = ASSERT( case last partial_mg0 of
666 AcyclicSCC ms -> ms_mod_name ms == mod; _ -> False )
667 List.init partial_mg0
668 | otherwise
669 = partial_mg0
670
671 stable_mg =
672 [ AcyclicSCC ms
673 | AcyclicSCC ms <- full_mg,
674 ms_mod_name ms `elem` stable_obj++stable_bco,
675 ms_mod_name ms `notElem` [ ms_mod_name ms' |
676 AcyclicSCC ms' <- partial_mg ] ]
677
678 mg = stable_mg ++ partial_mg
679
680 -- clean up between compilations
681 let cleanup = cleanTempFilesExcept dflags
682 (ppFilesFromSummaries (flattenSCCs mg2_with_srcimps))
683
684 debugTraceMsg dflags 2 (hang (text "Ready for upsweep")
685 2 (ppr mg))
686 (upsweep_ok, hsc_env1, modsUpswept)
687 <- upsweep (hsc_env { hsc_HPT = emptyHomePackageTable })
688 pruned_hpt stable_mods cleanup mg
689
690 -- Make modsDone be the summaries for each home module now
691 -- available; this should equal the domain of hpt3.
692 -- Get in in a roughly top .. bottom order (hence reverse).
693
694 let modsDone = reverse modsUpswept
695
696 -- Try and do linking in some form, depending on whether the
697 -- upsweep was completely or only partially successful.
698
699 if succeeded upsweep_ok
700
701 then
702 -- Easy; just relink it all.
703 do debugTraceMsg dflags 2 (text "Upsweep completely successful.")
704
705 -- Clean up after ourselves
706 cleanTempFilesExcept dflags (ppFilesFromSummaries modsDone)
707
708 -- Issue a warning for the confusing case where the user
709 -- said '-o foo' but we're not going to do any linking.
710 -- We attempt linking if either (a) one of the modules is
711 -- called Main, or (b) the user said -no-hs-main, indicating
712 -- that main() is going to come from somewhere else.
713 --
714 let ofile = outputFile dflags
715 let no_hs_main = dopt Opt_NoHsMain dflags
716 let
717 main_mod = mainModIs dflags
718 a_root_is_Main = any ((==main_mod).ms_mod) mod_graph
719 do_linking = a_root_is_Main || no_hs_main
720
721 when (ghci_mode == BatchCompile && isJust ofile && not do_linking) $
722 debugTraceMsg dflags 1 (text ("Warning: output was redirected with -o, " ++
723 "but no output will be generated\n" ++
724 "because there is no " ++ moduleNameString (moduleName main_mod) ++ " module."))
725
726 -- link everything together
727 linkresult <- link ghci_mode dflags do_linking (hsc_HPT hsc_env1)
728
729 loadFinish Succeeded linkresult ref hsc_env1
730
731 else
732 -- Tricky. We need to back out the effects of compiling any
733 -- half-done cycles, both so as to clean up the top level envs
734 -- and to avoid telling the interactive linker to link them.
735 do debugTraceMsg dflags 2 (text "Upsweep partially successful.")
736
737 let modsDone_names
738 = map ms_mod modsDone
739 let mods_to_zap_names
740 = findPartiallyCompletedCycles modsDone_names
741 mg2_with_srcimps
742 let mods_to_keep
743 = filter ((`notElem` mods_to_zap_names).ms_mod)
744 modsDone
745
746 let hpt4 = retainInTopLevelEnvs (map ms_mod_name mods_to_keep)
747 (hsc_HPT hsc_env1)
748
749 -- Clean up after ourselves
750 cleanTempFilesExcept dflags (ppFilesFromSummaries mods_to_keep)
751
752 -- there should be no Nothings where linkables should be, now
753 ASSERT(all (isJust.hm_linkable)
754 (eltsUFM (hsc_HPT hsc_env))) do
755
756 -- Link everything together
757 linkresult <- link ghci_mode dflags False hpt4
758
759 let hsc_env4 = hsc_env1{ hsc_HPT = hpt4 }
760 loadFinish Failed linkresult ref hsc_env4
761
762 -- Finish up after a load.
763
764 -- If the link failed, unload everything and return.
765 loadFinish all_ok Failed ref hsc_env
766 = do unload hsc_env []
767 writeIORef ref $! discardProg hsc_env
768 return Failed
769
770 -- Empty the interactive context and set the module context to the topmost
771 -- newly loaded module, or the Prelude if none were loaded.
772 loadFinish all_ok Succeeded ref hsc_env
773 = do writeIORef ref $! hsc_env{ hsc_IC = emptyInteractiveContext }
774 return all_ok
775
776
777 -- Forget the current program, but retain the persistent info in HscEnv
778 discardProg :: HscEnv -> HscEnv
779 discardProg hsc_env
780 = hsc_env { hsc_mod_graph = emptyMG,
781 hsc_IC = emptyInteractiveContext,
782 hsc_HPT = emptyHomePackageTable }
783
784 -- used to fish out the preprocess output files for the purposes of
785 -- cleaning up. The preprocessed file *might* be the same as the
786 -- source file, but that doesn't do any harm.
787 ppFilesFromSummaries summaries = map ms_hspp_file summaries
788
789 -- -----------------------------------------------------------------------------
790 -- Check module
791
792 data CheckedModule =
793 CheckedModule { parsedSource :: ParsedSource,
794 renamedSource :: Maybe RenamedSource,
795 typecheckedSource :: Maybe TypecheckedSource,
796 checkedModuleInfo :: Maybe ModuleInfo
797 }
798 -- ToDo: improvements that could be made here:
799 -- if the module succeeded renaming but not typechecking,
800 -- we can still get back the GlobalRdrEnv and exports, so
801 -- perhaps the ModuleInfo should be split up into separate
802 -- fields within CheckedModule.
803
804 type ParsedSource = Located (HsModule RdrName)
805 type RenamedSource = (HsGroup Name, [LImportDecl Name], Maybe [LIE Name],
806 Maybe (HsDoc Name), HaddockModInfo Name)
807 type TypecheckedSource = LHsBinds Id
808
809 -- NOTE:
810 -- - things that aren't in the output of the typechecker right now:
811 -- - the export list
812 -- - the imports
813 -- - type signatures
814 -- - type/data/newtype declarations
815 -- - class declarations
816 -- - instances
817 -- - extra things in the typechecker's output:
818 -- - default methods are turned into top-level decls.
819 -- - dictionary bindings
820
821
822 -- | This is the way to get access to parsed and typechecked source code
823 -- for a module. 'checkModule' loads all the dependencies of the specified
824 -- module in the Session, and then attempts to typecheck the module. If
825 -- successful, it returns the abstract syntax for the module.
826 checkModule :: Session -> ModuleName -> IO (Maybe CheckedModule)
827 checkModule session@(Session ref) mod = do
828 -- load up the dependencies first
829 r <- load session (LoadDependenciesOf mod)
830 if (failed r) then return Nothing else do
831
832 -- now parse & typecheck the module
833 hsc_env <- readIORef ref
834 let mg = hsc_mod_graph hsc_env
835 case [ ms | ms <- mg, ms_mod_name ms == mod ] of
836 [] -> return Nothing
837 (ms:_) -> do
838 mbChecked <- hscFileCheck hsc_env{hsc_dflags=ms_hspp_opts ms} ms
839 case mbChecked of
840 Nothing -> return Nothing
841 Just (HscChecked parsed renamed Nothing) ->
842 return (Just (CheckedModule {
843 parsedSource = parsed,
844 renamedSource = renamed,
845 typecheckedSource = Nothing,
846 checkedModuleInfo = Nothing }))
847 Just (HscChecked parsed renamed
848 (Just (tc_binds, rdr_env, details))) -> do
849 let minf = ModuleInfo {
850 minf_type_env = md_types details,
851 minf_exports = availsToNameSet $
852 md_exports details,
853 minf_rdr_env = Just rdr_env,
854 minf_instances = md_insts details
855 #ifdef GHCI
856 ,minf_dbg_sites = noDbgSites
857 #endif
858 }
859 return (Just (CheckedModule {
860 parsedSource = parsed,
861 renamedSource = renamed,
862 typecheckedSource = Just tc_binds,
863 checkedModuleInfo = Just minf }))
864
865 -- ---------------------------------------------------------------------------
866 -- Unloading
867
868 unload :: HscEnv -> [Linkable] -> IO ()
869 unload hsc_env stable_linkables -- Unload everthing *except* 'stable_linkables'
870 = case ghcMode (hsc_dflags hsc_env) of
871 BatchCompile -> return ()
872 JustTypecheck -> return ()
873 #ifdef GHCI
874 Interactive -> Linker.unload (hsc_dflags hsc_env) stable_linkables
875 #else
876 Interactive -> panic "unload: no interpreter"
877 #endif
878 other -> panic "unload: strange mode"
879
880 -- -----------------------------------------------------------------------------
881 -- checkStability
882
883 {-
884 Stability tells us which modules definitely do not need to be recompiled.
885 There are two main reasons for having stability:
886
887 - avoid doing a complete upsweep of the module graph in GHCi when
888 modules near the bottom of the tree have not changed.
889
890 - to tell GHCi when it can load object code: we can only load object code
891 for a module when we also load object code fo all of the imports of the
892 module. So we need to know that we will definitely not be recompiling
893 any of these modules, and we can use the object code.
894
895 NB. stability is of no importance to BatchCompile at all, only Interactive.
896 (ToDo: what about JustTypecheck?)
897
898 The stability check is as follows. Both stableObject and
899 stableBCO are used during the upsweep phase later.
900
901 -------------------
902 stable m = stableObject m || stableBCO m
903
904 stableObject m =
905 all stableObject (imports m)
906 && old linkable does not exist, or is == on-disk .o
907 && date(on-disk .o) > date(.hs)
908
909 stableBCO m =
910 all stable (imports m)
911 && date(BCO) > date(.hs)
912 -------------------
913
914 These properties embody the following ideas:
915
916 - if a module is stable:
917 - if it has been compiled in a previous pass (present in HPT)
918 then it does not need to be compiled or re-linked.
919 - if it has not been compiled in a previous pass,
920 then we only need to read its .hi file from disk and
921 link it to produce a ModDetails.
922
923 - if a modules is not stable, we will definitely be at least
924 re-linking, and possibly re-compiling it during the upsweep.
925 All non-stable modules can (and should) therefore be unlinked
926 before the upsweep.
927
928 - Note that objects are only considered stable if they only depend
929 on other objects. We can't link object code against byte code.
930 -}
931
932 checkStability
933 :: HomePackageTable -- HPT from last compilation
934 -> [SCC ModSummary] -- current module graph (cyclic)
935 -> [ModuleName] -- all home modules
936 -> ([ModuleName], -- stableObject
937 [ModuleName]) -- stableBCO
938
939 checkStability hpt sccs all_home_mods = foldl checkSCC ([],[]) sccs
940 where
941 checkSCC (stable_obj, stable_bco) scc0
942 | stableObjects = (scc_mods ++ stable_obj, stable_bco)
943 | stableBCOs = (stable_obj, scc_mods ++ stable_bco)
944 | otherwise = (stable_obj, stable_bco)
945 where
946 scc = flattenSCC scc0
947 scc_mods = map ms_mod_name scc
948 home_module m = m `elem` all_home_mods && m `notElem` scc_mods
949
950 scc_allimps = nub (filter home_module (concatMap ms_allimps scc))
951 -- all imports outside the current SCC, but in the home pkg
952
953 stable_obj_imps = map (`elem` stable_obj) scc_allimps
954 stable_bco_imps = map (`elem` stable_bco) scc_allimps
955
956 stableObjects =
957 and stable_obj_imps
958 && all object_ok scc
959
960 stableBCOs =
961 and (zipWith (||) stable_obj_imps stable_bco_imps)
962 && all bco_ok scc
963
964 object_ok ms
965 | Just t <- ms_obj_date ms = t >= ms_hs_date ms
966 && same_as_prev t
967 | otherwise = False
968 where
969 same_as_prev t = case lookupUFM hpt (ms_mod_name ms) of
970 Just hmi | Just l <- hm_linkable hmi
971 -> isObjectLinkable l && t == linkableTime l
972 _other -> True
973 -- why '>=' rather than '>' above? If the filesystem stores
974 -- times to the nearset second, we may occasionally find that
975 -- the object & source have the same modification time,
976 -- especially if the source was automatically generated
977 -- and compiled. Using >= is slightly unsafe, but it matches
978 -- make's behaviour.
979
980 bco_ok ms
981 = case lookupUFM hpt (ms_mod_name ms) of
982 Just hmi | Just l <- hm_linkable hmi ->
983 not (isObjectLinkable l) &&
984 linkableTime l >= ms_hs_date ms
985 _other -> False
986
987 ms_allimps :: ModSummary -> [ModuleName]
988 ms_allimps ms = map unLoc (ms_srcimps ms ++ ms_imps ms)
989
990 -- -----------------------------------------------------------------------------
991 -- Prune the HomePackageTable
992
993 -- Before doing an upsweep, we can throw away:
994 --
995 -- - For non-stable modules:
996 -- - all ModDetails, all linked code
997 -- - all unlinked code that is out of date with respect to
998 -- the source file
999 --
1000 -- This is VERY IMPORTANT otherwise we'll end up requiring 2x the
1001 -- space at the end of the upsweep, because the topmost ModDetails of the
1002 -- old HPT holds on to the entire type environment from the previous
1003 -- compilation.
1004
1005 pruneHomePackageTable
1006 :: HomePackageTable
1007 -> [ModSummary]
1008 -> ([ModuleName],[ModuleName])
1009 -> HomePackageTable
1010
1011 pruneHomePackageTable hpt summ (stable_obj, stable_bco)
1012 = mapUFM prune hpt
1013 where prune hmi
1014 | is_stable modl = hmi'
1015 | otherwise = hmi'{ hm_details = emptyModDetails }
1016 where
1017 modl = moduleName (mi_module (hm_iface hmi))
1018 hmi' | Just l <- hm_linkable hmi, linkableTime l < ms_hs_date ms
1019 = hmi{ hm_linkable = Nothing }
1020 | otherwise
1021 = hmi
1022 where ms = expectJust "prune" (lookupUFM ms_map modl)
1023
1024 ms_map = listToUFM [(ms_mod_name ms, ms) | ms <- summ]
1025
1026 is_stable m = m `elem` stable_obj || m `elem` stable_bco
1027
1028 -- -----------------------------------------------------------------------------
1029
1030 -- Return (names of) all those in modsDone who are part of a cycle
1031 -- as defined by theGraph.
1032 findPartiallyCompletedCycles :: [Module] -> [SCC ModSummary] -> [Module]
1033 findPartiallyCompletedCycles modsDone theGraph
1034 = chew theGraph
1035 where
1036 chew [] = []
1037 chew ((AcyclicSCC v):rest) = chew rest -- acyclic? not interesting.
1038 chew ((CyclicSCC vs):rest)
1039 = let names_in_this_cycle = nub (map ms_mod vs)
1040 mods_in_this_cycle
1041 = nub ([done | done <- modsDone,
1042 done `elem` names_in_this_cycle])
1043 chewed_rest = chew rest
1044 in
1045 if notNull mods_in_this_cycle
1046 && length mods_in_this_cycle < length names_in_this_cycle
1047 then mods_in_this_cycle ++ chewed_rest
1048 else chewed_rest
1049
1050 -- -----------------------------------------------------------------------------
1051 -- The upsweep
1052
1053 -- This is where we compile each module in the module graph, in a pass
1054 -- from the bottom to the top of the graph.
1055
1056 -- There better had not be any cyclic groups here -- we check for them.
1057
1058 upsweep
1059 :: HscEnv -- Includes initially-empty HPT
1060 -> HomePackageTable -- HPT from last time round (pruned)
1061 -> ([ModuleName],[ModuleName]) -- stable modules (see checkStability)
1062 -> IO () -- How to clean up unwanted tmp files
1063 -> [SCC ModSummary] -- Mods to do (the worklist)
1064 -> IO (SuccessFlag,
1065 HscEnv, -- With an updated HPT
1066 [ModSummary]) -- Mods which succeeded
1067
1068 upsweep hsc_env old_hpt stable_mods cleanup mods
1069 = upsweep' hsc_env old_hpt stable_mods cleanup mods 1 (length mods)
1070
1071 upsweep' hsc_env old_hpt stable_mods cleanup
1072 [] _ _
1073 = return (Succeeded, hsc_env, [])
1074
1075 upsweep' hsc_env old_hpt stable_mods cleanup
1076 (CyclicSCC ms:_) _ _
1077 = do fatalErrorMsg (hsc_dflags hsc_env) (cyclicModuleErr ms)
1078 return (Failed, hsc_env, [])
1079
1080 upsweep' hsc_env old_hpt stable_mods cleanup
1081 (AcyclicSCC mod:mods) mod_index nmods
1082 = do -- putStrLn ("UPSWEEP_MOD: hpt = " ++
1083 -- show (map (moduleUserString.moduleName.mi_module.hm_iface)
1084 -- (moduleEnvElts (hsc_HPT hsc_env)))
1085
1086 mb_mod_info <- upsweep_mod hsc_env old_hpt stable_mods mod
1087 mod_index nmods
1088
1089 cleanup -- Remove unwanted tmp files between compilations
1090
1091 case mb_mod_info of
1092 Nothing -> return (Failed, hsc_env, [])
1093 Just mod_info -> do
1094 { let this_mod = ms_mod_name mod
1095
1096 -- Add new info to hsc_env
1097 hpt1 = addToUFM (hsc_HPT hsc_env) this_mod mod_info
1098 hsc_env1 = hsc_env { hsc_HPT = hpt1 }
1099
1100 -- Space-saving: delete the old HPT entry
1101 -- for mod BUT if mod is a hs-boot
1102 -- node, don't delete it. For the
1103 -- interface, the HPT entry is probaby for the
1104 -- main Haskell source file. Deleting it
1105 -- would force .. (what?? --SDM)
1106 old_hpt1 | isBootSummary mod = old_hpt
1107 | otherwise = delFromUFM old_hpt this_mod
1108
1109 ; (restOK, hsc_env2, modOKs)
1110 <- upsweep' hsc_env1 old_hpt1 stable_mods cleanup
1111 mods (mod_index+1) nmods
1112 ; return (restOK, hsc_env2, mod:modOKs)
1113 }
1114
1115
1116 -- Compile a single module. Always produce a Linkable for it if
1117 -- successful. If no compilation happened, return the old Linkable.
1118 upsweep_mod :: HscEnv
1119 -> HomePackageTable
1120 -> ([ModuleName],[ModuleName])
1121 -> ModSummary
1122 -> Int -- index of module
1123 -> Int -- total number of modules
1124 -> IO (Maybe HomeModInfo) -- Nothing => Failed
1125
1126 upsweep_mod hsc_env old_hpt (stable_obj, stable_bco) summary mod_index nmods
1127 = do
1128 let
1129 this_mod_name = ms_mod_name summary
1130 this_mod = ms_mod summary
1131 mb_obj_date = ms_obj_date summary
1132 obj_fn = ml_obj_file (ms_location summary)
1133 hs_date = ms_hs_date summary
1134
1135 compile_it :: Maybe Linkable -> IO (Maybe HomeModInfo)
1136 compile_it = upsweep_compile hsc_env old_hpt this_mod_name
1137 summary mod_index nmods
1138
1139 case ghcMode (hsc_dflags hsc_env) of
1140 BatchCompile ->
1141 case () of
1142 -- Batch-compilating is easy: just check whether we have
1143 -- an up-to-date object file. If we do, then the compiler
1144 -- needs to do a recompilation check.
1145 _ | Just obj_date <- mb_obj_date, obj_date >= hs_date -> do
1146 linkable <-
1147 findObjectLinkable this_mod obj_fn obj_date
1148 compile_it (Just linkable)
1149
1150 | otherwise ->
1151 compile_it Nothing
1152
1153 interactive ->
1154 case () of
1155 _ | is_stable_obj, isJust old_hmi ->
1156 return old_hmi
1157 -- object is stable, and we have an entry in the
1158 -- old HPT: nothing to do
1159
1160 | is_stable_obj, isNothing old_hmi -> do
1161 linkable <-
1162 findObjectLinkable this_mod obj_fn
1163 (expectJust "upseep1" mb_obj_date)
1164 compile_it (Just linkable)
1165 -- object is stable, but we need to load the interface
1166 -- off disk to make a HMI.
1167
1168 | is_stable_bco ->
1169 ASSERT(isJust old_hmi) -- must be in the old_hpt
1170 return old_hmi
1171 -- BCO is stable: nothing to do
1172
1173 | Just hmi <- old_hmi,
1174 Just l <- hm_linkable hmi, not (isObjectLinkable l),
1175 linkableTime l >= ms_hs_date summary ->
1176 compile_it (Just l)
1177 -- we have an old BCO that is up to date with respect
1178 -- to the source: do a recompilation check as normal.
1179
1180 | otherwise ->
1181 compile_it Nothing
1182 -- no existing code at all: we must recompile.
1183 where
1184 is_stable_obj = this_mod_name `elem` stable_obj
1185 is_stable_bco = this_mod_name `elem` stable_bco
1186
1187 old_hmi = lookupUFM old_hpt this_mod_name
1188
1189 -- Run hsc to compile a module
1190 upsweep_compile hsc_env old_hpt this_mod summary
1191 mod_index nmods
1192 mb_old_linkable = do
1193 let
1194 -- The old interface is ok if it's in the old HPT
1195 -- a) we're compiling a source file, and the old HPT
1196 -- entry is for a source file
1197 -- b) we're compiling a hs-boot file
1198 -- Case (b) allows an hs-boot file to get the interface of its
1199 -- real source file on the second iteration of the compilation
1200 -- manager, but that does no harm. Otherwise the hs-boot file
1201 -- will always be recompiled
1202
1203 mb_old_iface
1204 = case lookupUFM old_hpt this_mod of
1205 Nothing -> Nothing
1206 Just hm_info | isBootSummary summary -> Just iface
1207 | not (mi_boot iface) -> Just iface
1208 | otherwise -> Nothing
1209 where
1210 iface = hm_iface hm_info
1211
1212 compresult <- compile hsc_env summary mb_old_linkable mb_old_iface
1213 mod_index nmods
1214
1215 case compresult of
1216 -- Compilation failed. Compile may still have updated the PCS, tho.
1217 CompErrs -> return Nothing
1218
1219 -- Compilation "succeeded", and may or may not have returned a new
1220 -- linkable (depending on whether compilation was actually performed
1221 -- or not).
1222 CompOK new_details new_iface new_linkable
1223 -> do let new_info = HomeModInfo { hm_iface = new_iface,
1224 hm_details = new_details,
1225 hm_linkable = new_linkable }
1226 return (Just new_info)
1227
1228
1229 -- Filter modules in the HPT
1230 retainInTopLevelEnvs :: [ModuleName] -> HomePackageTable -> HomePackageTable
1231 retainInTopLevelEnvs keep_these hpt
1232 = listToUFM [ (mod, expectJust "retain" mb_mod_info)
1233 | mod <- keep_these
1234 , let mb_mod_info = lookupUFM hpt mod
1235 , isJust mb_mod_info ]
1236
1237 -- ---------------------------------------------------------------------------
1238 -- Topological sort of the module graph
1239
1240 topSortModuleGraph
1241 :: Bool -- Drop hi-boot nodes? (see below)
1242 -> [ModSummary]
1243 -> Maybe ModuleName
1244 -> [SCC ModSummary]
1245 -- Calculate SCCs of the module graph, possibly dropping the hi-boot nodes
1246 -- The resulting list of strongly-connected-components is in topologically
1247 -- sorted order, starting with the module(s) at the bottom of the
1248 -- dependency graph (ie compile them first) and ending with the ones at
1249 -- the top.
1250 --
1251 -- Drop hi-boot nodes (first boolean arg)?
1252 --
1253 -- False: treat the hi-boot summaries as nodes of the graph,
1254 -- so the graph must be acyclic
1255 --
1256 -- True: eliminate the hi-boot nodes, and instead pretend
1257 -- the a source-import of Foo is an import of Foo
1258 -- The resulting graph has no hi-boot nodes, but can by cyclic
1259
1260 topSortModuleGraph drop_hs_boot_nodes summaries Nothing
1261 = stronglyConnComp (fst (moduleGraphNodes drop_hs_boot_nodes summaries))
1262 topSortModuleGraph drop_hs_boot_nodes summaries (Just mod)
1263 = stronglyConnComp (map vertex_fn (reachable graph root))
1264 where
1265 -- restrict the graph to just those modules reachable from
1266 -- the specified module. We do this by building a graph with
1267 -- the full set of nodes, and determining the reachable set from
1268 -- the specified node.
1269 (nodes, lookup_key) = moduleGraphNodes drop_hs_boot_nodes summaries
1270 (graph, vertex_fn, key_fn) = graphFromEdges' nodes
1271 root
1272 | Just key <- lookup_key HsSrcFile mod, Just v <- key_fn key = v
1273 | otherwise = throwDyn (ProgramError "module does not exist")
1274
1275 moduleGraphNodes :: Bool -> [ModSummary]
1276 -> ([(ModSummary, Int, [Int])], HscSource -> ModuleName -> Maybe Int)
1277 moduleGraphNodes drop_hs_boot_nodes summaries = (nodes, lookup_key)
1278 where
1279 -- Drop hs-boot nodes by using HsSrcFile as the key
1280 hs_boot_key | drop_hs_boot_nodes = HsSrcFile
1281 | otherwise = HsBootFile
1282
1283 -- We use integers as the keys for the SCC algorithm
1284 nodes :: [(ModSummary, Int, [Int])]
1285 nodes = [(s, expectJust "topSort" $
1286 lookup_key (ms_hsc_src s) (ms_mod_name s),
1287 out_edge_keys hs_boot_key (map unLoc (ms_srcimps s)) ++
1288 out_edge_keys HsSrcFile (map unLoc (ms_imps s)) ++
1289 (-- see [boot-edges] below
1290 if drop_hs_boot_nodes || ms_hsc_src s == HsBootFile
1291 then []
1292 else case lookup_key HsBootFile (ms_mod_name s) of
1293 Nothing -> []
1294 Just k -> [k])
1295 )
1296 | s <- summaries
1297 , not (isBootSummary s && drop_hs_boot_nodes) ]
1298 -- Drop the hi-boot ones if told to do so
1299
1300 -- [boot-edges] if this is a .hs and there is an equivalent
1301 -- .hs-boot, add a link from the former to the latter. This
1302 -- has the effect of detecting bogus cases where the .hs-boot
1303 -- depends on the .hs, by introducing a cycle. Additionally,
1304 -- it ensures that we will always process the .hs-boot before
1305 -- the .hs, and so the HomePackageTable will always have the
1306 -- most up to date information.
1307
1308 key_map :: NodeMap Int
1309 key_map = listToFM ([(moduleName (ms_mod s), ms_hsc_src s)
1310 | s <- summaries]
1311 `zip` [1..])
1312
1313 lookup_key :: HscSource -> ModuleName -> Maybe Int
1314 lookup_key hs_src mod = lookupFM key_map (mod, hs_src)
1315
1316 out_edge_keys :: HscSource -> [ModuleName] -> [Int]
1317 out_edge_keys hi_boot ms = mapCatMaybes (lookup_key hi_boot) ms
1318 -- If we want keep_hi_boot_nodes, then we do lookup_key with
1319 -- the IsBootInterface parameter True; else False
1320
1321
1322 type NodeKey = (ModuleName, HscSource) -- The nodes of the graph are
1323 type NodeMap a = FiniteMap NodeKey a -- keyed by (mod, src_file_type) pairs
1324
1325 msKey :: ModSummary -> NodeKey
1326 msKey (ModSummary { ms_mod = mod, ms_hsc_src = boot }) = (moduleName mod,boot)
1327
1328 mkNodeMap :: [ModSummary] -> NodeMap ModSummary
1329 mkNodeMap summaries = listToFM [ (msKey s, s) | s <- summaries]
1330
1331 nodeMapElts :: NodeMap a -> [a]
1332 nodeMapElts = eltsFM
1333
1334 ms_mod_name :: ModSummary -> ModuleName
1335 ms_mod_name = moduleName . ms_mod
1336
1337 -- If there are {-# SOURCE #-} imports between strongly connected
1338 -- components in the topological sort, then those imports can
1339 -- definitely be replaced by ordinary non-SOURCE imports: if SOURCE
1340 -- were necessary, then the edge would be part of a cycle.
1341 warnUnnecessarySourceImports :: DynFlags -> [SCC ModSummary] -> IO ()
1342 warnUnnecessarySourceImports dflags sccs =
1343 printBagOfWarnings dflags (listToBag (concat (map (check.flattenSCC) sccs)))
1344 where check ms =
1345 let mods_in_this_cycle = map ms_mod_name ms in
1346 [ warn m i | m <- ms, i <- ms_srcimps m,
1347 unLoc i `notElem` mods_in_this_cycle ]
1348
1349 warn :: ModSummary -> Located ModuleName -> WarnMsg
1350 warn ms (L loc mod) =
1351 mkPlainErrMsg loc
1352 (ptext SLIT("Warning: {-# SOURCE #-} unnecessary in import of ")
1353 <+> quotes (ppr mod))
1354
1355 -----------------------------------------------------------------------------
1356 -- Downsweep (dependency analysis)
1357
1358 -- Chase downwards from the specified root set, returning summaries
1359 -- for all home modules encountered. Only follow source-import
1360 -- links.
1361
1362 -- We pass in the previous collection of summaries, which is used as a
1363 -- cache to avoid recalculating a module summary if the source is
1364 -- unchanged.
1365 --
1366 -- The returned list of [ModSummary] nodes has one node for each home-package
1367 -- module, plus one for any hs-boot files. The imports of these nodes
1368 -- are all there, including the imports of non-home-package modules.
1369
1370 downsweep :: HscEnv
1371 -> [ModSummary] -- Old summaries
1372 -> [ModuleName] -- Ignore dependencies on these; treat
1373 -- them as if they were package modules
1374 -> Bool -- True <=> allow multiple targets to have
1375 -- the same module name; this is
1376 -- very useful for ghc -M
1377 -> IO (Maybe [ModSummary])
1378 -- The elts of [ModSummary] all have distinct
1379 -- (Modules, IsBoot) identifiers, unless the Bool is true
1380 -- in which case there can be repeats
1381 downsweep hsc_env old_summaries excl_mods allow_dup_roots
1382 = -- catch error messages and return them
1383 handleDyn (\err_msg -> printBagOfErrors (hsc_dflags hsc_env) (unitBag err_msg) >> return Nothing) $ do
1384 rootSummaries <- mapM getRootSummary roots
1385 let root_map = mkRootMap rootSummaries
1386 checkDuplicates root_map
1387 summs <- loop (concatMap msDeps rootSummaries) root_map
1388 return (Just summs)
1389 where
1390 roots = hsc_targets hsc_env
1391
1392 old_summary_map :: NodeMap ModSummary
1393 old_summary_map = mkNodeMap old_summaries
1394
1395 getRootSummary :: Target -> IO ModSummary
1396 getRootSummary (Target (TargetFile file mb_phase) maybe_buf)
1397 = do exists <- doesFileExist file
1398 if exists
1399 then summariseFile hsc_env old_summaries file mb_phase maybe_buf
1400 else throwDyn $ mkPlainErrMsg noSrcSpan $
1401 text "can't find file:" <+> text file
1402 getRootSummary (Target (TargetModule modl) maybe_buf)
1403 = do maybe_summary <- summariseModule hsc_env old_summary_map False
1404 (L rootLoc modl) maybe_buf excl_mods
1405 case maybe_summary of
1406 Nothing -> packageModErr modl
1407 Just s -> return s
1408
1409 rootLoc = mkGeneralSrcSpan FSLIT("<command line>")
1410
1411 -- In a root module, the filename is allowed to diverge from the module
1412 -- name, so we have to check that there aren't multiple root files
1413 -- defining the same module (otherwise the duplicates will be silently
1414 -- ignored, leading to confusing behaviour).
1415 checkDuplicates :: NodeMap [ModSummary] -> IO ()
1416 checkDuplicates root_map
1417 | allow_dup_roots = return ()
1418 | null dup_roots = return ()
1419 | otherwise = multiRootsErr (head dup_roots)
1420 where
1421 dup_roots :: [[ModSummary]] -- Each at least of length 2
1422 dup_roots = filterOut isSingleton (nodeMapElts root_map)
1423
1424 loop :: [(Located ModuleName,IsBootInterface)]
1425 -- Work list: process these modules
1426 -> NodeMap [ModSummary]
1427 -- Visited set; the range is a list because
1428 -- the roots can have the same module names
1429 -- if allow_dup_roots is True
1430 -> IO [ModSummary]
1431 -- The result includes the worklist, except
1432 -- for those mentioned in the visited set
1433 loop [] done = return (concat (nodeMapElts done))
1434 loop ((wanted_mod, is_boot) : ss) done
1435 | Just summs <- lookupFM done key
1436 = if isSingleton summs then
1437 loop ss done
1438 else
1439 do { multiRootsErr summs; return [] }
1440 | otherwise = do { mb_s <- summariseModule hsc_env old_summary_map
1441 is_boot wanted_mod Nothing excl_mods
1442 ; case mb_s of
1443 Nothing -> loop ss done
1444 Just s -> loop (msDeps s ++ ss)
1445 (addToFM done key [s]) }
1446 where
1447 key = (unLoc wanted_mod, if is_boot then HsBootFile else HsSrcFile)
1448
1449 mkRootMap :: [ModSummary] -> NodeMap [ModSummary]
1450 mkRootMap summaries = addListToFM_C (++) emptyFM
1451 [ (msKey s, [s]) | s <- summaries ]
1452
1453 msDeps :: ModSummary -> [(Located ModuleName, IsBootInterface)]
1454 -- (msDeps s) returns the dependencies of the ModSummary s.
1455 -- A wrinkle is that for a {-# SOURCE #-} import we return
1456 -- *both* the hs-boot file
1457 -- *and* the source file
1458 -- as "dependencies". That ensures that the list of all relevant
1459 -- modules always contains B.hs if it contains B.hs-boot.
1460 -- Remember, this pass isn't doing the topological sort. It's
1461 -- just gathering the list of all relevant ModSummaries
1462 msDeps s =
1463 concat [ [(m,True), (m,False)] | m <- ms_srcimps s ]
1464 ++ [ (m,False) | m <- ms_imps s ]
1465
1466 -----------------------------------------------------------------------------
1467 -- Summarising modules
1468
1469 -- We have two types of summarisation:
1470 --
1471 -- * Summarise a file. This is used for the root module(s) passed to
1472 -- cmLoadModules. The file is read, and used to determine the root
1473 -- module name. The module name may differ from the filename.
1474 --
1475 -- * Summarise a module. We are given a module name, and must provide
1476 -- a summary. The finder is used to locate the file in which the module
1477 -- resides.
1478
1479 summariseFile
1480 :: HscEnv
1481 -> [ModSummary] -- old summaries
1482 -> FilePath -- source file name
1483 -> Maybe Phase -- start phase
1484 -> Maybe (StringBuffer,ClockTime)
1485 -> IO ModSummary
1486
1487 summariseFile hsc_env old_summaries file mb_phase maybe_buf
1488 -- we can use a cached summary if one is available and the
1489 -- source file hasn't changed, But we have to look up the summary
1490 -- by source file, rather than module name as we do in summarise.
1491 | Just old_summary <- findSummaryBySourceFile old_summaries file
1492 = do
1493 let location = ms_location old_summary
1494
1495 -- return the cached summary if the source didn't change
1496 src_timestamp <- case maybe_buf of
1497 Just (_,t) -> return t
1498 Nothing -> getModificationTime file
1499 -- The file exists; we checked in getRootSummary above.
1500 -- If it gets removed subsequently, then this
1501 -- getModificationTime may fail, but that's the right
1502 -- behaviour.
1503
1504 if ms_hs_date old_summary == src_timestamp
1505 then do -- update the object-file timestamp
1506 obj_timestamp <- getObjTimestamp location False
1507 return old_summary{ ms_obj_date = obj_timestamp }
1508 else
1509 new_summary
1510
1511 | otherwise
1512 = new_summary
1513 where
1514 new_summary = do
1515 let dflags = hsc_dflags hsc_env
1516
1517 (dflags', hspp_fn, buf)
1518 <- preprocessFile dflags file mb_phase maybe_buf
1519
1520 (srcimps,the_imps, L _ mod_name) <- getImports dflags' buf hspp_fn
1521
1522 -- Make a ModLocation for this file
1523 location <- mkHomeModLocation dflags mod_name file
1524
1525 -- Tell the Finder cache where it is, so that subsequent calls
1526 -- to findModule will find it, even if it's not on any search path
1527 mod <- addHomeModuleToFinder hsc_env mod_name location
1528
1529 src_timestamp <- case maybe_buf of
1530 Just (_,t) -> return t
1531 Nothing -> getModificationTime file
1532 -- getMofificationTime may fail
1533
1534 obj_timestamp <- modificationTimeIfExists (ml_obj_file location)
1535
1536 return (ModSummary { ms_mod = mod, ms_hsc_src = HsSrcFile,
1537 ms_location = location,
1538 ms_hspp_file = hspp_fn,
1539 ms_hspp_opts = dflags',
1540 ms_hspp_buf = Just buf,
1541 ms_srcimps = srcimps, ms_imps = the_imps,
1542 ms_hs_date = src_timestamp,
1543 ms_obj_date = obj_timestamp })
1544
1545 findSummaryBySourceFile :: [ModSummary] -> FilePath -> Maybe ModSummary
1546 findSummaryBySourceFile summaries file
1547 = case [ ms | ms <- summaries, HsSrcFile <- [ms_hsc_src ms],
1548 expectJust "findSummaryBySourceFile" (ml_hs_file (ms_location ms)) == file ] of
1549 [] -> Nothing
1550 (x:xs) -> Just x
1551
1552 -- Summarise a module, and pick up source and timestamp.
1553 summariseModule
1554 :: HscEnv
1555 -> NodeMap ModSummary -- Map of old summaries
1556 -> IsBootInterface -- True <=> a {-# SOURCE #-} import
1557 -> Located ModuleName -- Imported module to be summarised
1558 -> Maybe (StringBuffer, ClockTime)
1559 -> [ModuleName] -- Modules to exclude
1560 -> IO (Maybe ModSummary) -- Its new summary
1561
1562 summariseModule hsc_env old_summary_map is_boot (L loc wanted_mod) maybe_buf excl_mods
1563 | wanted_mod `elem` excl_mods
1564 = return Nothing
1565
1566 | Just old_summary <- lookupFM old_summary_map (wanted_mod, hsc_src)
1567 = do -- Find its new timestamp; all the
1568 -- ModSummaries in the old map have valid ml_hs_files
1569 let location = ms_location old_summary
1570 src_fn = expectJust "summariseModule" (ml_hs_file location)
1571
1572 -- check the modification time on the source file, and
1573 -- return the cached summary if it hasn't changed. If the
1574 -- file has disappeared, we need to call the Finder again.
1575 case maybe_buf of
1576 Just (_,t) -> check_timestamp old_summary location src_fn t
1577 Nothing -> do
1578 m <- System.IO.Error.try (getModificationTime src_fn)
1579 case m of
1580 Right t -> check_timestamp old_summary location src_fn t
1581 Left e | isDoesNotExistError e -> find_it
1582 | otherwise -> ioError e
1583
1584 | otherwise = find_it
1585 where
1586 dflags = hsc_dflags hsc_env
1587
1588 hsc_src = if is_boot then HsBootFile else HsSrcFile
1589
1590 check_timestamp old_summary location src_fn src_timestamp
1591 | ms_hs_date old_summary == src_timestamp = do
1592 -- update the object-file timestamp
1593 obj_timestamp <- getObjTimestamp location is_boot
1594 return (Just old_summary{ ms_obj_date = obj_timestamp })
1595 | otherwise =
1596 -- source changed: re-summarise.
1597 new_summary location (ms_mod old_summary) src_fn src_timestamp
1598
1599 find_it = do
1600 -- Don't use the Finder's cache this time. If the module was
1601 -- previously a package module, it may have now appeared on the
1602 -- search path, so we want to consider it to be a home module. If
1603 -- the module was previously a home module, it may have moved.
1604 uncacheModule hsc_env wanted_mod
1605 found <- findImportedModule hsc_env wanted_mod Nothing
1606 case found of
1607 Found location mod
1608 | isJust (ml_hs_file location) ->
1609 -- Home package
1610 just_found location mod
1611 | otherwise ->
1612 -- Drop external-pkg
1613 ASSERT(modulePackageId mod /= thisPackage dflags)
1614 return Nothing
1615 where
1616
1617 err -> noModError dflags loc wanted_mod err
1618 -- Not found
1619
1620 just_found location mod = do
1621 -- Adjust location to point to the hs-boot source file,
1622 -- hi file, object file, when is_boot says so
1623 let location' | is_boot = addBootSuffixLocn location
1624 | otherwise = location
1625 src_fn = expectJust "summarise2" (ml_hs_file location')
1626
1627 -- Check that it exists
1628 -- It might have been deleted since the Finder last found it
1629 maybe_t <- modificationTimeIfExists src_fn
1630 case maybe_t of
1631 Nothing -> noHsFileErr loc src_fn
1632 Just t -> new_summary location' mod src_fn t
1633
1634
1635 new_summary location mod src_fn src_timestamp
1636 = do
1637 -- Preprocess the source file and get its imports
1638 -- The dflags' contains the OPTIONS pragmas
1639 (dflags', hspp_fn, buf) <- preprocessFile dflags src_fn Nothing maybe_buf
1640 (srcimps, the_imps, L mod_loc mod_name) <- getImports dflags' buf hspp_fn
1641
1642 when (mod_name /= wanted_mod) $
1643 throwDyn $ mkPlainErrMsg mod_loc $
1644 text "file name does not match module name"
1645 <+> quotes (ppr mod_name)
1646
1647 -- Find the object timestamp, and return the summary
1648 obj_timestamp <- getObjTimestamp location is_boot
1649
1650 return (Just ( ModSummary { ms_mod = mod,
1651 ms_hsc_src = hsc_src,
1652 ms_location = location,
1653 ms_hspp_file = hspp_fn,
1654 ms_hspp_opts = dflags',
1655 ms_hspp_buf = Just buf,
1656 ms_srcimps = srcimps,
1657 ms_imps = the_imps,
1658 ms_hs_date = src_timestamp,
1659 ms_obj_date = obj_timestamp }))
1660
1661
1662 getObjTimestamp location is_boot
1663 = if is_boot then return Nothing
1664 else modificationTimeIfExists (ml_obj_file location)
1665
1666
1667 preprocessFile :: DynFlags -> FilePath -> Maybe Phase -> Maybe (StringBuffer,ClockTime)
1668 -> IO (DynFlags, FilePath, StringBuffer)
1669 preprocessFile dflags src_fn mb_phase Nothing
1670 = do
1671 (dflags', hspp_fn) <- preprocess dflags (src_fn, mb_phase)
1672 buf <- hGetStringBuffer hspp_fn
1673 return (dflags', hspp_fn, buf)
1674
1675 preprocessFile dflags src_fn mb_phase (Just (buf, time))
1676 = do
1677 -- case we bypass the preprocessing stage?
1678 let
1679 local_opts = getOptions buf src_fn
1680 --
1681 (dflags', errs) <- parseDynamicFlags dflags (map unLoc local_opts)
1682
1683 let
1684 needs_preprocessing
1685 | Just (Unlit _) <- mb_phase = True
1686 | Nothing <- mb_phase, Unlit _ <- startPhase src_fn = True
1687 -- note: local_opts is only required if there's no Unlit phase
1688 | dopt Opt_Cpp dflags' = True
1689 | dopt Opt_Pp dflags' = True
1690 | otherwise = False
1691
1692 when needs_preprocessing $
1693 ghcError (ProgramError "buffer needs preprocesing; interactive check disabled")
1694
1695 return (dflags', src_fn, buf)
1696
1697
1698 -----------------------------------------------------------------------------
1699 -- Error messages
1700 -----------------------------------------------------------------------------
1701
1702 noModError :: DynFlags -> SrcSpan -> ModuleName -> FindResult -> IO ab
1703 -- ToDo: we don't have a proper line number for this error
1704 noModError dflags loc wanted_mod err
1705 = throwDyn $ mkPlainErrMsg loc $ cannotFindModule dflags wanted_mod err
1706
1707 noHsFileErr loc path
1708 = throwDyn $ mkPlainErrMsg loc $ text "Can't find" <+> text path
1709
1710 packageModErr mod
1711 = throwDyn $ mkPlainErrMsg noSrcSpan $
1712 text "module" <+> quotes (ppr mod) <+> text "is a package module"
1713
1714 multiRootsErr :: [ModSummary] -> IO ()
1715 multiRootsErr summs@(summ1:_)
1716 = throwDyn $ mkPlainErrMsg noSrcSpan $
1717 text "module" <+> quotes (ppr mod) <+>
1718 text "is defined in multiple files:" <+>
1719 sep (map text files)
1720 where
1721 mod = ms_mod summ1
1722 files = map (expectJust "checkDup" . ml_hs_file . ms_location) summs
1723
1724 cyclicModuleErr :: [ModSummary] -> SDoc
1725 cyclicModuleErr ms
1726 = hang (ptext SLIT("Module imports form a cycle for modules:"))
1727 2 (vcat (map show_one ms))
1728 where
1729 show_one ms = sep [ show_mod (ms_hsc_src ms) (ms_mod ms),
1730 nest 2 $ ptext SLIT("imports:") <+>
1731 (pp_imps HsBootFile (ms_srcimps ms)
1732 $$ pp_imps HsSrcFile (ms_imps ms))]
1733 show_mod hsc_src mod = ppr mod <> text (hscSourceString hsc_src)
1734 pp_imps src mods = fsep (map (show_mod src) mods)
1735
1736
1737 -- | Inform GHC that the working directory has changed. GHC will flush
1738 -- its cache of module locations, since it may no longer be valid.
1739 -- Note: if you change the working directory, you should also unload
1740 -- the current program (set targets to empty, followed by load).
1741 workingDirectoryChanged :: Session -> IO ()
1742 workingDirectoryChanged s = withSession s $ flushFinderCaches
1743
1744 -- -----------------------------------------------------------------------------
1745 -- inspecting the session
1746
1747 -- | Get the module dependency graph.
1748 getModuleGraph :: Session -> IO ModuleGraph -- ToDo: DiGraph ModSummary
1749 getModuleGraph s = withSession s (return . hsc_mod_graph)
1750
1751 isLoaded :: Session -> ModuleName -> IO Bool
1752 isLoaded s m = withSession s $ \hsc_env ->
1753 return $! isJust (lookupUFM (hsc_HPT hsc_env) m)
1754
1755 getBindings :: Session -> IO [TyThing]
1756 getBindings s = withSession s (return . nameEnvElts . ic_type_env . hsc_IC)
1757
1758 getPrintUnqual :: Session -> IO PrintUnqualified
1759 getPrintUnqual s = withSession s (return . icPrintUnqual . hsc_IC)
1760
1761 -- | Container for information about a 'Module'.
1762 data ModuleInfo = ModuleInfo {
1763 minf_type_env :: TypeEnv,
1764 minf_exports :: NameSet, -- ToDo, [AvailInfo] like ModDetails?
1765 minf_rdr_env :: Maybe GlobalRdrEnv, -- Nothing for a compiled/package mod
1766 minf_instances :: [Instance],
1767 #ifdef GHCI
1768 minf_dbg_sites :: [(SiteNumber,Coord)]
1769 #endif
1770 -- ToDo: this should really contain the ModIface too
1771 }
1772 -- We don't want HomeModInfo here, because a ModuleInfo applies
1773 -- to package modules too.
1774
1775 -- | Request information about a loaded 'Module'
1776 getModuleInfo :: Session -> Module -> IO (Maybe ModuleInfo)
1777 getModuleInfo s mdl = withSession s $ \hsc_env -> do
1778 let mg = hsc_mod_graph hsc_env
1779 if mdl `elem` map ms_mod mg
1780 then getHomeModuleInfo hsc_env (moduleName mdl)
1781 else do
1782 {- if isHomeModule (hsc_dflags hsc_env) mdl
1783 then return Nothing
1784 else -} getPackageModuleInfo hsc_env mdl
1785 -- getPackageModuleInfo will attempt to find the interface, so
1786 -- we don't want to call it for a home module, just in case there
1787 -- was a problem loading the module and the interface doesn't
1788 -- exist... hence the isHomeModule test here. (ToDo: reinstate)
1789
1790 getPackageModuleInfo :: HscEnv -> Module -> IO (Maybe ModuleInfo)
1791 getPackageModuleInfo hsc_env mdl = do
1792 #ifdef GHCI
1793 (_msgs, mb_avails) <- getModuleExports hsc_env mdl
1794 case mb_avails of
1795 Nothing -> return Nothing
1796 Just avails -> do
1797 eps <- readIORef (hsc_EPS hsc_env)
1798 let
1799 names = availsToNameSet avails
1800 pte = eps_PTE eps
1801 tys = [ ty | name <- concatMap availNames avails,
1802 Just ty <- [lookupTypeEnv pte name] ]
1803 --
1804 return (Just (ModuleInfo {
1805 minf_type_env = mkTypeEnv tys,
1806 minf_exports = names,
1807 minf_rdr_env = Just $! nameSetToGlobalRdrEnv names (moduleName mdl),
1808 minf_instances = error "getModuleInfo: instances for package module unimplemented",
1809 minf_dbg_sites = noDbgSites
1810 }))
1811 #else
1812 -- bogusly different for non-GHCI (ToDo)
1813 return Nothing
1814 #endif
1815
1816 getHomeModuleInfo hsc_env mdl =
1817 case lookupUFM (hsc_HPT hsc_env) mdl of
1818 Nothing -> return Nothing
1819 Just hmi -> do
1820 let details = hm_details hmi
1821 return (Just (ModuleInfo {
1822 minf_type_env = md_types details,
1823 minf_exports = availsToNameSet (md_exports details),
1824 minf_rdr_env = mi_globals $! hm_iface hmi,
1825 minf_instances = md_insts details
1826 #ifdef GHCI
1827 ,minf_dbg_sites = md_dbg_sites details
1828 #endif
1829 }))
1830
1831 -- | The list of top-level entities defined in a module
1832 modInfoTyThings :: ModuleInfo -> [TyThing]
1833 modInfoTyThings minf = typeEnvElts (minf_type_env minf)
1834
1835 modInfoTopLevelScope :: ModuleInfo -> Maybe [Name]
1836 modInfoTopLevelScope minf
1837 = fmap (map gre_name . globalRdrEnvElts) (minf_rdr_env minf)
1838
1839 modInfoExports :: ModuleInfo -> [Name]
1840 modInfoExports minf = nameSetToList $! minf_exports minf
1841
1842 -- | Returns the instances defined by the specified module.
1843 -- Warning: currently unimplemented for package modules.
1844 modInfoInstances :: ModuleInfo -> [Instance]
1845 modInfoInstances = minf_instances
1846
1847 modInfoIsExportedName :: ModuleInfo -> Name -> Bool
1848 modInfoIsExportedName minf name = elemNameSet name (minf_exports minf)
1849
1850 modInfoPrintUnqualified :: ModuleInfo -> Maybe PrintUnqualified
1851 modInfoPrintUnqualified minf = fmap mkPrintUnqualified (minf_rdr_env minf)
1852
1853 modInfoLookupName :: Session -> ModuleInfo -> Name -> IO (Maybe TyThing)
1854 modInfoLookupName s minf name = withSession s $ \hsc_env -> do
1855 case lookupTypeEnv (minf_type_env minf) name of
1856 Just tyThing -> return (Just tyThing)
1857 Nothing -> do
1858 eps <- readIORef (hsc_EPS hsc_env)
1859 return $! lookupType (hsc_dflags hsc_env)
1860 (hsc_HPT hsc_env) (eps_PTE eps) name
1861
1862 #ifdef GHCI
1863 modInfoBkptSites = minf_dbg_sites
1864 #endif
1865
1866 isDictonaryId :: Id -> Bool
1867 isDictonaryId id
1868 = case tcSplitSigmaTy (idType id) of { (tvs, theta, tau) -> isDictTy tau }
1869
1870 -- | Looks up a global name: that is, any top-level name in any
1871 -- visible module. Unlike 'lookupName', lookupGlobalName does not use
1872 -- the interactive context, and therefore does not require a preceding
1873 -- 'setContext'.
1874 lookupGlobalName :: Session -> Name -> IO (Maybe TyThing)
1875 lookupGlobalName s name = withSession s $ \hsc_env -> do
1876 eps <- readIORef (hsc_EPS hsc_env)
1877 return $! lookupType (hsc_dflags hsc_env)
1878 (hsc_HPT hsc_env) (eps_PTE eps) name
1879
1880 -- -----------------------------------------------------------------------------
1881 -- Misc exported utils
1882
1883 dataConType :: DataCon -> Type
1884 dataConType dc = idType (dataConWrapId dc)
1885
1886 -- | print a 'NamedThing', adding parentheses if the name is an operator.
1887 pprParenSymName :: NamedThing a => a -> SDoc
1888 pprParenSymName a = parenSymOcc (getOccName a) (ppr (getName a))
1889
1890 -- ----------------------------------------------------------------------------
1891
1892 #if 0
1893
1894 -- ToDo:
1895 -- - Data and Typeable instances for HsSyn.
1896
1897 -- ToDo: check for small transformations that happen to the syntax in
1898 -- the typechecker (eg. -e ==> negate e, perhaps for fromIntegral)
1899
1900 -- ToDo: maybe use TH syntax instead of IfaceSyn? There's already a way
1901 -- to get from TyCons, Ids etc. to TH syntax (reify).
1902
1903 -- :browse will use either lm_toplev or inspect lm_interface, depending
1904 -- on whether the module is interpreted or not.
1905
1906 -- This is for reconstructing refactored source code
1907 -- Calls the lexer repeatedly.
1908 -- ToDo: add comment tokens to token stream
1909 getTokenStream :: Session -> Module -> IO [Located Token]
1910 #endif
1911
1912 -- -----------------------------------------------------------------------------
1913 -- Interactive evaluation
1914
1915 -- | Takes a 'ModuleName' and possibly a 'PackageId', and consults the
1916 -- filesystem and package database to find the corresponding 'Module',
1917 -- using the algorithm that is used for an @import@ declaration.
1918 findModule :: Session -> ModuleName -> Maybe PackageId -> IO Module
1919 findModule s mod_name maybe_pkg = withSession s $ \hsc_env ->
1920 findModule' hsc_env mod_name maybe_pkg
1921
1922 findModule' hsc_env mod_name maybe_pkg =
1923 let
1924 dflags = hsc_dflags hsc_env
1925 hpt = hsc_HPT hsc_env
1926 this_pkg = thisPackage dflags
1927 in
1928 case lookupUFM hpt mod_name of
1929 Just mod_info -> return (mi_module (hm_iface mod_info))
1930 _not_a_home_module -> do
1931 res <- findImportedModule hsc_env mod_name Nothing
1932 case res of
1933 Found _ m | modulePackageId m /= this_pkg -> return m
1934 | otherwise -> throwDyn (CmdLineError (showSDoc $
1935 text "module" <+> pprModule m <+>
1936 text "is not loaded"))
1937 err -> let msg = cannotFindModule dflags mod_name err in
1938 throwDyn (CmdLineError (showSDoc msg))
1939
1940 #ifdef GHCI
1941
1942 -- | Set the interactive evaluation context.
1943 --
1944 -- Setting the context doesn't throw away any bindings; the bindings
1945 -- we've built up in the InteractiveContext simply move to the new
1946 -- module. They always shadow anything in scope in the current context.
1947 setContext :: Session
1948 -> [Module] -- entire top level scope of these modules
1949 -> [Module] -- exports only of these modules
1950 -> IO ()
1951 setContext sess@(Session ref) toplev_mods export_mods = do
1952 hsc_env <- readIORef ref
1953 let old_ic = hsc_IC hsc_env
1954 hpt = hsc_HPT hsc_env
1955 --
1956 export_env <- mkExportEnv hsc_env export_mods
1957 toplev_envs <- mapM (mkTopLevEnv hpt) toplev_mods
1958 let all_env = foldr plusGlobalRdrEnv export_env toplev_envs
1959 writeIORef ref hsc_env{ hsc_IC = old_ic { ic_toplev_scope = toplev_mods,
1960 ic_exports = export_mods,
1961 ic_rn_gbl_env = all_env }}
1962 reinstallBreakpointHandlers sess
1963
1964 -- Make a GlobalRdrEnv based on the exports of the modules only.
1965 mkExportEnv :: HscEnv -> [Module] -> IO GlobalRdrEnv
1966 mkExportEnv hsc_env mods = do
1967 stuff <- mapM (getModuleExports hsc_env) mods
1968 let
1969 (_msgs, mb_name_sets) = unzip stuff
1970 gres = [ nameSetToGlobalRdrEnv (availsToNameSet avails) (moduleName mod)
1971 | (Just avails, mod) <- zip mb_name_sets mods ]
1972 --
1973 return $! foldr plusGlobalRdrEnv emptyGlobalRdrEnv gres
1974
1975 nameSetToGlobalRdrEnv :: NameSet -> ModuleName -> GlobalRdrEnv
1976 nameSetToGlobalRdrEnv names mod =
1977 mkGlobalRdrEnv [ GRE { gre_name = name, gre_prov = vanillaProv mod }
1978 | name <- nameSetToList names ]
1979
1980 vanillaProv :: ModuleName -> Provenance
1981 -- We're building a GlobalRdrEnv as if the user imported
1982 -- all the specified modules into the global interactive module
1983 vanillaProv mod_name = Imported [ImpSpec { is_decl = decl, is_item = ImpAll}]
1984 where
1985 decl = ImpDeclSpec { is_mod = mod_name, is_as = mod_name,
1986 is_qual = False,
1987 is_dloc = srcLocSpan interactiveSrcLoc }
1988
1989 mkTopLevEnv :: HomePackageTable -> Module -> IO GlobalRdrEnv
1990 mkTopLevEnv hpt modl
1991 = case lookupUFM hpt (moduleName modl) of
1992 Nothing -> throwDyn (ProgramError ("mkTopLevEnv: not a home module " ++
1993 showSDoc (ppr modl)))
1994 Just details ->
1995 case mi_globals (hm_iface details) of
1996 Nothing ->
1997 throwDyn (ProgramError ("mkTopLevEnv: not interpreted "
1998 ++ showSDoc (ppr modl)))
1999 Just env -> return env
2000
2001 -- | Get the interactive evaluation context, consisting of a pair of the
2002 -- set of modules from which we take the full top-level scope, and the set
2003 -- of modules from which we take just the exports respectively.
2004 getContext :: Session -> IO ([Module],[Module])
2005 getContext s = withSession s (\HscEnv{ hsc_IC=ic } ->
2006 return (ic_toplev_scope ic, ic_exports ic))
2007
2008 -- | Returns 'True' if the specified module is interpreted, and hence has
2009 -- its full top-level scope available.
2010 moduleIsInterpreted :: Session -> Module -> IO Bool
2011 moduleIsInterpreted s modl = withSession s $ \h ->
2012 if modulePackageId modl /= thisPackage (hsc_dflags h)
2013 then return False
2014 else case lookupUFM (hsc_HPT h) (moduleName modl) of
2015 Just details -> return (isJust (mi_globals (hm_iface details)))
2016 _not_a_home_module -> return False
2017
2018 -- | Looks up an identifier in the current interactive context (for :info)
2019 getInfo :: Session -> Name -> IO (Maybe (TyThing,Fixity,[Instance]))
2020 getInfo s name = withSession s $ \hsc_env -> tcRnGetInfo hsc_env name
2021
2022 -- | Returns all names in scope in the current interactive context
2023 getNamesInScope :: Session -> IO [Name]
2024 getNamesInScope s = withSession s $ \hsc_env -> do
2025 return (map gre_name (globalRdrEnvElts (ic_rn_gbl_env (hsc_IC hsc_env))))
2026
2027 getRdrNamesInScope :: Session -> IO [RdrName]
2028 getRdrNamesInScope s = withSession s $ \hsc_env -> do
2029 let env = ic_rn_gbl_env (hsc_IC hsc_env)
2030 return (concat (map greToRdrNames (globalRdrEnvElts env)))
2031
2032 -- ToDo: move to RdrName
2033 greToRdrNames :: GlobalRdrElt -> [RdrName]
2034 greToRdrNames GRE{ gre_name = name, gre_prov = prov }
2035 = case prov of
2036 LocalDef -> [unqual]
2037 Imported specs -> concat (map do_spec (map is_decl specs))
2038 where
2039 occ = nameOccName name
2040 unqual = Unqual occ
2041 do_spec decl_spec
2042 | is_qual decl_spec = [qual]
2043 | otherwise = [unqual,qual]
2044 where qual = Qual (is_as decl_spec) occ
2045
2046 -- | Parses a string as an identifier, and returns the list of 'Name's that
2047 -- the identifier can refer to in the current interactive context.
2048 parseName :: Session -> String -> IO [Name]
2049 parseName s str = withSession s $ \hsc_env -> do
2050 maybe_rdr_name <- hscParseIdentifier (hsc_dflags hsc_env) str
2051 case maybe_rdr_name of
2052 Nothing -> return []
2053 Just (L _ rdr_name) -> do
2054 mb_names <- tcRnLookupRdrName hsc_env rdr_name
2055 case mb_names of
2056 Nothing -> return []
2057 Just ns -> return ns
2058 -- ToDo: should return error messages
2059
2060 -- | Returns the 'TyThing' for a 'Name'. The 'Name' may refer to any
2061 -- entity known to GHC, including 'Name's defined using 'runStmt'.
2062 lookupName :: Session -> Name -> IO (Maybe TyThing)
2063 lookupName s name = withSession s $ \hsc_env -> tcRnLookupName hsc_env name
2064
2065 -- -----------------------------------------------------------------------------
2066 -- Getting the type of an expression
2067
2068 -- | Get the type of an expression
2069 exprType :: Session -> String -> IO (Maybe Type)
2070 exprType s expr = withSession s $ \hsc_env -> do
2071 maybe_stuff <- hscTcExpr hsc_env expr
2072 case maybe_stuff of
2073 Nothing -> return Nothing
2074 Just ty -> return (Just tidy_ty)
2075 where
2076 tidy_ty = tidyType emptyTidyEnv ty
2077
2078 -- -----------------------------------------------------------------------------
2079 -- Getting the kind of a type
2080
2081 -- | Get the kind of a type
2082 typeKind :: Session -> String -> IO (Maybe Kind)
2083 typeKind s str = withSession s $ \hsc_env -> do
2084 maybe_stuff <- hscKcType hsc_env str
2085 case maybe_stuff of
2086 Nothing -> return Nothing
2087 Just kind -> return (Just kind)
2088
2089 -----------------------------------------------------------------------------
2090 -- cmCompileExpr: compile an expression and deliver an HValue
2091
2092 compileExpr :: Session -> String -> IO (Maybe HValue)
2093 compileExpr s expr = withSession s $ \hsc_env -> do
2094 maybe_stuff <- hscStmt hsc_env ("let __cmCompileExpr = "++expr)
2095 case maybe_stuff of
2096 Nothing -> return Nothing
2097 Just (new_ic, names, hval) -> do
2098 -- Run it!
2099 hvals <- (unsafeCoerce# hval) :: IO [HValue]
2100
2101 case (names,hvals) of
2102 ([n],[hv]) -> return (Just hv)
2103 _ -> panic "compileExpr"
2104
2105 -- -----------------------------------------------------------------------------
2106 -- Compile an expression into a dynamic
2107
2108 dynCompileExpr :: Session -> String -> IO (Maybe Dynamic)
2109 dynCompileExpr ses expr = do
2110 (full,exports) <- getContext ses
2111 setContext ses full $
2112 (mkModule
2113 (stringToPackageId "base") (mkModuleName "Data.Dynamic")
2114 ):exports
2115 let stmt = "let __dynCompileExpr = Data.Dynamic.toDyn (" ++ expr ++ ")"
2116 res <- withSession ses (flip hscStmt stmt)
2117 setContext ses full exports
2118 case res of
2119 Nothing -> return Nothing
2120 Just (_, names, hvals) -> do
2121 vals <- (unsafeCoerce# hvals :: IO [Dynamic])
2122 case (names,vals) of
2123 (_:[], v:[]) -> return (Just v)
2124 _ -> panic "dynCompileExpr"
2125
2126 -- -----------------------------------------------------------------------------
2127 -- running a statement interactively
2128
2129 data RunResult
2130 = RunOk [Name] -- ^ names bound by this evaluation
2131 | RunFailed -- ^ statement failed compilation
2132 | RunException Exception -- ^ statement raised an exception
2133
2134 -- | Run a statement in the current interactive context. Statemenet
2135 -- may bind multple values.
2136 runStmt :: Session -> String -> IO RunResult
2137 runStmt (Session ref) expr
2138 = do
2139 hsc_env <- readIORef ref
2140
2141 -- Turn off -fwarn-unused-bindings when running a statement, to hide
2142 -- warnings about the implicit bindings we introduce.
2143 let dflags' = dopt_unset (hsc_dflags hsc_env) Opt_WarnUnusedBinds
2144 hsc_env' = hsc_env{ hsc_dflags = dflags' }
2145
2146 maybe_stuff <- hscStmt hsc_env' expr
2147
2148 case maybe_stuff of
2149 Nothing -> return RunFailed
2150 Just (new_hsc_env, names, hval) -> do
2151
2152 let thing_to_run = unsafeCoerce# hval :: IO [HValue]
2153 either_hvals <- sandboxIO thing_to_run
2154
2155 case either_hvals of
2156 Left e -> do
2157 -- on error, keep the *old* interactive context,
2158 -- so that 'it' is not bound to something
2159 -- that doesn't exist.
2160 return (RunException e)
2161
2162 Right hvals -> do
2163 -- Get the newly bound things, and bind them.
2164 -- Don't need to delete any shadowed bindings;
2165 -- the new ones override the old ones.
2166 extendLinkEnv (zip names hvals)
2167
2168 writeIORef ref new_hsc_env
2169 return (RunOk names)
2170
2171 -- When running a computation, we redirect ^C exceptions to the running
2172 -- thread. ToDo: we might want a way to continue even if the target
2173 -- thread doesn't die when it receives the exception... "this thread
2174 -- is not responding".
2175 sandboxIO :: IO a -> IO (Either Exception a)
2176 sandboxIO thing = do
2177 m <- newEmptyMVar
2178 ts <- takeMVar interruptTargetThread
2179 child <- forkIO (do res <- Exception.try thing; putMVar m res)
2180 putMVar interruptTargetThread (child:ts)
2181 takeMVar m `finally` modifyMVar_ interruptTargetThread (return.tail)
2182
2183 {-
2184 -- This version of sandboxIO runs the expression in a completely new
2185 -- RTS main thread. It is disabled for now because ^C exceptions
2186 -- won't be delivered to the new thread, instead they'll be delivered
2187 -- to the (blocked) GHCi main thread.
2188
2189 -- SLPJ: when re-enabling this, reflect a wrong-stat error as an exception
2190
2191 sandboxIO :: IO a -> IO (Either Int (Either Exception a))
2192 sandboxIO thing = do
2193 st_thing <- newStablePtr (Exception.try thing)
2194 alloca $ \ p_st_result -> do
2195 stat <- rts_evalStableIO st_thing p_st_result
2196 freeStablePtr st_thing
2197 if stat == 1
2198 then do st_result <- peek p_st_result
2199 result <- deRefStablePtr st_result
2200 freeStablePtr st_result
2201 return (Right result)
2202 else do
2203 return (Left (fromIntegral stat))
2204
2205 foreign import "rts_evalStableIO" {- safe -}
2206 rts_evalStableIO :: StablePtr (IO a) -> Ptr (StablePtr a) -> IO CInt
2207 -- more informative than the C type!
2208 -}
2209
2210 -----------------------------------------------------------------------------
2211 -- show a module and it's source/object filenames
2212
2213 showModule :: Session -> ModSummary -> IO String
2214 showModule s mod_summary = withSession s $ \hsc_env -> do
2215 case lookupUFM (hsc_HPT hsc_env) (ms_mod_name mod_summary) of
2216 Nothing -> panic "missing linkable"
2217 Just mod_info -> return (showModMsg (hscTarget (hsc_dflags hsc_env)) (not obj_linkable) mod_summary)
2218 where
2219 obj_linkable = isObjectLinkable (expectJust "showModule" (hm_linkable mod_info))
2220
2221 getBreakpointHandler :: Session -> IO (Maybe (BkptHandler Module))
2222 getBreakpointHandler session = getSessionDynFlags session >>= return . bkptHandler
2223
2224 setBreakpointHandler :: Session -> BkptHandler Module -> IO ()
2225 setBreakpointHandler session handler = do
2226 dflags <- getSessionDynFlags session
2227 setSessionDynFlags session dflags{ bkptHandler = Just handler }
2228 let linkEnv = [ ( breakpointJumpName
2229 , unsafeCoerce# (jumpFunction session handler))
2230 , ( breakpointCondJumpName
2231 , unsafeCoerce# (jumpCondFunction session handler))
2232 , ( breakpointAutoJumpName
2233 , unsafeCoerce# (jumpAutoFunction session handler))
2234 ]
2235 writeIORef v_bkptLinkEnv linkEnv
2236 dflags <- getSessionDynFlags session
2237 reinstallBreakpointHandlers session
2238
2239 reinstallBreakpointHandlers :: Session -> IO ()
2240 reinstallBreakpointHandlers session = do
2241 dflags <- getSessionDynFlags session
2242 let mode = ghcMode dflags
2243 when (mode == Interactive) $ do
2244 linkEnv <- readIORef v_bkptLinkEnv
2245 initDynLinker dflags
2246 extendLinkEnv linkEnv
2247
2248 type SiteInfo = (String, String, SiteNumber)
2249 jumpFunction, jumpAutoFunction :: Session -> BkptHandler Module -> Int -> [Opaque]
2250 -> SiteInfo -> String -> b -> b
2251 jumpCondFunction :: Session -> BkptHandler Module -> Int -> [Opaque]
2252 -> SiteInfo -> String -> Bool -> b -> b
2253 jumpFunctionM :: Session -> BkptHandler a -> Int -> [Opaque] -> BkptLocation a
2254 -> String -> b -> IO b
2255
2256 jumpCondFunction _ _ _ _ _ _ False b = b
2257 jumpCondFunction session handler ptr hValues siteInfo locmsg True b
2258 = jumpFunction session handler ptr hValues siteInfo locmsg b
2259
2260 jumpFunction session handler ptr hValues siteInfo locmsg b
2261 | site <- mkSite siteInfo
2262 = unsafePerformIO $ jumpFunctionM session handler ptr hValues site locmsg b
2263
2264 jumpFunctionM session handler (I# idsPtr) wrapped_hValues site locmsg b =
2265 do
2266 ids <- deRefStablePtr (castPtrToStablePtr (Ptr (int2Addr# idsPtr)))
2267 ASSERT (length ids == length wrapped_hValues) return ()
2268 let hValues = [unsafeCoerce# hv | O hv <- wrapped_hValues]
2269 handleBreakpoint handler session (zip ids hValues) site locmsg b
2270
2271 jumpAutoFunction session handler ptr hValues siteInfo locmsg b
2272 | site <- mkSite siteInfo
2273 = unsafePerformIO $ do
2274 break <- isAutoBkptEnabled handler session site
2275 if break
2276 then jumpFunctionM session handler ptr hValues site locmsg b
2277 else return b
2278
2279 jumpStepByStepFunction session handler ptr hValues siteInfo locmsg b
2280 | site <- mkSite siteInfo
2281 = unsafePerformIO $ do
2282 jumpFunctionM session handler ptr hValues site locmsg b
2283
2284 mkSite :: SiteInfo -> BkptLocation Module
2285 mkSite (pkgName, modName, sitenum) =
2286 (mkModule (stringToPackageId pkgName) (mkModuleName modName), sitenum)
2287
2288 obtainTerm :: Session -> Bool -> Id -> IO (Maybe Term)
2289 obtainTerm sess force id = withSession sess $ \hsc_env ->
2290 getHValue (varName id) >>= traverse (cvObtainTerm hsc_env force Nothing)
2291
2292 #endif /* GHCI */