[project @ 2005-03-31 10:16:33 by simonmar]
[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         getSessionDynFlags,
21         setSessionDynFlags,
22         setMsgHandler,
23
24         -- * Targets
25         Target(..),
26         setTargets,
27         getTargets,
28         addTarget,
29         guessTarget,
30         
31         -- * Loading\/compiling the program
32         depanal,
33         load, SuccessFlag(..),          -- also does depanal
34         workingDirectoryChanged,
35
36         -- * Inspecting the module structure of the program
37         ModuleGraph, ModSummary(..),
38         getModuleGraph,
39         isLoaded,
40         topSortModuleGraph,
41
42         -- * Interactive evaluation
43         getBindings, getPrintUnqual,
44 #ifdef GHCI
45         setContext, getContext, 
46         moduleIsInterpreted,
47         getInfo, GetInfoResult,
48         exprType,
49         typeKind,
50         lookupName,
51         RunResult(..),
52         runStmt,
53         browseModule,
54         showModule,
55         compileExpr, HValue,
56 #endif
57
58         -- * Abstract syntax elements
59         Module, mkModule, pprModule,
60         Type, dropForAlls,
61         Kind,
62         Name, Id, TyCon, Class, DataCon,
63         TyThing(..), 
64         idType,
65
66         -- used by DriverMkDepend:
67         sessionHscEnv,
68         cyclicModuleErr,
69   ) where
70
71 {-
72  ToDo:
73
74   * return error messages rather than printing them.
75   * inline bits of HscMain here to simplify layering: hscGetInfo,
76     hscTcExpr, hscStmt.
77   * implement second argument to load.
78   * we need to expose DynFlags, so should parseDynamicFlags really be
79     part of this interface?
80   * what StaticFlags should we expose, if any?
81 -}
82
83 #include "HsVersions.h"
84
85 #ifdef GHCI
86 import qualified Linker
87 import Linker           ( HValue, extendLinkEnv )
88 import NameEnv          ( lookupNameEnv )
89 import TcRnDriver       ( mkExportEnv, getModuleContents )
90 import RdrName          ( GlobalRdrEnv, plusGlobalRdrEnv )
91 import HscMain          ( hscGetInfo, GetInfoResult, 
92                           hscStmt, hscTcExpr, hscKcType )
93 import Type             ( tidyType )
94 import VarEnv           ( emptyTidyEnv )
95 import GHC.Exts         ( unsafeCoerce# )
96 import IfaceSyn         ( IfaceDecl )
97 #endif
98
99 import Type             ( Kind, Type, dropForAlls )
100 import Id               ( Id, idType )
101 import TyCon            ( TyCon )
102 import Class            ( Class )
103 import DataCon          ( DataCon )
104 import Name             ( Name )
105 import NameEnv          ( nameEnvElts )
106 import DriverPipeline
107 import DriverPhases     ( Phase(..), isHaskellSrcFilename, startPhase )
108 import GetImports       ( getImports )
109 import Packages         ( isHomePackage )
110 import Finder
111 import HscMain          ( newHscEnv )
112 import HscTypes
113 import DynFlags
114 import StaticFlags
115 import SysTools         ( initSysTools, cleanTempFiles )
116 import Module
117 import FiniteMap
118 import Panic
119 import Digraph
120 import ErrUtils         ( showPass )
121 import qualified ErrUtils
122 import Util
123 import StringBuffer     ( StringBuffer(..), hGetStringBuffer, lexemeToString )
124 import Outputable
125 import SysTools         ( cleanTempFilesExcept )
126 import BasicTypes       ( SuccessFlag(..), succeeded )
127 import Maybes           ( orElse, expectJust, mapCatMaybes )
128
129 import Directory        ( getModificationTime, doesFileExist )
130 import Maybe            ( isJust, isNothing, fromJust )
131 import Maybes           ( expectJust )
132 import List             ( partition, nub )
133 import Monad            ( unless, when, foldM )
134 import System           ( exitWith, ExitCode(..) )
135 import Time             ( ClockTime )
136 import EXCEPTION as Exception hiding (handle)
137 import GLAEXTS          ( Int(..) )
138 import DATA_IOREF
139 import IO
140 import Prelude hiding (init)
141
142 -- -----------------------------------------------------------------------------
143 -- Exception handlers
144
145 -- | Install some default exception handlers and run the inner computation.
146 -- Unless you want to handle exceptions yourself, you should wrap this around
147 -- the top level of your program.  The default handlers output the error
148 -- message(s) to stderr and exit cleanly.
149 defaultErrorHandler :: IO a -> IO a
150 defaultErrorHandler inner = 
151   -- top-level exception handler: any unrecognised exception is a compiler bug.
152   handle (\exception -> do
153            hFlush stdout
154            case exception of
155                 -- an IO exception probably isn't our fault, so don't panic
156                 IOException _ ->  hPutStrLn stderr (show exception)
157                 AsyncException StackOverflow ->
158                         hPutStrLn stderr "stack overflow: use +RTS -K<size> to increase it"
159                 _other ->  hPutStr stderr (show (Panic (show exception)))
160            exitWith (ExitFailure 1)
161          ) $
162
163   -- all error messages are propagated as exceptions
164   handleDyn (\dyn -> do
165                 hFlush stdout
166                 case dyn of
167                      PhaseFailed _ code -> exitWith code
168                      Interrupted -> exitWith (ExitFailure 1)
169                      _ -> do hPutStrLn stderr (show (dyn :: GhcException))
170                              exitWith (ExitFailure 1)
171             ) $
172   inner
173
174 -- | Install a default cleanup handler to remove temporary files
175 -- deposited by a GHC run.  This is seperate from
176 -- 'defaultErrorHandler', because you might want to override the error
177 -- handling, but still get the ordinary cleanup behaviour.
178 defaultCleanupHandler :: DynFlags -> IO a -> IO a
179 defaultCleanupHandler dflags inner = 
180    -- make sure we clean up after ourselves
181    later (unless (dopt Opt_KeepTmpFiles dflags) $ 
182             cleanTempFiles dflags) 
183         -- exceptions will be blocked while we clean the temporary files,
184         -- so there shouldn't be any difficulty if we receive further
185         -- signals.
186    inner
187
188
189 -- | Initialises GHC.  This must be done /once/ only.  Takes the
190 -- command-line arguments.  All command-line arguments which aren't
191 -- understood by GHC will be returned.
192
193 init :: [String] -> IO [String]
194 init args = do
195    -- catch ^C
196    installSignalHandlers
197
198    -- Grab the -B option if there is one
199    let (minusB_args, argv1) = partition (prefixMatch "-B") args
200    dflags0 <- initSysTools minusB_args defaultDynFlags
201    writeIORef v_initDynFlags dflags0
202
203    -- Parse the static flags
204    argv2 <- parseStaticFlags argv1
205    return argv2
206
207 GLOBAL_VAR(v_initDynFlags, error "initDynFlags", DynFlags)
208         -- stores the DynFlags between the call to init and subsequent
209         -- calls to newSession.
210
211 -- | Starts a new session.  A session consists of a set of loaded
212 -- modules, a set of options (DynFlags), and an interactive context.
213 -- ToDo: GhcMode should say "keep typechecked code" and\/or "keep renamed
214 -- code".
215 newSession :: GhcMode -> IO Session
216 newSession mode = do
217   dflags0 <- readIORef v_initDynFlags
218   dflags <- initDynFlags dflags0
219   env <- newHscEnv dflags{ ghcMode=mode }
220   ref <- newIORef env
221   return (Session ref)
222
223 -- tmp: this breaks the abstraction, but required because DriverMkDepend
224 -- needs to call the Finder.  ToDo: untangle this.
225 sessionHscEnv :: Session -> IO HscEnv
226 sessionHscEnv (Session ref) = readIORef ref
227
228 withSession :: Session -> (HscEnv -> IO a) -> IO a
229 withSession (Session ref) f = do h <- readIORef ref; f h
230
231 modifySession :: Session -> (HscEnv -> HscEnv) -> IO ()
232 modifySession (Session ref) f = do h <- readIORef ref; writeIORef ref $! f h
233
234 -- -----------------------------------------------------------------------------
235 -- Flags & settings
236
237 -- | Grabs the DynFlags from the Session
238 getSessionDynFlags :: Session -> IO DynFlags
239 getSessionDynFlags s = withSession s (return . hsc_dflags)
240
241 -- | Updates the DynFlags in a Session
242 setSessionDynFlags :: Session -> DynFlags -> IO ()
243 setSessionDynFlags s dflags = modifySession s (\h -> h{ hsc_dflags = dflags })
244
245 -- | Messages during compilation (eg. warnings and progress messages)
246 -- are reported using this callback.  By default, these messages are
247 -- printed to stderr.
248 setMsgHandler :: (String -> IO ()) -> IO ()
249 setMsgHandler = ErrUtils.setMsgHandler
250
251 -- -----------------------------------------------------------------------------
252 -- Targets
253
254 -- ToDo: think about relative vs. absolute file paths. And what
255 -- happens when the current directory changes.
256
257 -- | Sets the targets for this session.  Each target may be a module name
258 -- or a filename.  The targets correspond to the set of root modules for
259 -- the program\/library.  Unloading the current program is achieved by
260 -- setting the current set of targets to be empty, followed by load.
261 setTargets :: Session -> [Target] -> IO ()
262 setTargets s targets = modifySession s (\h -> h{ hsc_targets = targets })
263
264 -- | returns the current set of targets
265 getTargets :: Session -> IO [Target]
266 getTargets s = withSession s (return . hsc_targets)
267
268 -- Add another target, or update an existing target with new content.
269 addTarget :: Session -> Target -> IO ()
270 addTarget s target
271   = modifySession s (\h -> h{ hsc_targets = target : hsc_targets h })
272
273 -- Remove a target
274 -- removeTarget :: Session -> Module -> IO ()
275
276 -- Attempts to guess what Target a string refers to.  This function implements
277 -- the --make/GHCi command-line syntax for filenames: 
278 --
279 --      - if the string looks like a Haskell source filename, then interpret
280 --        it as such
281 --      - if adding a .hs or .lhs suffix yields the name of an existing file,
282 --        then use that
283 --      - otherwise interpret the string as a module name
284 --
285 guessTarget :: String -> IO Target
286 guessTarget file
287    | isHaskellSrcFilename file
288    = return (Target (TargetFile file) Nothing)
289    | otherwise
290    = do exists <- doesFileExist hs_file
291         if exists then return (Target (TargetFile hs_file) Nothing) else do
292         exists <- doesFileExist lhs_file
293         if exists then return (Target (TargetFile lhs_file) Nothing) else do
294         return (Target (TargetModule (mkModule file)) Nothing)
295      where 
296          hs_file = file ++ ".hs"
297          lhs_file = file ++ ".lhs"
298
299 -- -----------------------------------------------------------------------------
300 -- Loading the program
301
302 -- | The result of load.
303 data LoadResult
304   = LoadOk      Errors  -- ^ all specified targets were loaded successfully.
305   | LoadFailed  Errors  -- ^ not all modules were loaded.
306
307 type Errors = [String]
308
309 {-
310 data ErrMsg = ErrMsg { 
311         errMsgSeverity  :: Severity,  -- warning, error, etc.
312         errMsgSpans     :: [SrcSpan],
313         errMsgShortDoc  :: Doc,
314         errMsgExtraInfo :: Doc
315         }
316 -}
317
318 -- Perform a dependency analysis starting from the current targets
319 -- and update the session with the new module graph.
320 depanal :: Session -> [Module] -> IO ()
321 depanal (Session ref) excluded_mods = do
322   hsc_env <- readIORef ref
323   let
324          dflags  = hsc_dflags hsc_env
325          gmode   = ghcMode (hsc_dflags hsc_env)
326          targets = hsc_targets hsc_env
327          old_graph = hsc_mod_graph hsc_env
328         
329   showPass dflags "Chasing dependencies"
330   when (verbosity dflags >= 1 && gmode == BatchCompile) $
331                hPutStrLn stderr (showSDoc (hcat [
332                      text "Chasing modules from: ",
333                         hcat (punctuate comma (map pprTarget targets))]))
334
335   graph <- downsweep hsc_env old_graph excluded_mods
336   writeIORef ref hsc_env{ hsc_mod_graph=graph }
337
338
339 -- | Try to load the program.  If a Module is supplied, then just
340 -- attempt to load up to this target.  If no Module is supplied,
341 -- then try to load all targets.
342 load :: Session -> Maybe Module -> IO SuccessFlag
343 load s@(Session ref) maybe_mod
344    = do 
345         -- Dependency analysis first.  Note that this fixes the module graph:
346         -- even if we don't get a fully successful upsweep, the full module
347         -- graph is still retained in the Session.  We can tell which modules
348         -- were successfully loaded by inspecting the Session's HPT.
349         depanal s []
350
351         hsc_env <- readIORef ref
352
353         let hpt1      = hsc_HPT hsc_env
354         let dflags    = hsc_dflags hsc_env
355         let mod_graph = hsc_mod_graph hsc_env
356
357         let ghci_mode = ghcMode (hsc_dflags hsc_env) -- this never changes
358         let verb      = verbosity dflags
359
360         -- The "bad" boot modules are the ones for which we have
361         -- B.hs-boot in the module graph, but no B.hs
362         -- The downsweep should have ensured this does not happen
363         -- (see msDeps)
364         let all_home_mods = [ms_mod s | s <- mod_graph, not (isBootSummary s)]
365             bad_boot_mods = [s        | s <- mod_graph, isBootSummary s,
366                                         not (ms_mod s `elem` all_home_mods)]
367         ASSERT( null bad_boot_mods ) return ()
368
369         -- mg2_with_srcimps drops the hi-boot nodes, returning a 
370         -- graph with cycles.  Among other things, it is used for
371         -- backing out partially complete cycles following a failed
372         -- upsweep, and for removing from hpt all the modules
373         -- not in strict downwards closure, during calls to compile.
374         let mg2_with_srcimps :: [SCC ModSummary]
375             mg2_with_srcimps = topSortModuleGraph True mod_graph Nothing
376
377             -- check the stability property for each module.
378             stable_mods@(stable_obj,stable_bco)
379                 | BatchCompile <- ghci_mode = ([],[])
380                 | otherwise = checkStability hpt1 mg2_with_srcimps all_home_mods
381
382             -- prune bits of the HPT which are definitely redundant now,
383             -- to save space.
384             pruned_hpt = pruneHomePackageTable hpt1 
385                                 (flattenSCCs mg2_with_srcimps)
386                                 stable_mods
387
388         evaluate pruned_hpt
389
390         when (verb >= 2) $
391             putStrLn (showSDoc (text "Stable obj:" <+> ppr stable_obj $$
392                                 text "Stable BCO:" <+> ppr stable_bco))
393
394         -- Unload any modules which are going to be re-linked this time around.
395         let stable_linkables = [ linkable
396                                | m <- stable_obj++stable_bco,
397                                  Just hmi <- [lookupModuleEnv pruned_hpt m],
398                                  Just linkable <- [hm_linkable hmi] ]
399         unload hsc_env stable_linkables
400
401         -- We could at this point detect cycles which aren't broken by
402         -- a source-import, and complain immediately, but it seems better
403         -- to let upsweep_mods do this, so at least some useful work gets
404         -- done before the upsweep is abandoned.
405         --hPutStrLn stderr "after tsort:\n"
406         --hPutStrLn stderr (showSDoc (vcat (map ppr mg2)))
407
408         -- Now do the upsweep, calling compile for each module in
409         -- turn.  Final result is version 3 of everything.
410
411         -- Topologically sort the module graph, this time including hi-boot
412         -- nodes, and possibly just including the portion of the graph
413         -- reachable from the module specified in the 2nd argument to load.
414         -- This graph should be cycle-free.
415         -- If we're restricting the upsweep to a portion of the graph, we
416         -- also want to retain everything that is still stable.
417         let full_mg, partial_mg :: [SCC ModSummary]
418             full_mg    = topSortModuleGraph False mod_graph Nothing
419             partial_mg = topSortModuleGraph False mod_graph maybe_mod
420
421             stable_mg = 
422                 [ AcyclicSCC ms
423                 | AcyclicSCC ms <- full_mg,
424                   ms_mod ms `elem` stable_obj++stable_bco,
425                   ms_mod ms `notElem` [ ms_mod ms' | 
426                                         AcyclicSCC ms' <- partial_mg ] ]
427
428             mg = stable_mg ++ partial_mg
429
430         -- clean up between compilations
431         let cleanup = cleanTempFilesExcept dflags
432                           (ppFilesFromSummaries (flattenSCCs mg2_with_srcimps))
433
434         (upsweep_ok, hsc_env1, modsUpswept)
435            <- upsweep (hsc_env { hsc_HPT = emptyHomePackageTable })
436                            pruned_hpt stable_mods cleanup mg
437
438         -- Make modsDone be the summaries for each home module now
439         -- available; this should equal the domain of hpt3.
440         -- Get in in a roughly top .. bottom order (hence reverse).
441
442         let modsDone = reverse modsUpswept
443
444         -- Try and do linking in some form, depending on whether the
445         -- upsweep was completely or only partially successful.
446
447         if succeeded upsweep_ok
448
449          then 
450            -- Easy; just relink it all.
451            do when (verb >= 2) $ 
452                  hPutStrLn stderr "Upsweep completely successful."
453
454               -- Clean up after ourselves
455               cleanTempFilesExcept dflags (ppFilesFromSummaries modsDone)
456
457               -- Issue a warning for the confusing case where the user
458               -- said '-o foo' but we're not going to do any linking.
459               -- We attempt linking if either (a) one of the modules is
460               -- called Main, or (b) the user said -no-hs-main, indicating
461               -- that main() is going to come from somewhere else.
462               --
463               let ofile = outputFile dflags
464               let no_hs_main = dopt Opt_NoHsMain dflags
465               let mb_main_mod = mainModIs dflags
466               let 
467                 main_mod = mb_main_mod `orElse` "Main"
468                 a_root_is_Main 
469                     = any ((==main_mod).moduleUserString.ms_mod) 
470                           mod_graph
471                 do_linking = a_root_is_Main || no_hs_main
472
473               when (ghci_mode == BatchCompile && isJust ofile && not do_linking
474                      && verb > 0) $
475                  hPutStrLn stderr ("Warning: output was redirected with -o, " ++
476                                    "but no output will be generated\n" ++
477                                    "because there is no " ++ main_mod ++ " module.")
478
479               -- link everything together
480               linkresult <- link ghci_mode dflags do_linking (hsc_HPT hsc_env1)
481
482               loadFinish Succeeded linkresult ref hsc_env1
483
484          else 
485            -- Tricky.  We need to back out the effects of compiling any
486            -- half-done cycles, both so as to clean up the top level envs
487            -- and to avoid telling the interactive linker to link them.
488            do when (verb >= 2) $
489                 hPutStrLn stderr "Upsweep partially successful."
490
491               let modsDone_names
492                      = map ms_mod modsDone
493               let mods_to_zap_names 
494                      = findPartiallyCompletedCycles modsDone_names 
495                           mg2_with_srcimps
496               let mods_to_keep
497                      = filter ((`notElem` mods_to_zap_names).ms_mod) 
498                           modsDone
499
500               let hpt4 = retainInTopLevelEnvs (map ms_mod mods_to_keep) 
501                                               (hsc_HPT hsc_env1)
502
503               -- Clean up after ourselves
504               cleanTempFilesExcept dflags (ppFilesFromSummaries mods_to_keep)
505
506               -- there should be no Nothings where linkables should be, now
507               ASSERT(all (isJust.hm_linkable) 
508                         (moduleEnvElts (hsc_HPT hsc_env))) do
509         
510               -- Link everything together
511               linkresult <- link ghci_mode dflags False hpt4
512
513               let hsc_env4 = hsc_env1{ hsc_HPT = hpt4 }
514               loadFinish Failed linkresult ref hsc_env4
515
516 -- Finish up after a load.
517
518 -- If the link failed, unload everything and return.
519 loadFinish all_ok Failed ref hsc_env
520   = do unload hsc_env []
521        writeIORef ref $! discardProg hsc_env
522        return Failed
523
524 -- Empty the interactive context and set the module context to the topmost
525 -- newly loaded module, or the Prelude if none were loaded.
526 loadFinish all_ok Succeeded ref hsc_env
527   = do writeIORef ref $! hsc_env{ hsc_IC = emptyInteractiveContext }
528        return all_ok
529
530
531 -- Forget the current program, but retain the persistent info in HscEnv
532 discardProg :: HscEnv -> HscEnv
533 discardProg hsc_env
534   = hsc_env { hsc_mod_graph = emptyMG, 
535               hsc_IC = emptyInteractiveContext,
536               hsc_HPT = emptyHomePackageTable }
537
538 -- used to fish out the preprocess output files for the purposes of
539 -- cleaning up.  The preprocessed file *might* be the same as the
540 -- source file, but that doesn't do any harm.
541 ppFilesFromSummaries summaries = [ fn | Just fn <- map ms_hspp_file summaries ]
542
543 -----------------------------------------------------------------------------
544 -- Unloading
545
546 unload :: HscEnv -> [Linkable] -> IO ()
547 unload hsc_env stable_linkables -- Unload everthing *except* 'stable_linkables'
548   = case ghcMode (hsc_dflags hsc_env) of
549         BatchCompile -> return ()
550 #ifdef GHCI
551         Interactive -> Linker.unload (hsc_dflags hsc_env) stable_linkables
552 #else
553         Interactive -> panic "unload: no interpreter"
554 #endif
555         other -> panic "unload: strange mode"
556
557 -- -----------------------------------------------------------------------------
558 -- checkStability
559
560 {-
561   Stability tells us which modules definitely do not need to be recompiled.
562   There are two main reasons for having stability:
563   
564    - avoid doing a complete upsweep of the module graph in GHCi when
565      modules near the bottom of the tree have not changed.
566
567    - to tell GHCi when it can load object code: we can only load object code
568      for a module when we also load object code fo  all of the imports of the
569      module.  So we need to know that we will definitely not be recompiling
570      any of these modules, and we can use the object code.
571
572   NB. stability is of no importance to BatchCompile at all, only Interactive.
573   (ToDo: what about JustTypecheck?)
574
575   The stability check is as follows.  Both stableObject and
576   stableBCO are used during the upsweep phase later.
577
578   -------------------
579   stable m = stableObject m || stableBCO m
580
581   stableObject m = 
582         all stableObject (imports m)
583         && old linkable does not exist, or is == on-disk .o
584         && date(on-disk .o) > date(.hs)
585
586   stableBCO m =
587         all stable (imports m)
588         && date(BCO) > date(.hs)
589   -------------------    
590
591   These properties embody the following ideas:
592
593     - if a module is stable:
594         - if it has been compiled in a previous pass (present in HPT)
595           then it does not need to be compiled or re-linked.
596         - if it has not been compiled in a previous pass,
597           then we only need to read its .hi file from disk and
598           link it to produce a ModDetails.
599
600     - if a modules is not stable, we will definitely be at least
601       re-linking, and possibly re-compiling it during the upsweep.
602       All non-stable modules can (and should) therefore be unlinked
603       before the upsweep.
604
605     - Note that objects are only considered stable if they only depend
606       on other objects.  We can't link object code against byte code.
607 -}
608
609 checkStability
610         :: HomePackageTable             -- HPT from last compilation
611         -> [SCC ModSummary]             -- current module graph (cyclic)
612         -> [Module]                     -- all home modules
613         -> ([Module],                   -- stableObject
614             [Module])                   -- stableBCO
615
616 checkStability hpt sccs all_home_mods = foldl checkSCC ([],[]) sccs
617   where
618    checkSCC (stable_obj, stable_bco) scc0
619      | stableObjects = (scc_mods ++ stable_obj, stable_bco)
620      | stableBCOs    = (stable_obj, scc_mods ++ stable_bco)
621      | otherwise     = (stable_obj, stable_bco)
622      where
623         scc = flattenSCC scc0
624         scc_mods = map ms_mod scc
625         home_module m   = m `elem` all_home_mods && m `notElem` scc_mods
626
627         scc_allimps = nub (filter home_module (concatMap ms_allimps scc))
628             -- all imports outside the current SCC, but in the home pkg
629         
630         stable_obj_imps = map (`elem` stable_obj) scc_allimps
631         stable_bco_imps = map (`elem` stable_bco) scc_allimps
632
633         stableObjects = 
634            and stable_obj_imps
635            && all object_ok scc
636
637         stableBCOs = 
638            and (zipWith (||) stable_obj_imps stable_bco_imps)
639            && all bco_ok scc
640
641         object_ok ms
642           | Just t <- ms_obj_date ms  =  t >= ms_hs_date ms 
643                                          && same_as_prev t
644           | otherwise = False
645           where
646              same_as_prev t = case lookupModuleEnv hpt (ms_mod ms) of
647                                 Nothing  -> True
648                                 Just hmi  | Just l <- hm_linkable hmi
649                                  -> isObjectLinkable l && t == linkableTime l
650                 -- why '>=' rather than '>' above?  If the filesystem stores
651                 -- times to the nearset second, we may occasionally find that
652                 -- the object & source have the same modification time, 
653                 -- especially if the source was automatically generated
654                 -- and compiled.  Using >= is slightly unsafe, but it matches
655                 -- make's behaviour.
656
657         bco_ok ms
658           = case lookupModuleEnv hpt (ms_mod ms) of
659                 Nothing  -> False
660                 Just hmi  | Just l <- hm_linkable hmi ->
661                         not (isObjectLinkable l) && 
662                         linkableTime l >= ms_hs_date ms
663
664 ms_allimps :: ModSummary -> [Module]
665 ms_allimps ms = ms_srcimps ms ++ ms_imps ms
666
667 -- -----------------------------------------------------------------------------
668 -- Prune the HomePackageTable
669
670 -- Before doing an upsweep, we can throw away:
671 --
672 --   - For non-stable modules:
673 --      - all ModDetails, all linked code
674 --   - all unlinked code that is out of date with respect to
675 --     the source file
676 --
677 -- This is VERY IMPORTANT otherwise we'll end up requiring 2x the
678 -- space at the end of the upsweep, because the topmost ModDetails of the
679 -- old HPT holds on to the entire type environment from the previous
680 -- compilation.
681
682 pruneHomePackageTable
683    :: HomePackageTable
684    -> [ModSummary]
685    -> ([Module],[Module])
686    -> HomePackageTable
687
688 pruneHomePackageTable hpt summ (stable_obj, stable_bco)
689   = mapModuleEnv prune hpt
690   where prune hmi
691           | is_stable modl = hmi'
692           | otherwise      = hmi'{ hm_details = emptyModDetails }
693           where
694            modl = mi_module (hm_iface hmi)
695            hmi' | Just l <- hm_linkable hmi, linkableTime l < ms_hs_date ms
696                 = hmi{ hm_linkable = Nothing }
697                 | otherwise
698                 = hmi
699                 where ms = expectJust "prune" (lookupModuleEnv ms_map modl)
700
701         ms_map = mkModuleEnv [(ms_mod ms, ms) | ms <- summ]
702
703         is_stable m = m `elem` stable_obj || m `elem` stable_bco
704
705 -- -----------------------------------------------------------------------------
706
707 -- Return (names of) all those in modsDone who are part of a cycle
708 -- as defined by theGraph.
709 findPartiallyCompletedCycles :: [Module] -> [SCC ModSummary] -> [Module]
710 findPartiallyCompletedCycles modsDone theGraph
711    = chew theGraph
712      where
713         chew [] = []
714         chew ((AcyclicSCC v):rest) = chew rest    -- acyclic?  not interesting.
715         chew ((CyclicSCC vs):rest)
716            = let names_in_this_cycle = nub (map ms_mod vs)
717                  mods_in_this_cycle  
718                     = nub ([done | done <- modsDone, 
719                                    done `elem` names_in_this_cycle])
720                  chewed_rest = chew rest
721              in 
722              if   notNull mods_in_this_cycle
723                   && length mods_in_this_cycle < length names_in_this_cycle
724              then mods_in_this_cycle ++ chewed_rest
725              else chewed_rest
726
727 -- -----------------------------------------------------------------------------
728 -- The upsweep
729
730 -- This is where we compile each module in the module graph, in a pass
731 -- from the bottom to the top of the graph.
732
733 -- There better had not be any cyclic groups here -- we check for them.
734
735 upsweep
736     :: HscEnv                   -- Includes initially-empty HPT
737     -> HomePackageTable         -- HPT from last time round (pruned)
738     -> ([Module],[Module])      -- stable modules (see checkStability)
739     -> IO ()                    -- How to clean up unwanted tmp files
740     -> [SCC ModSummary]         -- Mods to do (the worklist)
741     -> IO (SuccessFlag,
742            HscEnv,              -- With an updated HPT
743            [ModSummary])        -- Mods which succeeded
744
745 upsweep hsc_env old_hpt stable_mods cleanup
746      []
747    = return (Succeeded, hsc_env, [])
748
749 upsweep hsc_env old_hpt stable_mods cleanup
750      (CyclicSCC ms:_)
751    = do hPutStrLn stderr (showSDoc (cyclicModuleErr ms))
752         return (Failed, hsc_env, [])
753
754 upsweep hsc_env old_hpt stable_mods cleanup
755      (AcyclicSCC mod:mods)
756    = do -- putStrLn ("UPSWEEP_MOD: hpt = " ++ 
757         --           show (map (moduleUserString.moduleName.mi_module.hm_iface) 
758         --                     (moduleEnvElts (hsc_HPT hsc_env)))
759
760         mb_mod_info <- upsweep_mod hsc_env old_hpt stable_mods mod 
761
762         cleanup         -- Remove unwanted tmp files between compilations
763
764         case mb_mod_info of
765             Nothing -> return (Failed, hsc_env, [])
766             Just mod_info -> do 
767                 { let this_mod = ms_mod mod
768
769                         -- Add new info to hsc_env
770                       hpt1     = extendModuleEnv (hsc_HPT hsc_env) 
771                                         this_mod mod_info
772                       hsc_env1 = hsc_env { hsc_HPT = hpt1 }
773
774                         -- Space-saving: delete the old HPT entry
775                         -- for mod BUT if mod is a hs-boot
776                         -- node, don't delete it.  For the
777                         -- interface, the HPT entry is probaby for the
778                         -- main Haskell source file.  Deleting it
779                         -- would force .. (what?? --SDM)
780                       old_hpt1 | isBootSummary mod = old_hpt
781                                | otherwise = delModuleEnv old_hpt this_mod
782
783                 ; (restOK, hsc_env2, modOKs) 
784                         <- upsweep hsc_env1 old_hpt1 stable_mods cleanup mods
785                 ; return (restOK, hsc_env2, mod:modOKs)
786                 }
787
788
789 -- Compile a single module.  Always produce a Linkable for it if 
790 -- successful.  If no compilation happened, return the old Linkable.
791 upsweep_mod :: HscEnv
792             -> HomePackageTable
793             -> ([Module],[Module])
794             -> ModSummary
795             -> IO (Maybe HomeModInfo)   -- Nothing => Failed
796
797 upsweep_mod hsc_env old_hpt (stable_obj, stable_bco) summary
798    = do 
799         let 
800             this_mod    = ms_mod summary
801             mb_obj_date = ms_obj_date summary
802             obj_fn      = ml_obj_file (ms_location summary)
803             hs_date     = ms_hs_date summary
804
805             compile_it :: Maybe Linkable -> IO (Maybe HomeModInfo)
806             compile_it  = upsweep_compile hsc_env old_hpt this_mod summary
807
808         case ghcMode (hsc_dflags hsc_env) of
809             BatchCompile ->
810                 case () of
811                    -- Batch-compilating is easy: just check whether we have
812                    -- an up-to-date object file.  If we do, then the compiler
813                    -- needs to do a recompilation check.
814                    _ | Just obj_date <- mb_obj_date, obj_date >= hs_date -> do
815                            linkable <- 
816                                 findObjectLinkable this_mod obj_fn obj_date
817                            compile_it (Just linkable)
818
819                      | otherwise ->
820                            compile_it Nothing
821
822             interactive ->
823                 case () of
824                     _ | is_stable_obj, isJust old_hmi ->
825                            return old_hmi
826                         -- object is stable, and we have an entry in the
827                         -- old HPT: nothing to do
828
829                       | is_stable_obj, isNothing old_hmi -> do
830                            linkable <-
831                                 findObjectLinkable this_mod obj_fn 
832                                         (expectJust "upseep1" mb_obj_date)
833                            compile_it (Just linkable)
834                         -- object is stable, but we need to load the interface
835                         -- off disk to make a HMI.
836
837                       | is_stable_bco -> 
838                            ASSERT(isJust old_hmi) -- must be in the old_hpt
839                            return old_hmi
840                         -- BCO is stable: nothing to do
841
842                       | Just hmi <- old_hmi,
843                         Just l <- hm_linkable hmi, not (isObjectLinkable l),
844                         linkableTime l >= ms_hs_date summary ->
845                            compile_it (Just l)
846                         -- we have an old BCO that is up to date with respect
847                         -- to the source: do a recompilation check as normal.
848
849                       | otherwise ->
850                           compile_it Nothing
851                         -- no existing code at all: we must recompile.
852                    where
853                     is_stable_obj = this_mod `elem` stable_obj
854                     is_stable_bco = this_mod `elem` stable_bco
855
856                     old_hmi = lookupModuleEnv old_hpt this_mod
857
858 -- Run hsc to compile a module
859 upsweep_compile hsc_env old_hpt this_mod summary mb_old_linkable = do
860   let
861         -- The old interface is ok if it's in the old HPT 
862         --      a) we're compiling a source file, and the old HPT
863         --      entry is for a source file
864         --      b) we're compiling a hs-boot file
865         -- Case (b) allows an hs-boot file to get the interface of its
866         -- real source file on the second iteration of the compilation
867         -- manager, but that does no harm.  Otherwise the hs-boot file
868         -- will always be recompiled
869
870         mb_old_iface 
871                 = case lookupModuleEnv old_hpt this_mod of
872                      Nothing                              -> Nothing
873                      Just hm_info | isBootSummary summary -> Just iface
874                                   | not (mi_boot iface)   -> Just iface
875                                   | otherwise             -> Nothing
876                                    where 
877                                      iface = hm_iface hm_info
878
879   compresult <- compile hsc_env summary mb_old_linkable mb_old_iface
880
881   case compresult of
882         -- Compilation failed.  Compile may still have updated the PCS, tho.
883         CompErrs -> return Nothing
884
885         -- Compilation "succeeded", and may or may not have returned a new
886         -- linkable (depending on whether compilation was actually performed
887         -- or not).
888         CompOK new_details new_iface new_linkable
889               -> do let new_info = HomeModInfo { hm_iface = new_iface,
890                                                  hm_details = new_details,
891                                                  hm_linkable = new_linkable }
892                     return (Just new_info)
893
894
895 -- Filter modules in the HPT
896 retainInTopLevelEnvs :: [Module] -> HomePackageTable -> HomePackageTable
897 retainInTopLevelEnvs keep_these hpt
898    = mkModuleEnv [ (mod, expectJust "retain" mb_mod_info)
899                  | mod <- keep_these
900                  , let mb_mod_info = lookupModuleEnv hpt mod
901                  , isJust mb_mod_info ]
902
903 -- ---------------------------------------------------------------------------
904 -- Topological sort of the module graph
905
906 topSortModuleGraph
907           :: Bool               -- Drop hi-boot nodes? (see below)
908           -> [ModSummary]
909           -> Maybe Module
910           -> [SCC ModSummary]
911 -- Calculate SCCs of the module graph, possibly dropping the hi-boot nodes
912 --
913 -- Drop hi-boot nodes (first boolean arg)? 
914 --
915 --   False:     treat the hi-boot summaries as nodes of the graph,
916 --              so the graph must be acyclic
917 --
918 --   True:      eliminate the hi-boot nodes, and instead pretend
919 --              the a source-import of Foo is an import of Foo
920 --              The resulting graph has no hi-boot nodes, but can by cyclic
921
922 topSortModuleGraph drop_hs_boot_nodes summaries Nothing
923   = stronglyConnComp (fst (moduleGraphNodes drop_hs_boot_nodes summaries))
924 topSortModuleGraph drop_hs_boot_nodes summaries (Just mod)
925   = stronglyConnComp (map vertex_fn (reachable graph root))
926   where 
927         -- restrict the graph to just those modules reachable from
928         -- the specified module.  We do this by building a graph with
929         -- the full set of nodes, and determining the reachable set from
930         -- the specified node.
931         (nodes, lookup_key) = moduleGraphNodes drop_hs_boot_nodes summaries
932         (graph, vertex_fn, key_fn) = graphFromEdges' nodes
933         root 
934           | Just key <- lookup_key HsSrcFile mod, Just v <- key_fn key = v
935           | otherwise  = throwDyn (ProgramError "module does not exist")
936
937 moduleGraphNodes :: Bool -> [ModSummary]
938   -> ([(ModSummary, Int, [Int])], HscSource -> Module -> Maybe Int)
939 moduleGraphNodes drop_hs_boot_nodes summaries = (nodes, lookup_key)
940    where
941         -- Drop hs-boot nodes by using HsSrcFile as the key
942         hs_boot_key | drop_hs_boot_nodes = HsSrcFile
943                     | otherwise          = HsBootFile   
944
945         -- We use integers as the keys for the SCC algorithm
946         nodes :: [(ModSummary, Int, [Int])]     
947         nodes = [(s, expectJust "topSort" (lookup_key (ms_hsc_src s) (ms_mod s)), 
948                      out_edge_keys hs_boot_key (ms_srcimps s) ++
949                      out_edge_keys HsSrcFile   (ms_imps s)    )
950                 | s <- summaries
951                 , not (isBootSummary s && drop_hs_boot_nodes) ]
952                 -- Drop the hi-boot ones if told to do so
953
954         key_map :: NodeMap Int
955         key_map = listToFM ([(ms_mod s, ms_hsc_src s) | s <- summaries]
956                            `zip` [1..])
957
958         lookup_key :: HscSource -> Module -> Maybe Int
959         lookup_key hs_src mod = lookupFM key_map (mod, hs_src)
960
961         out_edge_keys :: HscSource -> [Module] -> [Int]
962         out_edge_keys hi_boot ms = mapCatMaybes (lookup_key hi_boot) ms
963                 -- If we want keep_hi_boot_nodes, then we do lookup_key with
964                 -- the IsBootInterface parameter True; else False
965
966
967 type NodeKey   = (Module, HscSource)      -- The nodes of the graph are 
968 type NodeMap a = FiniteMap NodeKey a      -- keyed by (mod, src_file_type) pairs
969
970 msKey :: ModSummary -> NodeKey
971 msKey (ModSummary { ms_mod = mod, ms_hsc_src = boot }) = (mod,boot)
972
973 emptyNodeMap :: NodeMap a
974 emptyNodeMap = emptyFM
975
976 mkNodeMap :: [ModSummary] -> NodeMap ModSummary
977 mkNodeMap summaries = listToFM [ (msKey s, s) | s <- summaries]
978         
979 nodeMapElts :: NodeMap a -> [a]
980 nodeMapElts = eltsFM
981
982 -- -----------------------------------------------------------------
983 -- The unlinked image
984 -- 
985 -- The compilation manager keeps a list of compiled, but as-yet unlinked
986 -- binaries (byte code or object code).  Even when it links bytecode
987 -- it keeps the unlinked version so it can re-link it later without
988 -- recompiling.
989
990 type UnlinkedImage = [Linkable] -- the unlinked images (should be a set, really)
991
992 findModuleLinkable_maybe :: [Linkable] -> Module -> Maybe Linkable
993 findModuleLinkable_maybe lis mod
994    = case [LM time nm us | LM time nm us <- lis, nm == mod] of
995         []   -> Nothing
996         [li] -> Just li
997         many -> pprPanic "findModuleLinkable" (ppr mod)
998
999 delModuleLinkable :: [Linkable] -> Module -> [Linkable]
1000 delModuleLinkable ls mod = [ l | l@(LM _ nm _) <- ls, nm /= mod ]
1001
1002 -----------------------------------------------------------------------------
1003 -- Downsweep (dependency analysis)
1004
1005 -- Chase downwards from the specified root set, returning summaries
1006 -- for all home modules encountered.  Only follow source-import
1007 -- links.
1008
1009 -- We pass in the previous collection of summaries, which is used as a
1010 -- cache to avoid recalculating a module summary if the source is
1011 -- unchanged.
1012 --
1013 -- The returned list of [ModSummary] nodes has one node for each home-package
1014 -- module, plus one for any hs-boot files.  The imports of these nodes 
1015 -- are all there, including the imports of non-home-package modules.
1016
1017 downsweep :: HscEnv
1018           -> [ModSummary]       -- Old summaries
1019           -> [Module]           -- Ignore dependencies on these; treat them as
1020                                 -- if they were package modules
1021           -> IO [ModSummary]
1022 downsweep hsc_env old_summaries excl_mods
1023    = do rootSummaries <- mapM getRootSummary roots
1024         checkDuplicates rootSummaries
1025         loop (concatMap msDeps rootSummaries) 
1026              (mkNodeMap rootSummaries)
1027      where
1028         roots = hsc_targets hsc_env
1029
1030         old_summary_map :: NodeMap ModSummary
1031         old_summary_map = mkNodeMap old_summaries
1032
1033         getRootSummary :: Target -> IO ModSummary
1034         getRootSummary (Target (TargetFile file) maybe_buf)
1035            = do exists <- doesFileExist file
1036                 if exists then summariseFile hsc_env file maybe_buf else do
1037                 throwDyn (CmdLineError ("can't find file: " ++ file))   
1038         getRootSummary (Target (TargetModule modl) maybe_buf)
1039            = do maybe_summary <- summarise hsc_env emptyNodeMap Nothing False 
1040                                            modl maybe_buf excl_mods
1041                 case maybe_summary of
1042                    Nothing -> packageModErr modl
1043                    Just s  -> return s
1044
1045         -- In a root module, the filename is allowed to diverge from the module
1046         -- name, so we have to check that there aren't multiple root files
1047         -- defining the same module (otherwise the duplicates will be silently
1048         -- ignored, leading to confusing behaviour).
1049         checkDuplicates :: [ModSummary] -> IO ()
1050         checkDuplicates summaries = mapM_ check summaries
1051           where check summ = 
1052                   case dups of
1053                         []     -> return ()
1054                         [_one] -> return ()
1055                         many   -> multiRootsErr modl many
1056                    where modl = ms_mod summ
1057                          dups = 
1058                            [ expectJust "checkDup" (ml_hs_file (ms_location summ'))
1059                            | summ' <- summaries, ms_mod summ' == modl ]
1060
1061         loop :: [(FilePath,Module,IsBootInterface)]
1062                         -- Work list: process these modules
1063              -> NodeMap ModSummary
1064                         -- Visited set
1065              -> IO [ModSummary]
1066                         -- The result includes the worklist, except
1067                         -- for those mentioned in the visited set
1068         loop [] done      = return (nodeMapElts done)
1069         loop ((cur_path, wanted_mod, is_boot) : ss) done 
1070           | key `elemFM` done = loop ss done
1071           | otherwise         = do { mb_s <- summarise hsc_env old_summary_map 
1072                                                  (Just cur_path) is_boot 
1073                                                  wanted_mod Nothing excl_mods
1074                                    ; case mb_s of
1075                                         Nothing -> loop ss done
1076                                         Just s  -> loop (msDeps s ++ ss) 
1077                                                         (addToFM done key s) }
1078           where
1079             key = (wanted_mod, if is_boot then HsBootFile else HsSrcFile)
1080
1081 msDeps :: ModSummary -> [(FilePath,             -- Importing module
1082                           Module,               -- Imported module
1083                           IsBootInterface)]      -- {-# SOURCE #-} import or not
1084 -- (msDeps s) returns the dependencies of the ModSummary s.
1085 -- A wrinkle is that for a {-# SOURCE #-} import we return
1086 --      *both* the hs-boot file
1087 --      *and* the source file
1088 -- as "dependencies".  That ensures that the list of all relevant
1089 -- modules always contains B.hs if it contains B.hs-boot.
1090 -- Remember, this pass isn't doing the topological sort.  It's
1091 -- just gathering the list of all relevant ModSummaries
1092 msDeps s =  concat [ [(f, m, True), (f,m,False)] | m <- ms_srcimps s] 
1093          ++ [(f,m,False) | m <- ms_imps    s] 
1094         where
1095           f = msHsFilePath s    -- Keep the importing module for error reporting
1096
1097
1098 -----------------------------------------------------------------------------
1099 -- Summarising modules
1100
1101 -- We have two types of summarisation:
1102 --
1103 --    * Summarise a file.  This is used for the root module(s) passed to
1104 --      cmLoadModules.  The file is read, and used to determine the root
1105 --      module name.  The module name may differ from the filename.
1106 --
1107 --    * Summarise a module.  We are given a module name, and must provide
1108 --      a summary.  The finder is used to locate the file in which the module
1109 --      resides.
1110
1111 summariseFile :: HscEnv -> FilePath
1112    -> Maybe (StringBuffer,ClockTime)
1113    -> IO ModSummary
1114 -- Used for Haskell source only, I think
1115 -- We know the file name, and we know it exists,
1116 -- but we don't necessarily know the module name (might differ)
1117 summariseFile hsc_env file maybe_buf
1118    = do let dflags = hsc_dflags hsc_env
1119
1120         (dflags', hspp_fn, buf)
1121             <- preprocessFile dflags file maybe_buf
1122
1123         (srcimps,the_imps,mod) <- getImports dflags' buf hspp_fn
1124
1125         -- Make a ModLocation for this file
1126         location <- mkHomeModLocation dflags mod file
1127
1128         -- Tell the Finder cache where it is, so that subsequent calls
1129         -- to findModule will find it, even if it's not on any search path
1130         addHomeModuleToFinder hsc_env mod location
1131
1132         src_timestamp <- case maybe_buf of
1133                            Just (_,t) -> return t
1134                            Nothing    -> getModificationTime file
1135
1136         obj_timestamp <- modificationTimeIfExists (ml_obj_file location)
1137
1138         return (ModSummary { ms_mod = mod, ms_hsc_src = HsSrcFile,
1139                              ms_location = location,
1140                              ms_hspp_file = Just hspp_fn,
1141                              ms_hspp_buf  = Just buf,
1142                              ms_srcimps = srcimps, ms_imps = the_imps,
1143                              ms_hs_date = src_timestamp,
1144                              ms_obj_date = obj_timestamp })
1145
1146 -- Summarise a module, and pick up source and timestamp.
1147 summarise :: HscEnv
1148           -> NodeMap ModSummary -- Map of old summaries
1149           -> Maybe FilePath     -- Importing module (for error messages)
1150           -> IsBootInterface    -- True <=> a {-# SOURCE #-} import
1151           -> Module             -- Imported module to be summarised
1152           -> Maybe (StringBuffer, ClockTime)
1153           -> [Module]           -- Modules to exclude
1154           -> IO (Maybe ModSummary)      -- Its new summary
1155
1156 summarise hsc_env old_summary_map cur_mod is_boot wanted_mod maybe_buf excl_mods
1157   | wanted_mod `elem` excl_mods
1158   = return Nothing
1159
1160   | Just old_summary <- lookupFM old_summary_map (wanted_mod, hsc_src)
1161   = do          -- Find its new timestamp; all the 
1162                 -- ModSummaries in the old map have valid ml_hs_files
1163         let location = ms_location old_summary
1164             src_fn = expectJust "summarise" (ml_hs_file location)
1165
1166                 -- return the cached summary if the source didn't change
1167         src_timestamp <- case maybe_buf of
1168                            Just (_,t) -> return t
1169                            Nothing    -> getModificationTime src_fn
1170
1171         if ms_hs_date old_summary == src_timestamp 
1172            then do -- update the object-file timestamp
1173                   obj_timestamp <- getObjTimestamp location is_boot
1174                   return (Just old_summary{ ms_obj_date = obj_timestamp })
1175            else
1176                 -- source changed: re-summarise
1177                 new_summary location src_fn maybe_buf src_timestamp
1178
1179   | otherwise
1180   = do  found <- findModule hsc_env wanted_mod True {-explicit-}
1181         case found of
1182              Found location pkg 
1183                 | not (isHomePackage pkg) -> return Nothing
1184                         -- Drop external-pkg
1185                 | isJust (ml_hs_file location) -> just_found location
1186                         -- Home package
1187              err -> noModError dflags cur_mod wanted_mod err
1188                         -- Not found
1189   where
1190     dflags = hsc_dflags hsc_env
1191
1192     hsc_src = if is_boot then HsBootFile else HsSrcFile
1193
1194     just_found location = do
1195                 -- Adjust location to point to the hs-boot source file, 
1196                 -- hi file, object file, when is_boot says so
1197         let location' | is_boot   = addBootSuffixLocn location
1198                       | otherwise = location
1199             src_fn = expectJust "summarise2" (ml_hs_file location')
1200
1201                 -- Check that it exists
1202                 -- It might have been deleted since the Finder last found it
1203         maybe_t <- modificationTimeIfExists src_fn
1204         case maybe_t of
1205           Nothing -> noHsFileErr cur_mod src_fn
1206           Just t  -> new_summary location' src_fn Nothing t
1207
1208
1209     new_summary location src_fn maybe_bug src_timestamp
1210       = do
1211         -- Preprocess the source file and get its imports
1212         -- The dflags' contains the OPTIONS pragmas
1213         (dflags', hspp_fn, buf) <- preprocessFile dflags src_fn maybe_buf
1214         (srcimps, the_imps, mod_name) <- getImports dflags' buf hspp_fn
1215
1216         when (mod_name /= wanted_mod) $
1217                 throwDyn (ProgramError 
1218                    (showSDoc (text src_fn
1219                               <>  text ": file name does not match module name"
1220                               <+> quotes (ppr mod_name))))
1221
1222                 -- Find the object timestamp, and return the summary
1223         obj_timestamp <- getObjTimestamp location is_boot
1224
1225         return (Just ( ModSummary { ms_mod       = wanted_mod, 
1226                                     ms_hsc_src   = hsc_src,
1227                                     ms_location  = location,
1228                                     ms_hspp_file = Just hspp_fn,
1229                                     ms_hspp_buf  = Just buf,
1230                                     ms_srcimps   = srcimps,
1231                                     ms_imps      = the_imps,
1232                                     ms_hs_date   = src_timestamp,
1233                                     ms_obj_date  = obj_timestamp }))
1234
1235
1236 getObjTimestamp location is_boot
1237   = if is_boot then return Nothing
1238                else modificationTimeIfExists (ml_obj_file location)
1239
1240
1241 preprocessFile :: DynFlags -> FilePath -> Maybe (StringBuffer,ClockTime)
1242   -> IO (DynFlags, FilePath, StringBuffer)
1243 preprocessFile dflags src_fn Nothing
1244   = do
1245         (dflags', hspp_fn) <- preprocess dflags src_fn
1246         buf <- hGetStringBuffer hspp_fn
1247         return (dflags', hspp_fn, buf)
1248
1249 preprocessFile dflags src_fn (Just (buf, time))
1250   = do
1251         -- case we bypass the preprocessing stage?
1252         let 
1253             local_opts = getOptionsFromStringBuffer buf
1254         --
1255         (dflags', errs) <- parseDynamicFlags dflags local_opts
1256
1257         let
1258             needs_preprocessing
1259                 | Unlit _ <- startPhase src_fn  = True
1260                   -- note: local_opts is only required if there's no Unlit phase
1261                 | dopt Opt_Cpp dflags'          = True
1262                 | dopt Opt_Pp  dflags'          = True
1263                 | otherwise                     = False
1264
1265         when needs_preprocessing $
1266            ghcError (ProgramError "buffer needs preprocesing; interactive check disabled")
1267
1268         return (dflags', "<buffer>", buf)
1269
1270
1271 -- code adapted from the file-based version in DriverUtil
1272 getOptionsFromStringBuffer :: StringBuffer -> [String]
1273 getOptionsFromStringBuffer buffer@(StringBuffer _ len# _) = 
1274   let 
1275         ls = lines (lexemeToString buffer (I# len#))  -- lazy, so it's ok
1276   in
1277   look ls
1278   where
1279         look [] = []
1280         look (l':ls) = do
1281             let l = removeSpaces l'
1282             case () of
1283                 () | null l -> look ls
1284                    | prefixMatch "#" l -> look ls
1285                    | prefixMatch "{-# LINE" l -> look ls   -- -}
1286                    | Just opts <- matchOptions l
1287                         -> opts ++ look ls
1288                    | otherwise -> []
1289
1290 -----------------------------------------------------------------------------
1291 --                      Error messages
1292 -----------------------------------------------------------------------------
1293
1294 noModError :: DynFlags -> Maybe FilePath -> Module -> FindResult -> IO ab
1295 -- ToDo: we don't have a proper line number for this error
1296 noModError dflags cur_mod wanted_mod err
1297   = throwDyn $ ProgramError $ showSDoc $
1298     vcat [cantFindError dflags wanted_mod err,
1299           nest 2 (parens (pp_where cur_mod))]
1300                                 
1301 noHsFileErr cur_mod path
1302   = throwDyn $ CmdLineError $ showSDoc $
1303     vcat [text "Can't find" <+> text path,
1304           nest 2 (parens (pp_where cur_mod))]
1305  
1306 pp_where Nothing  = text "one of the roots of the dependency analysis"
1307 pp_where (Just p) = text "imported from" <+> text p
1308
1309 packageModErr mod
1310   = throwDyn (CmdLineError (showSDoc (text "module" <+>
1311                                    quotes (ppr mod) <+>
1312                                    text "is a package module")))
1313
1314 multiRootsErr mod files
1315   = throwDyn (ProgramError (showSDoc (
1316         text "module" <+> quotes (ppr mod) <+> 
1317         text "is defined in multiple files:" <+>
1318         sep (map text files))))
1319
1320 cyclicModuleErr :: [ModSummary] -> SDoc
1321 cyclicModuleErr ms
1322   = hang (ptext SLIT("Module imports form a cycle for modules:"))
1323        2 (vcat (map show_one ms))
1324   where
1325     show_one ms = sep [ show_mod (ms_hsc_src ms) (ms_mod ms),
1326                         nest 2 $ ptext SLIT("imports:") <+> 
1327                                    (pp_imps HsBootFile (ms_srcimps ms)
1328                                    $$ pp_imps HsSrcFile  (ms_imps ms))]
1329     show_mod hsc_src mod = ppr mod <> text (hscSourceString hsc_src)
1330     pp_imps src mods = fsep (map (show_mod src) mods)
1331
1332
1333 -- | Inform GHC that the working directory has changed.  GHC will flush
1334 -- its cache of module locations, since it may no longer be valid.
1335 -- Note: if you change the working directory, you should also unload
1336 -- the current program (set targets to empty, followed by load).
1337 workingDirectoryChanged :: Session -> IO ()
1338 workingDirectoryChanged s = withSession s $ \hsc_env ->
1339   flushFinderCache (hsc_FC hsc_env)
1340
1341 -- -----------------------------------------------------------------------------
1342 -- inspecting the session
1343
1344 -- | Get the module dependency graph.
1345 getModuleGraph :: Session -> IO ModuleGraph -- ToDo: DiGraph ModSummary
1346 getModuleGraph s = withSession s (return . hsc_mod_graph)
1347
1348 isLoaded :: Session -> Module -> IO Bool
1349 isLoaded s m = withSession s $ \hsc_env ->
1350   return $! isJust (lookupModuleEnv (hsc_HPT hsc_env) m)
1351
1352 getBindings :: Session -> IO [TyThing]
1353 getBindings s = withSession s (return . nameEnvElts . ic_type_env . hsc_IC)
1354
1355 getPrintUnqual :: Session -> IO PrintUnqualified
1356 getPrintUnqual s = withSession s (return . icPrintUnqual . hsc_IC)
1357
1358 #if 0
1359 getModuleInfo :: Session -> Module -> IO ModuleInfo
1360
1361 data ObjectCode
1362   = ByteCode
1363   | BinaryCode FilePath
1364
1365 data ModuleInfo = ModuleInfo {
1366   lm_modulename :: Module,
1367   lm_summary    :: ModSummary,
1368   lm_interface  :: ModIface,
1369   lm_tc_code    :: Maybe TypecheckedCode,
1370   lm_rn_code    :: Maybe RenamedCode,
1371   lm_obj        :: Maybe ObjectCode
1372   }
1373
1374 type TypecheckedCode = HsTypecheckedGroup
1375 type RenamedCode     = [HsGroup Name]
1376
1377 -- ToDo: typechecks abstract syntax or renamed abstract syntax.  Issues:
1378 --   - typechecked syntax includes extra dictionary translation and
1379 --     AbsBinds which need to be translated back into something closer to
1380 --     the original source.
1381 --   - renamed syntax currently doesn't exist in a single blob, since
1382 --     renaming and typechecking are interleaved at splice points.  We'd
1383 --     need a restriction that there are no splices in the source module.
1384
1385 -- ToDo:
1386 --   - Data and Typeable instances for HsSyn.
1387
1388 -- ToDo:
1389 --   - things that aren't in the output of the renamer:
1390 --     - the export list
1391 --     - the imports
1392
1393 -- ToDo:
1394 --   - things that aren't in the output of the typechecker right now:
1395 --     - the export list
1396 --     - the imports
1397 --     - type signatures
1398 --     - type/data/newtype declarations
1399 --     - class declarations
1400 --     - instances
1401 --   - extra things in the typechecker's output:
1402 --     - default methods are turned into top-level decls.
1403 --     - dictionary bindings
1404
1405 -- ToDo: check for small transformations that happen to the syntax in
1406 -- the typechecker (eg. -e ==> negate e, perhaps for fromIntegral)
1407
1408 -- ToDo: maybe use TH syntax instead of IfaceSyn?  There's already a way
1409 -- to get from TyCons, Ids etc. to TH syntax (reify).
1410
1411 -- :browse will use either lm_toplev or inspect lm_interface, depending
1412 -- on whether the module is interpreted or not.
1413
1414 -- various abstract syntax types (perhaps IfaceBlah)
1415 data Type = ...
1416 data Kind = ...
1417
1418 -- This is for reconstructing refactored source code
1419 -- Calls the lexer repeatedly.
1420 -- ToDo: add comment tokens to token stream
1421 getTokenStream :: Session -> Module -> IO [Located Token]
1422 #endif
1423
1424 -- -----------------------------------------------------------------------------
1425 -- Interactive evaluation
1426
1427 #ifdef GHCI
1428
1429 -- | Set the interactive evaluation context.
1430 --
1431 -- Setting the context doesn't throw away any bindings; the bindings
1432 -- we've built up in the InteractiveContext simply move to the new
1433 -- module.  They always shadow anything in scope in the current context.
1434 setContext :: Session
1435            -> [Module]  -- entire top level scope of these modules
1436            -> [Module]  -- exports only of these modules
1437            -> IO ()
1438 setContext (Session ref) toplevs exports = do 
1439   hsc_env <- readIORef ref
1440   let old_ic  = hsc_IC     hsc_env
1441       hpt     = hsc_HPT    hsc_env
1442
1443   mapM_ (checkModuleExists hsc_env hpt) exports
1444   export_env  <- mkExportEnv hsc_env exports
1445   toplev_envs <- mapM (mkTopLevEnv hpt) toplevs
1446   let all_env = foldr plusGlobalRdrEnv export_env toplev_envs
1447   writeIORef ref hsc_env{ hsc_IC = old_ic { ic_toplev_scope = toplevs,
1448                                             ic_exports      = exports,
1449                                             ic_rn_gbl_env   = all_env } }
1450
1451 checkModuleExists :: HscEnv -> HomePackageTable -> Module -> IO ()
1452 checkModuleExists hsc_env hpt mod = 
1453   case lookupModuleEnv hpt mod of
1454     Just mod_info -> return ()
1455     _not_a_home_module -> do
1456           res <- findPackageModule hsc_env mod True
1457           case res of
1458             Found _ _ -> return  ()
1459             err -> let msg = cantFindError (hsc_dflags hsc_env) mod err in
1460                    throwDyn (CmdLineError (showSDoc msg))
1461
1462 mkTopLevEnv :: HomePackageTable -> Module -> IO GlobalRdrEnv
1463 mkTopLevEnv hpt modl
1464  = case lookupModuleEnv hpt modl of
1465       Nothing ->        
1466          throwDyn (ProgramError ("mkTopLevEnv: not a home module " 
1467                         ++ showSDoc (pprModule modl)))
1468       Just details ->
1469          case mi_globals (hm_iface details) of
1470                 Nothing  -> 
1471                    throwDyn (ProgramError ("mkTopLevEnv: not interpreted " 
1472                                                 ++ showSDoc (pprModule modl)))
1473                 Just env -> return env
1474
1475 -- | Get the interactive evaluation context, consisting of a pair of the
1476 -- set of modules from which we take the full top-level scope, and the set
1477 -- of modules from which we take just the exports respectively.
1478 getContext :: Session -> IO ([Module],[Module])
1479 getContext s = withSession s (\HscEnv{ hsc_IC=ic } ->
1480                                 return (ic_toplev_scope ic, ic_exports ic))
1481
1482 -- | Returns 'True' if the specified module is interpreted, and hence has
1483 -- its full top-level scope available.
1484 moduleIsInterpreted :: Session -> Module -> IO Bool
1485 moduleIsInterpreted s modl = withSession s $ \h ->
1486  case lookupModuleEnv (hsc_HPT h) modl of
1487       Just details       -> return (isJust (mi_globals (hm_iface details)))
1488       _not_a_home_module -> return False
1489
1490 -- | Looks up an identifier in the current interactive context (for :info)
1491 getInfo :: Session -> String -> IO [GetInfoResult]
1492 getInfo s id = withSession s $ \hsc_env -> hscGetInfo hsc_env id
1493
1494 -- -----------------------------------------------------------------------------
1495 -- Getting the type of an expression
1496
1497 -- | Get the type of an expression
1498 exprType :: Session -> String -> IO (Maybe Type)
1499 exprType s expr = withSession s $ \hsc_env -> do
1500    maybe_stuff <- hscTcExpr hsc_env expr
1501    case maybe_stuff of
1502         Nothing -> return Nothing
1503         Just ty -> return (Just tidy_ty)
1504              where 
1505                 tidy_ty = tidyType emptyTidyEnv ty
1506                 dflags  = hsc_dflags hsc_env
1507
1508 -- -----------------------------------------------------------------------------
1509 -- Getting the kind of a type
1510
1511 -- | Get the kind of a  type
1512 typeKind  :: Session -> String -> IO (Maybe Kind)
1513 typeKind s str = withSession s $ \hsc_env -> do
1514    maybe_stuff <- hscKcType hsc_env str
1515    case maybe_stuff of
1516         Nothing -> return Nothing
1517         Just kind -> return (Just kind)
1518
1519 -----------------------------------------------------------------------------
1520 -- lookupName: returns the TyThing for a Name in the interactive context.
1521 -- ToDo: should look it up in the full environment
1522
1523 lookupName :: Session -> Name -> IO (Maybe TyThing)
1524 lookupName s name = withSession s $ \hsc_env -> do
1525   return $! lookupNameEnv (ic_type_env (hsc_IC hsc_env)) name
1526
1527 -----------------------------------------------------------------------------
1528 -- cmCompileExpr: compile an expression and deliver an HValue
1529
1530 compileExpr :: Session -> String -> IO (Maybe HValue)
1531 compileExpr s expr = withSession s $ \hsc_env -> do
1532   maybe_stuff <- hscStmt hsc_env ("let __cmCompileExpr = "++expr)
1533   case maybe_stuff of
1534         Nothing -> return Nothing
1535         Just (new_ic, names, hval) -> do
1536                         -- Run it!
1537                 hvals <- (unsafeCoerce# hval) :: IO [HValue]
1538
1539                 case (names,hvals) of
1540                   ([n],[hv]) -> return (Just hv)
1541                   _          -> panic "compileExpr"
1542
1543 -- -----------------------------------------------------------------------------
1544 -- running a statement interactively
1545
1546 data RunResult
1547   = RunOk [Name]                -- ^ names bound by this evaluation
1548   | RunFailed                   -- ^ statement failed compilation
1549   | RunException Exception      -- ^ statement raised an exception
1550
1551 -- | Run a statement in the current interactive context.  Statemenet
1552 -- may bind multple values.
1553 runStmt :: Session -> String -> IO RunResult
1554 runStmt (Session ref) expr
1555    = do 
1556         hsc_env <- readIORef ref
1557
1558         -- Turn off -fwarn-unused-bindings when running a statement, to hide
1559         -- warnings about the implicit bindings we introduce.
1560         let dflags'  = dopt_unset (hsc_dflags hsc_env) Opt_WarnUnusedBinds
1561             hsc_env' = hsc_env{ hsc_dflags = dflags' }
1562
1563         maybe_stuff <- hscStmt hsc_env' expr
1564
1565         case maybe_stuff of
1566            Nothing -> return RunFailed
1567            Just (new_hsc_env, names, hval) -> do
1568
1569                 let thing_to_run = unsafeCoerce# hval :: IO [HValue]
1570                 either_hvals <- sandboxIO thing_to_run
1571
1572                 case either_hvals of
1573                     Left e -> do
1574                         -- on error, keep the *old* interactive context,
1575                         -- so that 'it' is not bound to something
1576                         -- that doesn't exist.
1577                         return (RunException e)
1578
1579                     Right hvals -> do
1580                         -- Get the newly bound things, and bind them.  
1581                         -- Don't need to delete any shadowed bindings;
1582                         -- the new ones override the old ones. 
1583                         extendLinkEnv (zip names hvals)
1584                         
1585                         writeIORef ref new_hsc_env
1586                         return (RunOk names)
1587
1588
1589 -- We run the statement in a "sandbox" to protect the rest of the
1590 -- system from anything the expression might do.  For now, this
1591 -- consists of just wrapping it in an exception handler, but see below
1592 -- for another version.
1593
1594 sandboxIO :: IO a -> IO (Either Exception a)
1595 sandboxIO thing = Exception.try thing
1596
1597 {-
1598 -- This version of sandboxIO runs the expression in a completely new
1599 -- RTS main thread.  It is disabled for now because ^C exceptions
1600 -- won't be delivered to the new thread, instead they'll be delivered
1601 -- to the (blocked) GHCi main thread.
1602
1603 -- SLPJ: when re-enabling this, reflect a wrong-stat error as an exception
1604
1605 sandboxIO :: IO a -> IO (Either Int (Either Exception a))
1606 sandboxIO thing = do
1607   st_thing <- newStablePtr (Exception.try thing)
1608   alloca $ \ p_st_result -> do
1609     stat <- rts_evalStableIO st_thing p_st_result
1610     freeStablePtr st_thing
1611     if stat == 1
1612         then do st_result <- peek p_st_result
1613                 result <- deRefStablePtr st_result
1614                 freeStablePtr st_result
1615                 return (Right result)
1616         else do
1617                 return (Left (fromIntegral stat))
1618
1619 foreign import "rts_evalStableIO"  {- safe -}
1620   rts_evalStableIO :: StablePtr (IO a) -> Ptr (StablePtr a) -> IO CInt
1621   -- more informative than the C type!
1622 -}
1623
1624 -- ---------------------------------------------------------------------------
1625 -- cmBrowseModule: get all the TyThings defined in a module
1626
1627 browseModule :: Session -> Module -> Bool -> IO [IfaceDecl]
1628 browseModule s modl exports_only = withSession s $ \hsc_env -> do
1629   mb_decls <- getModuleContents hsc_env modl exports_only
1630   case mb_decls of
1631         Nothing -> return []            -- An error of some kind
1632         Just ds -> return ds
1633
1634
1635 -----------------------------------------------------------------------------
1636 -- show a module and it's source/object filenames
1637
1638 showModule :: Session -> ModSummary -> IO String
1639 showModule s mod_summary = withSession s $ \hsc_env -> do
1640   case lookupModuleEnv (hsc_HPT hsc_env) (ms_mod mod_summary) of
1641         Nothing       -> panic "missing linkable"
1642         Just mod_info -> return (showModMsg obj_linkable mod_summary)
1643                       where
1644                          obj_linkable = isObjectLinkable (fromJust (hm_linkable mod_info))
1645
1646 #endif /* GHCI */