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