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