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