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