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