Complete the changes for #1205
[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         newSession,
15
16         -- * Flags and settings
17         DynFlags(..), DynFlag(..), Severity(..), HscTarget(..), dopt,
18         GhcMode(..), GhcLink(..), defaultObjectTarget,
19         parseDynamicFlags,
20         getSessionDynFlags,
21         setSessionDynFlags,
22         parseStaticFlags,
23
24         -- * Targets
25         Target(..), TargetId(..), Phase,
26         setTargets,
27         getTargets,
28         addTarget,
29         removeTarget,
30         guessTarget,
31         
32         -- * Extending the program scope 
33         extendGlobalRdrScope,  -- :: Session -> [GlobalRdrElt] -> IO ()
34         setGlobalRdrScope,     -- :: Session -> [GlobalRdrElt] -> IO ()
35         extendGlobalTypeScope, -- :: Session -> [Id] -> IO ()
36         setGlobalTypeScope,    -- :: Session -> [Id] -> IO ()
37
38         -- * Loading\/compiling the program
39         depanal,
40         load, LoadHowMuch(..), SuccessFlag(..), -- also does depanal
41         workingDirectoryChanged,
42         checkModule, checkAndLoadModule, CheckedModule(..),
43         TypecheckedSource, ParsedSource, RenamedSource,
44         compileToCore, compileToCoreModule, compileToCoreSimplified,
45         compileCoreToObj,
46
47         -- * Parsing Haddock comments
48         parseHaddockComment,
49
50         -- * Inspecting the module structure of the program
51         ModuleGraph, ModSummary(..), ms_mod_name, ModLocation(..),
52         getModuleGraph,
53         isLoaded,
54         topSortModuleGraph,
55
56         -- * Inspecting modules
57         ModuleInfo,
58         getModuleInfo,
59         modInfoTyThings,
60         modInfoTopLevelScope,
61         modInfoExports,
62         modInfoInstances,
63         modInfoIsExportedName,
64         modInfoLookupName,
65         lookupGlobalName,
66         mkPrintUnqualifiedForModule,
67
68         -- * Printing
69         PrintUnqualified, alwaysQualify,
70
71         -- * Interactive evaluation
72         getBindings, getPrintUnqual,
73         findModule,
74 #ifdef GHCI
75         setContext, getContext, 
76         getNamesInScope,
77         getRdrNamesInScope,
78         getGRE,
79         moduleIsInterpreted,
80         getInfo,
81         exprType,
82         typeKind,
83         parseName,
84         RunResult(..),  
85         runStmt, SingleStep(..),
86         resume,
87         Resume(resumeStmt, resumeThreadId, resumeBreakInfo, resumeSpan,
88                resumeHistory, resumeHistoryIx),
89         History(historyBreakInfo, historyEnclosingDecl), 
90         GHC.getHistorySpan, getHistoryModule,
91         getResumeContext,
92         abandon, abandonAll,
93         InteractiveEval.back,
94         InteractiveEval.forward,
95         showModule,
96         isModuleInterpreted,
97         InteractiveEval.compileExpr, HValue, dynCompileExpr,
98         lookupName,
99         GHC.obtainTerm, GHC.obtainTerm1, GHC.obtainTermB, reconstructType,
100         modInfoModBreaks,
101         ModBreaks(..), BreakIndex,
102         BreakInfo(breakInfo_number, breakInfo_module),
103         BreakArray, setBreakOn, setBreakOff, getBreak,
104 #endif
105
106         -- * Abstract syntax elements
107
108         -- ** Packages
109         PackageId,
110
111         -- ** Modules
112         Module, mkModule, pprModule, moduleName, modulePackageId,
113         ModuleName, mkModuleName, moduleNameString,
114
115         -- ** Names
116         Name, 
117         isExternalName, nameModule, pprParenSymName, nameSrcSpan,
118         NamedThing(..),
119         RdrName(Qual,Unqual),
120         
121         -- ** Identifiers
122         Id, idType,
123         isImplicitId, isDeadBinder,
124         isExportedId, isLocalId, isGlobalId,
125         isRecordSelector,
126         isPrimOpId, isFCallId, isClassOpId_maybe,
127         isDataConWorkId, idDataCon,
128         isBottomingId, isDictonaryId,
129         recordSelectorFieldLabel,
130
131         -- ** Type constructors
132         TyCon, 
133         tyConTyVars, tyConDataCons, tyConArity,
134         isClassTyCon, isSynTyCon, isNewTyCon, isPrimTyCon, isFunTyCon,
135         isOpenTyCon,
136         synTyConDefn, synTyConType, synTyConResKind,
137
138         -- ** Type variables
139         TyVar,
140         alphaTyVars,
141
142         -- ** Data constructors
143         DataCon,
144         dataConSig, dataConType, dataConTyCon, dataConFieldLabels,
145         dataConIsInfix, isVanillaDataCon,
146         dataConStrictMarks,  
147         StrictnessMark(..), isMarkedStrict,
148
149         -- ** Classes
150         Class, 
151         classMethods, classSCTheta, classTvsFds,
152         pprFundeps,
153
154         -- ** Instances
155         Instance, 
156         instanceDFunId, pprInstance, pprInstanceHdr,
157
158         -- ** Types and Kinds
159         Type, splitForAllTys, funResultTy, 
160         pprParendType, pprTypeApp, 
161         Kind,
162         PredType,
163         ThetaType, pprThetaArrow,
164
165         -- ** Entities
166         TyThing(..), 
167
168         -- ** Syntax
169         module HsSyn, -- ToDo: remove extraneous bits
170
171         -- ** Fixities
172         FixityDirection(..), 
173         defaultFixity, maxPrecedence, 
174         negateFixity,
175         compareFixity,
176
177         -- ** Source locations
178         SrcLoc, pprDefnLoc,
179         mkSrcLoc, isGoodSrcLoc, noSrcLoc,
180         srcLocFile, srcLocLine, srcLocCol,
181         SrcSpan,
182         mkSrcSpan, srcLocSpan, isGoodSrcSpan, noSrcSpan,
183         srcSpanStart, srcSpanEnd,
184         srcSpanFile, 
185         srcSpanStartLine, srcSpanEndLine, 
186         srcSpanStartCol, srcSpanEndCol,
187
188         -- * Exceptions
189         GhcException(..), showGhcException,
190
191         -- * Miscellaneous
192         sessionHscEnv,
193         cyclicModuleErr,
194   ) where
195
196 {-
197  ToDo:
198
199   * inline bits of HscMain here to simplify layering: hscTcExpr, hscStmt.
200   * what StaticFlags should we expose, if any?
201 -}
202
203 #include "HsVersions.h"
204
205 #ifdef GHCI
206 import qualified Linker
207 import Linker           ( HValue )
208 import ByteCodeInstr
209 import BreakArray
210 import NameSet
211 import InteractiveEval
212 import TcRnDriver
213 #endif
214
215 import TcIface
216 import TcRnTypes        hiding (LIE)
217 import TcRnMonad        ( initIfaceCheck )
218 import Packages
219 import NameSet
220 import RdrName
221 import qualified HsSyn -- hack as we want to reexport the whole module
222 import HsSyn hiding ((<.>))
223 import Type             hiding (typeKind)
224 import TcType           hiding (typeKind)
225 import Id
226 import Var              hiding (setIdType)
227 import TysPrim          ( alphaTyVars )
228 import TyCon
229 import Class
230 import FunDeps
231 import DataCon
232 import Name             hiding ( varName )
233 import OccName          ( parenSymOcc )
234 import InstEnv          ( Instance, instanceDFunId, pprInstance, pprInstanceHdr,
235                           emptyInstEnv )
236 import FamInstEnv       ( emptyFamInstEnv )
237 import SrcLoc
238 import CoreSyn
239 import TidyPgm
240 import DriverPipeline
241 import DriverPhases     ( HscSource(..), Phase(..), isHaskellSrcFilename, startPhase )
242 import HeaderInfo
243 import Finder
244 import HscMain
245 import HscTypes
246 import DynFlags
247 import StaticFlags
248 import SysTools     ( initSysTools, cleanTempFiles, cleanTempFilesExcept,
249                       cleanTempDirs )
250 import Module
251 import LazyUniqFM
252 import UniqSet
253 import Unique
254 import FiniteMap
255 import Panic
256 import Digraph
257 import Bag              ( unitBag, listToBag )
258 import ErrUtils
259 import Util
260 import StringBuffer     ( StringBuffer, hGetStringBuffer )
261 import Outputable
262 import BasicTypes
263 import Maybes           ( expectJust, mapCatMaybes )
264 import HaddockParse
265 import HaddockLex       ( tokenise )
266 import FastString
267
268 import Control.Concurrent
269 import System.Directory ( getModificationTime, doesFileExist,
270                           getCurrentDirectory )
271 import Data.Maybe
272 import Data.List
273 import qualified Data.List as List
274 import Control.Monad
275 import System.Exit      ( exitWith, ExitCode(..) )
276 import System.Time      ( ClockTime, getClockTime )
277 import Control.Exception as Exception hiding (handle)
278 import Data.IORef
279 import System.FilePath
280 import System.IO
281 import System.IO.Error  ( try, isDoesNotExistError )
282 import Prelude hiding (init)
283
284
285 -- -----------------------------------------------------------------------------
286 -- Exception handlers
287
288 -- | Install some default exception handlers and run the inner computation.
289 -- Unless you want to handle exceptions yourself, you should wrap this around
290 -- the top level of your program.  The default handlers output the error
291 -- message(s) to stderr and exit cleanly.
292 defaultErrorHandler :: DynFlags -> IO a -> IO a
293 defaultErrorHandler dflags inner = 
294   -- top-level exception handler: any unrecognised exception is a compiler bug.
295   handle (\exception -> do
296            hFlush stdout
297            case exception of
298                 -- an IO exception probably isn't our fault, so don't panic
299                 IOException _ ->
300                   fatalErrorMsg dflags (text (show exception))
301                 AsyncException StackOverflow ->
302                   fatalErrorMsg dflags (text "stack overflow: use +RTS -K<size> to increase it")
303                 _other ->
304                   fatalErrorMsg dflags (text (show (Panic (show exception))))
305            exitWith (ExitFailure 1)
306          ) $
307
308   -- program errors: messages with locations attached.  Sometimes it is
309   -- convenient to just throw these as exceptions.
310   handleDyn (\dyn -> do printBagOfErrors dflags (unitBag dyn)
311                         exitWith (ExitFailure 1)) $
312
313   -- error messages propagated as exceptions
314   handleDyn (\dyn -> do
315                 hFlush stdout
316                 case dyn of
317                      PhaseFailed _ code -> exitWith code
318                      Interrupted -> exitWith (ExitFailure 1)
319                      _ -> do fatalErrorMsg dflags (text (show (dyn :: GhcException)))
320                              exitWith (ExitFailure 1)
321             ) $
322   inner
323
324 -- | Install a default cleanup handler to remove temporary files
325 -- deposited by a GHC run.  This is seperate from
326 -- 'defaultErrorHandler', because you might want to override the error
327 -- handling, but still get the ordinary cleanup behaviour.
328 defaultCleanupHandler :: DynFlags -> IO a -> IO a
329 defaultCleanupHandler dflags inner = 
330     -- make sure we clean up after ourselves
331     later (do cleanTempFiles dflags
332               cleanTempDirs dflags
333           )
334           -- exceptions will be blocked while we clean the temporary files,
335           -- so there shouldn't be any difficulty if we receive further
336           -- signals.
337     inner
338
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: explain argument [[mb_top_dir]]
343 newSession :: Maybe FilePath -> IO Session
344 newSession mb_top_dir = do
345   -- catch ^C
346   main_thread <- myThreadId
347   modifyMVar_ interruptTargetThread (return . (main_thread :))
348   installSignalHandlers
349
350   initStaticOpts
351   dflags0 <- initDynFlags defaultDynFlags
352   dflags <- initSysTools mb_top_dir dflags0
353   env <- newHscEnv dflags
354   ref <- newIORef env
355   return (Session ref)
356
357 -- tmp: this breaks the abstraction, but required because DriverMkDepend
358 -- needs to call the Finder.  ToDo: untangle this.
359 sessionHscEnv :: Session -> IO HscEnv
360 sessionHscEnv (Session ref) = readIORef ref
361
362 -- -----------------------------------------------------------------------------
363 -- Flags & settings
364
365 -- | Grabs the DynFlags from the Session
366 getSessionDynFlags :: Session -> IO DynFlags
367 getSessionDynFlags s = withSession s (return . hsc_dflags)
368
369 -- | Updates the DynFlags in a Session.  This also reads
370 -- the package database (unless it has already been read),
371 -- and prepares the compilers knowledge about packages.  It
372 -- can be called again to load new packages: just add new
373 -- package flags to (packageFlags dflags).
374 --
375 -- Returns a list of new packages that may need to be linked in using
376 -- the dynamic linker (see 'linkPackages') as a result of new package
377 -- flags.  If you are not doing linking or doing static linking, you
378 -- can ignore the list of packages returned.
379 --
380 setSessionDynFlags :: Session -> DynFlags -> IO [PackageId]
381 setSessionDynFlags (Session ref) dflags = do
382   hsc_env <- readIORef ref
383   (dflags', preload) <- initPackages dflags
384   writeIORef ref $! hsc_env{ hsc_dflags = dflags' }
385   return preload
386
387 -- | If there is no -o option, guess the name of target executable
388 -- by using top-level source file name as a base.
389 guessOutputFile :: Session -> IO ()
390 guessOutputFile s = modifySession s $ \env ->
391     let dflags = hsc_dflags env
392         mod_graph = hsc_mod_graph env
393         mainModuleSrcPath :: Maybe String
394         mainModuleSrcPath = do
395             let isMain = (== mainModIs dflags) . ms_mod
396             [ms] <- return (filter isMain mod_graph)
397             ml_hs_file (ms_location ms)
398         name = fmap dropExtension mainModuleSrcPath
399
400 #if defined(mingw32_HOST_OS)
401         -- we must add the .exe extention unconditionally here, otherwise
402         -- when name has an extension of its own, the .exe extension will
403         -- not be added by DriverPipeline.exeFileName.  See #2248
404         name_exe = fmap (<.> "exe") name
405 #else
406         name_exe = name
407 #endif
408     in
409     case outputFile dflags of
410         Just _ -> env
411         Nothing -> env { hsc_dflags = dflags { outputFile = name_exe } }
412
413 -- -----------------------------------------------------------------------------
414 -- Targets
415
416 -- ToDo: think about relative vs. absolute file paths. And what
417 -- happens when the current directory changes.
418
419 -- | Sets the targets for this session.  Each target may be a module name
420 -- or a filename.  The targets correspond to the set of root modules for
421 -- the program\/library.  Unloading the current program is achieved by
422 -- setting the current set of targets to be empty, followed by load.
423 setTargets :: Session -> [Target] -> IO ()
424 setTargets s targets = modifySession s (\h -> h{ hsc_targets = targets })
425
426 -- | returns the current set of targets
427 getTargets :: Session -> IO [Target]
428 getTargets s = withSession s (return . hsc_targets)
429
430 -- | Add another target
431 addTarget :: Session -> Target -> IO ()
432 addTarget s target
433   = modifySession s (\h -> h{ hsc_targets = target : hsc_targets h })
434
435 -- | Remove a target
436 removeTarget :: Session -> TargetId -> IO ()
437 removeTarget s target_id
438   = modifySession s (\h -> h{ hsc_targets = filter (hsc_targets h) })
439   where
440    filter targets = [ t | t@(Target id _) <- targets, id /= target_id ]
441
442 -- Attempts to guess what Target a string refers to.  This function implements
443 -- the --make/GHCi command-line syntax for filenames: 
444 --
445 --      - if the string looks like a Haskell source filename, then interpret
446 --        it as such
447 --      - if adding a .hs or .lhs suffix yields the name of an existing file,
448 --        then use that
449 --      - otherwise interpret the string as a module name
450 --
451 guessTarget :: String -> Maybe Phase -> IO Target
452 guessTarget file (Just phase)
453    = return (Target (TargetFile file (Just phase)) Nothing)
454 guessTarget file Nothing
455    | isHaskellSrcFilename file
456    = return (Target (TargetFile file Nothing) Nothing)
457    | looksLikeModuleName file
458    = return (Target (TargetModule (mkModuleName file)) Nothing)
459    | otherwise
460    = do exists <- doesFileExist hs_file
461         if exists
462            then return (Target (TargetFile hs_file Nothing) Nothing)
463            else do
464         exists <- doesFileExist lhs_file
465         if exists
466            then return (Target (TargetFile lhs_file Nothing) Nothing)
467            else do
468         throwDyn (ProgramError (showSDoc $
469                  text "target" <+> quotes (text file) <+> 
470                  text "is not a module name or a source file"))
471      where 
472          hs_file  = file <.> "hs"
473          lhs_file = file <.> "lhs"
474
475 -- -----------------------------------------------------------------------------
476 -- Extending the program scope
477
478 extendGlobalRdrScope :: Session -> [GlobalRdrElt] -> IO ()
479 extendGlobalRdrScope session rdrElts
480     = modifySession session $ \hscEnv ->
481       let global_rdr = hsc_global_rdr_env hscEnv
482       in hscEnv{ hsc_global_rdr_env = foldl extendGlobalRdrEnv global_rdr rdrElts }
483
484 setGlobalRdrScope :: Session -> [GlobalRdrElt] -> IO ()
485 setGlobalRdrScope session rdrElts
486     = modifySession session $ \hscEnv ->
487       hscEnv{ hsc_global_rdr_env = foldl extendGlobalRdrEnv emptyGlobalRdrEnv rdrElts }
488
489 extendGlobalTypeScope :: Session -> [Id] -> IO ()
490 extendGlobalTypeScope session ids
491     = modifySession session $ \hscEnv ->
492       let global_type = hsc_global_type_env hscEnv
493       in hscEnv{ hsc_global_type_env = extendTypeEnvWithIds global_type ids }
494
495 setGlobalTypeScope :: Session -> [Id] -> IO ()
496 setGlobalTypeScope session ids
497     = modifySession session $ \hscEnv ->
498       hscEnv{ hsc_global_type_env = extendTypeEnvWithIds emptyTypeEnv ids }
499
500 -- -----------------------------------------------------------------------------
501 -- Parsing Haddock comments
502
503 parseHaddockComment :: String -> Either String (HsDoc RdrName)
504 parseHaddockComment string = 
505   case parseHaddockParagraphs (tokenise string) of
506     MyLeft x  -> Left x
507     MyRight x -> Right x
508
509 -- -----------------------------------------------------------------------------
510 -- Loading the program
511
512 -- Perform a dependency analysis starting from the current targets
513 -- and update the session with the new module graph.
514 depanal :: Session -> [ModuleName] -> Bool -> IO (Maybe ModuleGraph)
515 depanal (Session ref) excluded_mods allow_dup_roots = do
516   hsc_env <- readIORef ref
517   let
518          dflags  = hsc_dflags hsc_env
519          targets = hsc_targets hsc_env
520          old_graph = hsc_mod_graph hsc_env
521         
522   showPass dflags "Chasing dependencies"
523   debugTraceMsg dflags 2 (hcat [
524              text "Chasing modules from: ",
525              hcat (punctuate comma (map pprTarget targets))])
526
527   r <- downsweep hsc_env old_graph excluded_mods allow_dup_roots
528   case r of
529     Just mod_graph -> writeIORef ref hsc_env{ hsc_mod_graph = mod_graph }
530     _ -> return ()
531   return r
532
533 {-
534 -- | The result of load.
535 data LoadResult
536   = LoadOk      Errors  -- ^ all specified targets were loaded successfully.
537   | LoadFailed  Errors  -- ^ not all modules were loaded.
538
539 type Errors = [String]
540
541 data ErrMsg = ErrMsg { 
542         errMsgSeverity  :: Severity,  -- warning, error, etc.
543         errMsgSpans     :: [SrcSpan],
544         errMsgShortDoc  :: Doc,
545         errMsgExtraInfo :: Doc
546         }
547 -}
548
549 data LoadHowMuch
550    = LoadAllTargets
551    | LoadUpTo ModuleName
552    | LoadDependenciesOf ModuleName
553
554 -- | Try to load the program.  If a Module is supplied, then just
555 -- attempt to load up to this target.  If no Module is supplied,
556 -- then try to load all targets.
557 load :: Session -> LoadHowMuch -> IO SuccessFlag
558 load s how_much
559    = do 
560         -- Dependency analysis first.  Note that this fixes the module graph:
561         -- even if we don't get a fully successful upsweep, the full module
562         -- graph is still retained in the Session.  We can tell which modules
563         -- were successfully loaded by inspecting the Session's HPT.
564         mb_graph <- depanal s [] False
565         case mb_graph of
566            Just mod_graph -> load2 s how_much mod_graph
567            Nothing        -> return Failed
568
569 load2 :: Session -> LoadHowMuch -> [ModSummary] -> IO SuccessFlag
570 load2 s@(Session ref) how_much mod_graph = do
571         guessOutputFile s
572         hsc_env <- readIORef ref
573
574         let hpt1      = hsc_HPT hsc_env
575         let dflags    = hsc_dflags hsc_env
576
577         -- The "bad" boot modules are the ones for which we have
578         -- B.hs-boot in the module graph, but no B.hs
579         -- The downsweep should have ensured this does not happen
580         -- (see msDeps)
581         let all_home_mods = [ms_mod_name s 
582                             | s <- mod_graph, not (isBootSummary s)]
583             bad_boot_mods = [s        | s <- mod_graph, isBootSummary s,
584                                         not (ms_mod_name s `elem` all_home_mods)]
585         ASSERT( null bad_boot_mods ) return ()
586
587         -- check that the module given in HowMuch actually exists, otherwise
588         -- topSortModuleGraph will bomb later.
589         let checkHowMuch (LoadUpTo m)           = checkMod m
590             checkHowMuch (LoadDependenciesOf m) = checkMod m
591             checkHowMuch _ = id
592
593             checkMod m and_then
594                 | m `elem` all_home_mods = and_then
595                 | otherwise = do 
596                         errorMsg dflags (text "no such module:" <+> 
597                                          quotes (ppr m))
598                         return Failed
599
600         checkHowMuch how_much $ do
601
602         -- mg2_with_srcimps drops the hi-boot nodes, returning a 
603         -- graph with cycles.  Among other things, it is used for
604         -- backing out partially complete cycles following a failed
605         -- upsweep, and for removing from hpt all the modules
606         -- not in strict downwards closure, during calls to compile.
607         let mg2_with_srcimps :: [SCC ModSummary]
608             mg2_with_srcimps = topSortModuleGraph True mod_graph Nothing
609
610         -- If we can determine that any of the {-# SOURCE #-} imports
611         -- are definitely unnecessary, then emit a warning.
612         warnUnnecessarySourceImports dflags mg2_with_srcimps
613
614         let
615             -- check the stability property for each module.
616             stable_mods@(stable_obj,stable_bco)
617                 = checkStability hpt1 mg2_with_srcimps all_home_mods
618
619             -- prune bits of the HPT which are definitely redundant now,
620             -- to save space.
621             pruned_hpt = pruneHomePackageTable hpt1 
622                                 (flattenSCCs mg2_with_srcimps)
623                                 stable_mods
624
625         evaluate pruned_hpt
626
627         -- before we unload anything, make sure we don't leave an old
628         -- interactive context around pointing to dead bindings.  Also,
629         -- write the pruned HPT to allow the old HPT to be GC'd.
630         writeIORef ref $! hsc_env{ hsc_IC = emptyInteractiveContext,
631                                    hsc_HPT = pruned_hpt }
632
633         debugTraceMsg dflags 2 (text "Stable obj:" <+> ppr stable_obj $$
634                                 text "Stable BCO:" <+> ppr stable_bco)
635
636         -- Unload any modules which are going to be re-linked this time around.
637         let stable_linkables = [ linkable
638                                | m <- stable_obj++stable_bco,
639                                  Just hmi <- [lookupUFM pruned_hpt m],
640                                  Just linkable <- [hm_linkable hmi] ]
641         unload hsc_env stable_linkables
642
643         -- We could at this point detect cycles which aren't broken by
644         -- a source-import, and complain immediately, but it seems better
645         -- to let upsweep_mods do this, so at least some useful work gets
646         -- done before the upsweep is abandoned.
647         --hPutStrLn stderr "after tsort:\n"
648         --hPutStrLn stderr (showSDoc (vcat (map ppr mg2)))
649
650         -- Now do the upsweep, calling compile for each module in
651         -- turn.  Final result is version 3 of everything.
652
653         -- Topologically sort the module graph, this time including hi-boot
654         -- nodes, and possibly just including the portion of the graph
655         -- reachable from the module specified in the 2nd argument to load.
656         -- This graph should be cycle-free.
657         -- If we're restricting the upsweep to a portion of the graph, we
658         -- also want to retain everything that is still stable.
659         let full_mg :: [SCC ModSummary]
660             full_mg    = topSortModuleGraph False mod_graph Nothing
661
662             maybe_top_mod = case how_much of
663                                 LoadUpTo m           -> Just m
664                                 LoadDependenciesOf m -> Just m
665                                 _                    -> Nothing
666
667             partial_mg0 :: [SCC ModSummary]
668             partial_mg0 = topSortModuleGraph False mod_graph maybe_top_mod
669
670             -- LoadDependenciesOf m: we want the upsweep to stop just
671             -- short of the specified module (unless the specified module
672             -- is stable).
673             partial_mg
674                 | LoadDependenciesOf _mod <- how_much
675                 = ASSERT( case last partial_mg0 of 
676                             AcyclicSCC ms -> ms_mod_name ms == _mod; _ -> False )
677                   List.init partial_mg0
678                 | otherwise
679                 = partial_mg0
680   
681             stable_mg = 
682                 [ AcyclicSCC ms
683                 | AcyclicSCC ms <- full_mg,
684                   ms_mod_name ms `elem` stable_obj++stable_bco,
685                   ms_mod_name ms `notElem` [ ms_mod_name ms' | 
686                                                 AcyclicSCC ms' <- partial_mg ] ]
687
688             mg = stable_mg ++ partial_mg
689
690         -- clean up between compilations
691         let cleanup = cleanTempFilesExcept dflags
692                           (ppFilesFromSummaries (flattenSCCs mg2_with_srcimps))
693
694         debugTraceMsg dflags 2 (hang (text "Ready for upsweep") 
695                                    2 (ppr mg))
696         (upsweep_ok, hsc_env1, modsUpswept)
697            <- upsweep (hsc_env { hsc_HPT = emptyHomePackageTable })
698                            pruned_hpt stable_mods cleanup mg
699
700         -- Make modsDone be the summaries for each home module now
701         -- available; this should equal the domain of hpt3.
702         -- Get in in a roughly top .. bottom order (hence reverse).
703
704         let modsDone = reverse modsUpswept
705
706         -- Try and do linking in some form, depending on whether the
707         -- upsweep was completely or only partially successful.
708
709         if succeeded upsweep_ok
710
711          then 
712            -- Easy; just relink it all.
713            do debugTraceMsg dflags 2 (text "Upsweep completely successful.")
714
715               -- Clean up after ourselves
716               cleanTempFilesExcept dflags (ppFilesFromSummaries modsDone)
717
718               -- Issue a warning for the confusing case where the user
719               -- said '-o foo' but we're not going to do any linking.
720               -- We attempt linking if either (a) one of the modules is
721               -- called Main, or (b) the user said -no-hs-main, indicating
722               -- that main() is going to come from somewhere else.
723               --
724               let ofile = outputFile dflags
725               let no_hs_main = dopt Opt_NoHsMain dflags
726               let 
727                 main_mod = mainModIs dflags
728                 a_root_is_Main = any ((==main_mod).ms_mod) mod_graph
729                 do_linking = a_root_is_Main || no_hs_main
730
731               when (ghcLink dflags == LinkBinary 
732                     && isJust ofile && not do_linking) $
733                 debugTraceMsg dflags 1 $
734                     text ("Warning: output was redirected with -o, " ++
735                           "but no output will be generated\n" ++
736                           "because there is no " ++ 
737                           moduleNameString (moduleName main_mod) ++ " module.")
738
739               -- link everything together
740               linkresult <- link (ghcLink dflags) dflags do_linking (hsc_HPT hsc_env1)
741
742               loadFinish Succeeded linkresult ref hsc_env1
743
744          else 
745            -- Tricky.  We need to back out the effects of compiling any
746            -- half-done cycles, both so as to clean up the top level envs
747            -- and to avoid telling the interactive linker to link them.
748            do debugTraceMsg dflags 2 (text "Upsweep partially successful.")
749
750               let modsDone_names
751                      = map ms_mod modsDone
752               let mods_to_zap_names 
753                      = findPartiallyCompletedCycles modsDone_names 
754                           mg2_with_srcimps
755               let mods_to_keep
756                      = filter ((`notElem` mods_to_zap_names).ms_mod) 
757                           modsDone
758
759               let hpt4 = retainInTopLevelEnvs (map ms_mod_name mods_to_keep) 
760                                               (hsc_HPT hsc_env1)
761
762               -- Clean up after ourselves
763               cleanTempFilesExcept dflags (ppFilesFromSummaries mods_to_keep)
764
765               -- there should be no Nothings where linkables should be, now
766               ASSERT(all (isJust.hm_linkable) 
767                         (eltsUFM (hsc_HPT hsc_env))) do
768         
769               -- Link everything together
770               linkresult <- link (ghcLink dflags) dflags False hpt4
771
772               let hsc_env4 = hsc_env1{ hsc_HPT = hpt4 }
773               loadFinish Failed linkresult ref hsc_env4
774
775 -- Finish up after a load.
776
777 -- If the link failed, unload everything and return.
778 loadFinish :: SuccessFlag -> SuccessFlag -> IORef HscEnv -> HscEnv -> IO SuccessFlag
779 loadFinish _all_ok Failed ref hsc_env
780   = do unload hsc_env []
781        writeIORef ref $! discardProg hsc_env
782        return Failed
783
784 -- Empty the interactive context and set the module context to the topmost
785 -- newly loaded module, or the Prelude if none were loaded.
786 loadFinish all_ok Succeeded ref hsc_env
787   = do writeIORef ref $! hsc_env{ hsc_IC = emptyInteractiveContext }
788        return all_ok
789
790
791 -- Forget the current program, but retain the persistent info in HscEnv
792 discardProg :: HscEnv -> HscEnv
793 discardProg hsc_env
794   = hsc_env { hsc_mod_graph = emptyMG, 
795               hsc_IC = emptyInteractiveContext,
796               hsc_HPT = emptyHomePackageTable }
797
798 -- used to fish out the preprocess output files for the purposes of
799 -- cleaning up.  The preprocessed file *might* be the same as the
800 -- source file, but that doesn't do any harm.
801 ppFilesFromSummaries :: [ModSummary] -> [FilePath]
802 ppFilesFromSummaries summaries = map ms_hspp_file summaries
803
804 -- -----------------------------------------------------------------------------
805 -- Check module
806
807 data CheckedModule = 
808   CheckedModule { parsedSource      :: ParsedSource,
809                   renamedSource     :: Maybe RenamedSource,
810                   typecheckedSource :: Maybe TypecheckedSource,
811                   checkedModuleInfo :: Maybe ModuleInfo,
812                   coreModule        :: Maybe ModGuts
813                 }
814         -- ToDo: improvements that could be made here:
815         --  if the module succeeded renaming but not typechecking,
816         --  we can still get back the GlobalRdrEnv and exports, so
817         --  perhaps the ModuleInfo should be split up into separate
818         --  fields within CheckedModule.
819
820 type ParsedSource      = Located (HsModule RdrName)
821 type RenamedSource     = (HsGroup Name, [LImportDecl Name], Maybe [LIE Name],
822                           Maybe (HsDoc Name), HaddockModInfo Name)
823 type TypecheckedSource = LHsBinds Id
824
825 -- NOTE:
826 --   - things that aren't in the output of the typechecker right now:
827 --     - the export list
828 --     - the imports
829 --     - type signatures
830 --     - type/data/newtype declarations
831 --     - class declarations
832 --     - instances
833 --   - extra things in the typechecker's output:
834 --     - default methods are turned into top-level decls.
835 --     - dictionary bindings
836
837
838 -- | This is the way to get access to parsed and typechecked source code
839 -- for a module.  'checkModule' attempts to typecheck the module.  If
840 -- successful, it returns the abstract syntax for the module.
841 -- If compileToCore is true, it also desugars the module and returns the 
842 -- resulting Core bindings as a component of the CheckedModule.
843 checkModule :: Session -> ModuleName -> Bool -> IO (Maybe CheckedModule)
844 checkModule (Session ref) mod compile_to_core
845  = do
846    hsc_env <- readIORef ref   
847    let mg  = hsc_mod_graph hsc_env
848    case [ ms | ms <- mg, ms_mod_name ms == mod ] of
849         [] -> return Nothing
850         (ms:_) -> checkModule_ ref ms compile_to_core False
851
852 -- | parses and typechecks a module, optionally generates Core, and also
853 -- loads the module into the 'Session' so that modules which depend on
854 -- this one may subsequently be typechecked using 'checkModule' or
855 -- 'checkAndLoadModule'.  If you need to check more than one module,
856 -- you probably want to use 'checkAndLoadModule'.  Constructing the
857 -- interface takes a little work, so it might be slightly slower than
858 -- 'checkModule'.
859 checkAndLoadModule :: Session -> ModSummary -> Bool -> IO (Maybe CheckedModule)
860 checkAndLoadModule (Session ref) ms compile_to_core
861  = checkModule_ ref ms compile_to_core True
862
863 checkModule_ :: IORef HscEnv -> ModSummary -> Bool -> Bool
864              -> IO (Maybe CheckedModule)
865 checkModule_ ref ms compile_to_core load
866  = do
867    let mod = ms_mod_name ms
868    hsc_env0 <- readIORef ref   
869    let hsc_env = hsc_env0{hsc_dflags=ms_hspp_opts ms}
870    mb_parsed <- parseFile hsc_env ms
871    case mb_parsed of
872              Nothing -> return Nothing
873              Just rdr_module -> do
874                mb_typechecked <- typecheckRenameModule hsc_env ms rdr_module
875                case mb_typechecked of
876                  Nothing -> return (Just CheckedModule {
877                                               parsedSource = rdr_module,
878                                               renamedSource = Nothing,
879                                               typecheckedSource = Nothing,
880                                               checkedModuleInfo = Nothing,
881                                               coreModule = Nothing })
882                  Just (tcg, rn_info) -> do
883                    details <- makeSimpleDetails hsc_env tcg
884                    
885                    let tc_binds = tcg_binds tcg
886                    let rdr_env  = tcg_rdr_env tcg
887                    let minf = ModuleInfo {
888                                 minf_type_env  = md_types details,
889                                 minf_exports   = availsToNameSet $
890                                                      md_exports details,
891                                 minf_rdr_env   = Just rdr_env,
892                                 minf_instances = md_insts details
893 #ifdef GHCI
894                                ,minf_modBreaks = emptyModBreaks 
895 #endif
896                               }
897
898                    mb_guts <- if compile_to_core
899                                  then deSugarModule hsc_env ms tcg
900                                  else return Nothing              
901
902                    -- If we are loading this module so that we can typecheck
903                    -- dependent modules, generate an interface and stuff it
904                    -- all in the HomePackageTable.
905                    when load $ do
906                      (iface,_) <- makeSimpleIface hsc_env Nothing tcg details
907                      let mod_info = HomeModInfo {
908                                         hm_iface = iface,
909                                         hm_details = details,
910                                         hm_linkable = Nothing }
911                      let hpt_new = addToUFM (hsc_HPT hsc_env) mod mod_info
912                      writeIORef ref hsc_env0{ hsc_HPT = hpt_new }
913
914                    return (Just (CheckedModule {
915                                         parsedSource = rdr_module,
916                                         renamedSource = rn_info,
917                                         typecheckedSource = Just tc_binds,
918                                         checkedModuleInfo = Just minf,
919                                         coreModule = mb_guts }))
920
921 -- | This is the way to get access to the Core bindings corresponding
922 -- to a module. 'compileToCore' invokes 'checkModule' to parse, typecheck, and
923 -- desugar the module, then returns the resulting Core module (consisting of
924 -- the module name, type declarations, and function declarations) if
925 -- successful.
926 compileToCoreModule :: Session -> FilePath -> IO (Maybe CoreModule)
927 compileToCoreModule = compileCore False
928
929 -- | Like compileToCoreModule, but invokes the simplifier, so
930 -- as to return simplified and tidied Core.
931 compileToCoreSimplified :: Session -> FilePath -> IO (Maybe CoreModule)
932 compileToCoreSimplified = compileCore True
933
934 -- | Provided for backwards-compatibility: compileToCore returns just the Core
935 -- bindings, but for most purposes, you probably want to call
936 -- compileToCoreModule.
937 compileToCore :: Session -> FilePath -> IO (Maybe [CoreBind])
938 compileToCore session fn = do
939    maybeCoreModule <- compileToCoreModule session fn
940    return $ fmap cm_binds maybeCoreModule
941
942 -- | Takes a CoreModule and compiles the bindings therein
943 -- to object code. The first argument is a bool flag indicating
944 -- whether to run the simplifier.
945 -- The resulting .o, .hi, and executable files, if any, are stored in the
946 -- current directory, and named according to the module name.
947 -- Returns True iff compilation succeeded.
948 -- This has only so far been tested with a single self-contained module.
949 compileCoreToObj :: Bool -> Session -> CoreModule -> IO Bool
950 compileCoreToObj simplify session cm@(CoreModule{ cm_module = mName }) = do
951   hscEnv      <- sessionHscEnv session
952   dflags      <- getSessionDynFlags session
953   currentTime <- getClockTime
954   cwd         <- getCurrentDirectory
955   modLocation <- mkHiOnlyModLocation dflags (hiSuf dflags) cwd
956                    ((moduleNameSlashes . moduleName) mName)
957
958   let modSummary = ModSummary { ms_mod = mName,
959          ms_hsc_src = ExtCoreFile,
960          ms_location = modLocation,
961          -- By setting the object file timestamp to Nothing,
962          -- we always force recompilation, which is what we
963          -- want. (Thus it doesn't matter what the timestamp
964          -- for the (nonexistent) source file is.)
965          ms_hs_date = currentTime,
966          ms_obj_date = Nothing,
967          -- Only handling the single-module case for now, so no imports.
968          ms_srcimps = [],
969          ms_imps = [],
970          -- No source file
971          ms_hspp_file = "",
972          ms_hspp_opts = dflags,
973          ms_hspp_buf = Nothing
974       }
975
976   mbHscResult <- evalComp
977      ((if simplify then hscSimplify else return) (mkModGuts cm)
978      >>= hscNormalIface >>= hscWriteIface >>= hscOneShot)
979      (CompState{ compHscEnv=hscEnv,
980                  compModSummary=modSummary,
981                  compOldIface=Nothing})
982   return $ isJust mbHscResult
983
984 -- Makes a "vanilla" ModGuts.
985 mkModGuts :: CoreModule -> ModGuts
986 mkModGuts coreModule = ModGuts {
987   mg_module = cm_module coreModule,
988   mg_boot = False,
989   mg_exports = [],
990   mg_deps = noDependencies,
991   mg_dir_imps = emptyModuleEnv,
992   mg_used_names = emptyNameSet,
993   mg_rdr_env = emptyGlobalRdrEnv,
994   mg_fix_env = emptyFixityEnv,
995   mg_types = emptyTypeEnv,
996   mg_insts = [],
997   mg_fam_insts = [],
998   mg_rules = [],
999   mg_binds = cm_binds coreModule,
1000   mg_foreign = NoStubs,
1001   mg_warns = NoWarnings,
1002   mg_hpc_info = emptyHpcInfo False,
1003   mg_modBreaks = emptyModBreaks,
1004   mg_vect_info = noVectInfo,
1005   mg_inst_env = emptyInstEnv,
1006   mg_fam_inst_env = emptyFamInstEnv
1007 }
1008
1009 compileCore :: Bool -> Session -> FilePath -> IO (Maybe CoreModule)
1010 compileCore simplify session fn = do
1011    -- First, set the target to the desired filename
1012    target <- guessTarget fn Nothing
1013    addTarget session target
1014    load session LoadAllTargets
1015    -- Then find dependencies
1016    maybeModGraph <- depanal session [] True
1017    case maybeModGraph of
1018      Nothing -> return Nothing
1019      Just modGraph -> do
1020        case find ((== fn) . msHsFilePath) modGraph of
1021          Just modSummary -> do 
1022            -- Now we have the module name;
1023            -- parse, typecheck and desugar the module
1024            let mod = ms_mod_name modSummary
1025            maybeCheckedModule <- checkModule session mod True
1026            case maybeCheckedModule of
1027              Nothing -> return Nothing 
1028              Just checkedMod -> (liftM $ fmap gutsToCoreModule) $
1029                                 case (coreModule checkedMod) of
1030                                   Just mg | simplify -> (sessionHscEnv session)
1031                                   -- If simplify is true: simplify (hscSimplify),
1032                                   -- then tidy (tidyProgram).
1033                                    >>= \ hscEnv -> evalComp (hscSimplify mg)
1034                                          (CompState{ compHscEnv=hscEnv,
1035                                                      compModSummary=modSummary,
1036                                                      compOldIface=Nothing})
1037                                           >>= (tidyProgram hscEnv)
1038                                           >>= (return . Just . Left)
1039                                   Just guts -> return $ Just $ Right guts
1040                                   Nothing   -> return Nothing
1041          Nothing -> panic "compileToCoreModule: target FilePath not found in\
1042                            module dependency graph"
1043   where -- two versions, based on whether we simplify (thus run tidyProgram,
1044         -- which returns a (CgGuts, ModDetails) pair, or not (in which case
1045         -- we just have a ModGuts.
1046         gutsToCoreModule :: Either (CgGuts, ModDetails) ModGuts -> CoreModule
1047         gutsToCoreModule (Left (cg, md))  = CoreModule {
1048           cm_module = cg_module cg,    cm_types = md_types md,
1049           cm_imports = cg_dir_imps cg, cm_binds = cg_binds cg
1050         }
1051         gutsToCoreModule (Right mg) = CoreModule {
1052           cm_module  = mg_module mg,                   cm_types   = mg_types mg,
1053           cm_imports = moduleEnvKeys (mg_dir_imps mg), cm_binds   = mg_binds mg
1054          }
1055
1056 -- ---------------------------------------------------------------------------
1057 -- Unloading
1058
1059 unload :: HscEnv -> [Linkable] -> IO ()
1060 unload hsc_env stable_linkables -- Unload everthing *except* 'stable_linkables'
1061   = case ghcLink (hsc_dflags hsc_env) of
1062 #ifdef GHCI
1063         LinkInMemory -> Linker.unload (hsc_dflags hsc_env) stable_linkables
1064 #else
1065         LinkInMemory -> panic "unload: no interpreter"
1066                                 -- urgh.  avoid warnings:
1067                                 hsc_env stable_linkables
1068 #endif
1069         _other -> return ()
1070
1071 -- -----------------------------------------------------------------------------
1072 -- checkStability
1073
1074 {-
1075   Stability tells us which modules definitely do not need to be recompiled.
1076   There are two main reasons for having stability:
1077   
1078    - avoid doing a complete upsweep of the module graph in GHCi when
1079      modules near the bottom of the tree have not changed.
1080
1081    - to tell GHCi when it can load object code: we can only load object code
1082      for a module when we also load object code fo  all of the imports of the
1083      module.  So we need to know that we will definitely not be recompiling
1084      any of these modules, and we can use the object code.
1085
1086   The stability check is as follows.  Both stableObject and
1087   stableBCO are used during the upsweep phase later.
1088
1089   -------------------
1090   stable m = stableObject m || stableBCO m
1091
1092   stableObject m = 
1093         all stableObject (imports m)
1094         && old linkable does not exist, or is == on-disk .o
1095         && date(on-disk .o) > date(.hs)
1096
1097   stableBCO m =
1098         all stable (imports m)
1099         && date(BCO) > date(.hs)
1100   -------------------    
1101
1102   These properties embody the following ideas:
1103
1104     - if a module is stable, then:
1105         - if it has been compiled in a previous pass (present in HPT)
1106           then it does not need to be compiled or re-linked.
1107         - if it has not been compiled in a previous pass,
1108           then we only need to read its .hi file from disk and
1109           link it to produce a ModDetails.
1110
1111     - if a modules is not stable, we will definitely be at least
1112       re-linking, and possibly re-compiling it during the upsweep.
1113       All non-stable modules can (and should) therefore be unlinked
1114       before the upsweep.
1115
1116     - Note that objects are only considered stable if they only depend
1117       on other objects.  We can't link object code against byte code.
1118 -}
1119
1120 checkStability
1121         :: HomePackageTable             -- HPT from last compilation
1122         -> [SCC ModSummary]             -- current module graph (cyclic)
1123         -> [ModuleName]                 -- all home modules
1124         -> ([ModuleName],               -- stableObject
1125             [ModuleName])               -- stableBCO
1126
1127 checkStability hpt sccs all_home_mods = foldl checkSCC ([],[]) sccs
1128   where
1129    checkSCC (stable_obj, stable_bco) scc0
1130      | stableObjects = (scc_mods ++ stable_obj, stable_bco)
1131      | stableBCOs    = (stable_obj, scc_mods ++ stable_bco)
1132      | otherwise     = (stable_obj, stable_bco)
1133      where
1134         scc = flattenSCC scc0
1135         scc_mods = map ms_mod_name scc
1136         home_module m   = m `elem` all_home_mods && m `notElem` scc_mods
1137
1138         scc_allimps = nub (filter home_module (concatMap ms_allimps scc))
1139             -- all imports outside the current SCC, but in the home pkg
1140         
1141         stable_obj_imps = map (`elem` stable_obj) scc_allimps
1142         stable_bco_imps = map (`elem` stable_bco) scc_allimps
1143
1144         stableObjects = 
1145            and stable_obj_imps
1146            && all object_ok scc
1147
1148         stableBCOs = 
1149            and (zipWith (||) stable_obj_imps stable_bco_imps)
1150            && all bco_ok scc
1151
1152         object_ok ms
1153           | Just t <- ms_obj_date ms  =  t >= ms_hs_date ms 
1154                                          && same_as_prev t
1155           | otherwise = False
1156           where
1157              same_as_prev t = case lookupUFM hpt (ms_mod_name ms) of
1158                                 Just hmi  | Just l <- hm_linkable hmi
1159                                  -> isObjectLinkable l && t == linkableTime l
1160                                 _other  -> True
1161                 -- why '>=' rather than '>' above?  If the filesystem stores
1162                 -- times to the nearset second, we may occasionally find that
1163                 -- the object & source have the same modification time, 
1164                 -- especially if the source was automatically generated
1165                 -- and compiled.  Using >= is slightly unsafe, but it matches
1166                 -- make's behaviour.
1167
1168         bco_ok ms
1169           = case lookupUFM hpt (ms_mod_name ms) of
1170                 Just hmi  | Just l <- hm_linkable hmi ->
1171                         not (isObjectLinkable l) && 
1172                         linkableTime l >= ms_hs_date ms
1173                 _other  -> False
1174
1175 ms_allimps :: ModSummary -> [ModuleName]
1176 ms_allimps ms = map unLoc (ms_srcimps ms ++ ms_imps ms)
1177
1178 -- -----------------------------------------------------------------------------
1179 -- Prune the HomePackageTable
1180
1181 -- Before doing an upsweep, we can throw away:
1182 --
1183 --   - For non-stable modules:
1184 --      - all ModDetails, all linked code
1185 --   - all unlinked code that is out of date with respect to
1186 --     the source file
1187 --
1188 -- This is VERY IMPORTANT otherwise we'll end up requiring 2x the
1189 -- space at the end of the upsweep, because the topmost ModDetails of the
1190 -- old HPT holds on to the entire type environment from the previous
1191 -- compilation.
1192
1193 pruneHomePackageTable
1194    :: HomePackageTable
1195    -> [ModSummary]
1196    -> ([ModuleName],[ModuleName])
1197    -> HomePackageTable
1198
1199 pruneHomePackageTable hpt summ (stable_obj, stable_bco)
1200   = mapUFM prune hpt
1201   where prune hmi
1202           | is_stable modl = hmi'
1203           | otherwise      = hmi'{ hm_details = emptyModDetails }
1204           where
1205            modl = moduleName (mi_module (hm_iface hmi))
1206            hmi' | Just l <- hm_linkable hmi, linkableTime l < ms_hs_date ms
1207                 = hmi{ hm_linkable = Nothing }
1208                 | otherwise
1209                 = hmi
1210                 where ms = expectJust "prune" (lookupUFM ms_map modl)
1211
1212         ms_map = listToUFM [(ms_mod_name ms, ms) | ms <- summ]
1213
1214         is_stable m = m `elem` stable_obj || m `elem` stable_bco
1215
1216 -- -----------------------------------------------------------------------------
1217
1218 -- Return (names of) all those in modsDone who are part of a cycle
1219 -- as defined by theGraph.
1220 findPartiallyCompletedCycles :: [Module] -> [SCC ModSummary] -> [Module]
1221 findPartiallyCompletedCycles modsDone theGraph
1222    = chew theGraph
1223      where
1224         chew [] = []
1225         chew ((AcyclicSCC _):rest) = chew rest    -- acyclic?  not interesting.
1226         chew ((CyclicSCC vs):rest)
1227            = let names_in_this_cycle = nub (map ms_mod vs)
1228                  mods_in_this_cycle  
1229                     = nub ([done | done <- modsDone, 
1230                                    done `elem` names_in_this_cycle])
1231                  chewed_rest = chew rest
1232              in 
1233              if   notNull mods_in_this_cycle
1234                   && length mods_in_this_cycle < length names_in_this_cycle
1235              then mods_in_this_cycle ++ chewed_rest
1236              else chewed_rest
1237
1238 -- -----------------------------------------------------------------------------
1239 -- The upsweep
1240
1241 -- This is where we compile each module in the module graph, in a pass
1242 -- from the bottom to the top of the graph.
1243
1244 -- There better had not be any cyclic groups here -- we check for them.
1245
1246 upsweep
1247     :: HscEnv                   -- Includes initially-empty HPT
1248     -> HomePackageTable         -- HPT from last time round (pruned)
1249     -> ([ModuleName],[ModuleName]) -- stable modules (see checkStability)
1250     -> IO ()                    -- How to clean up unwanted tmp files
1251     -> [SCC ModSummary]         -- Mods to do (the worklist)
1252     -> IO (SuccessFlag,
1253            HscEnv,              -- With an updated HPT
1254            [ModSummary])        -- Mods which succeeded
1255
1256 upsweep hsc_env old_hpt stable_mods cleanup sccs = do
1257    (res, hsc_env, done) <- upsweep' hsc_env old_hpt [] sccs 1 (length sccs)
1258    return (res, hsc_env, reverse done)
1259  where
1260
1261   upsweep' hsc_env _old_hpt done
1262      [] _ _
1263    = return (Succeeded, hsc_env, done)
1264
1265   upsweep' hsc_env _old_hpt done
1266      (CyclicSCC ms:_) _ _
1267    = do fatalErrorMsg (hsc_dflags hsc_env) (cyclicModuleErr ms)
1268         return (Failed, hsc_env, done)
1269
1270   upsweep' hsc_env old_hpt done
1271      (AcyclicSCC mod:mods) mod_index nmods
1272    = do -- putStrLn ("UPSWEEP_MOD: hpt = " ++ 
1273         --           show (map (moduleUserString.moduleName.mi_module.hm_iface) 
1274         --                     (moduleEnvElts (hsc_HPT hsc_env)))
1275
1276         mb_mod_info <- upsweep_mod hsc_env old_hpt stable_mods mod 
1277                        mod_index nmods
1278
1279         cleanup         -- Remove unwanted tmp files between compilations
1280
1281         case mb_mod_info of
1282             Nothing -> return (Failed, hsc_env, done)
1283             Just mod_info -> do 
1284                 let this_mod = ms_mod_name mod
1285
1286                         -- Add new info to hsc_env
1287                     hpt1     = addToUFM (hsc_HPT hsc_env) this_mod mod_info
1288                     hsc_env1 = hsc_env { hsc_HPT = hpt1 }
1289
1290                         -- Space-saving: delete the old HPT entry
1291                         -- for mod BUT if mod is a hs-boot
1292                         -- node, don't delete it.  For the
1293                         -- interface, the HPT entry is probaby for the
1294                         -- main Haskell source file.  Deleting it
1295                         -- would force the real module to be recompiled
1296                         -- every time.
1297                     old_hpt1 | isBootSummary mod = old_hpt
1298                              | otherwise = delFromUFM old_hpt this_mod
1299
1300                     done' = mod:done
1301
1302                         -- fixup our HomePackageTable after we've finished compiling
1303                         -- a mutually-recursive loop.  See reTypecheckLoop, below.
1304                 hsc_env2 <- reTypecheckLoop hsc_env1 mod done'
1305
1306                 upsweep' hsc_env2 old_hpt1 done' mods (mod_index+1) nmods
1307
1308
1309 -- Compile a single module.  Always produce a Linkable for it if 
1310 -- successful.  If no compilation happened, return the old Linkable.
1311 upsweep_mod :: HscEnv
1312             -> HomePackageTable
1313             -> ([ModuleName],[ModuleName])
1314             -> ModSummary
1315             -> Int  -- index of module
1316             -> Int  -- total number of modules
1317             -> IO (Maybe HomeModInfo)   -- Nothing => Failed
1318
1319 upsweep_mod hsc_env old_hpt (stable_obj, stable_bco) summary mod_index nmods
1320    =    let 
1321             this_mod_name = ms_mod_name summary
1322             this_mod    = ms_mod summary
1323             mb_obj_date = ms_obj_date summary
1324             obj_fn      = ml_obj_file (ms_location summary)
1325             hs_date     = ms_hs_date summary
1326
1327             is_stable_obj = this_mod_name `elem` stable_obj
1328             is_stable_bco = this_mod_name `elem` stable_bco
1329
1330             old_hmi = lookupUFM old_hpt this_mod_name
1331
1332             -- We're using the dflags for this module now, obtained by
1333             -- applying any options in its LANGUAGE & OPTIONS_GHC pragmas.
1334             dflags = ms_hspp_opts summary
1335             prevailing_target = hscTarget (hsc_dflags hsc_env)
1336             local_target      = hscTarget dflags
1337
1338             -- If OPTIONS_GHC contains -fasm or -fvia-C, be careful that
1339             -- we don't do anything dodgy: these should only work to change
1340             -- from -fvia-C to -fasm and vice-versa, otherwise we could 
1341             -- end up trying to link object code to byte code.
1342             target = if prevailing_target /= local_target
1343                         && (not (isObjectTarget prevailing_target)
1344                             || not (isObjectTarget local_target))
1345                         then prevailing_target
1346                         else local_target 
1347
1348             -- store the corrected hscTarget into the summary
1349             summary' = summary{ ms_hspp_opts = dflags { hscTarget = target } }
1350
1351             -- The old interface is ok if
1352             --  a) we're compiling a source file, and the old HPT
1353             --     entry is for a source file
1354             --  b) we're compiling a hs-boot file
1355             -- Case (b) allows an hs-boot file to get the interface of its
1356             -- real source file on the second iteration of the compilation
1357             -- manager, but that does no harm.  Otherwise the hs-boot file
1358             -- will always be recompiled
1359             
1360             mb_old_iface 
1361                 = case old_hmi of
1362                      Nothing                              -> Nothing
1363                      Just hm_info | isBootSummary summary -> Just iface
1364                                   | not (mi_boot iface)   -> Just iface
1365                                   | otherwise             -> Nothing
1366                                    where 
1367                                      iface = hm_iface hm_info
1368
1369             compile_it :: Maybe Linkable -> IO (Maybe HomeModInfo)
1370             compile_it  = compile hsc_env summary' mod_index nmods mb_old_iface
1371
1372             compile_it_discard_iface 
1373                         = compile hsc_env summary' mod_index nmods Nothing
1374
1375         in
1376         case target of
1377
1378             _any
1379                 -- Regardless of whether we're generating object code or
1380                 -- byte code, we can always use an existing object file
1381                 -- if it is *stable* (see checkStability).
1382                 | is_stable_obj, isJust old_hmi ->
1383                         return old_hmi
1384                         -- object is stable, and we have an entry in the
1385                         -- old HPT: nothing to do
1386
1387                 | is_stable_obj, isNothing old_hmi -> do
1388                         linkable <- findObjectLinkable this_mod obj_fn 
1389                                         (expectJust "upseep1" mb_obj_date)
1390                         compile_it (Just linkable)
1391                         -- object is stable, but we need to load the interface
1392                         -- off disk to make a HMI.
1393
1394             HscInterpreted
1395                 | is_stable_bco -> 
1396                         ASSERT(isJust old_hmi) -- must be in the old_hpt
1397                         return old_hmi
1398                         -- BCO is stable: nothing to do
1399
1400                 | Just hmi <- old_hmi,
1401                   Just l <- hm_linkable hmi, not (isObjectLinkable l),
1402                   linkableTime l >= ms_hs_date summary ->
1403                         compile_it (Just l)
1404                         -- we have an old BCO that is up to date with respect
1405                         -- to the source: do a recompilation check as normal.
1406
1407                 | otherwise -> 
1408                         compile_it Nothing
1409                         -- no existing code at all: we must recompile.
1410
1411               -- When generating object code, if there's an up-to-date
1412               -- object file on the disk, then we can use it.
1413               -- However, if the object file is new (compared to any
1414               -- linkable we had from a previous compilation), then we
1415               -- must discard any in-memory interface, because this
1416               -- means the user has compiled the source file
1417               -- separately and generated a new interface, that we must
1418               -- read from the disk.
1419               --
1420             obj | isObjectTarget obj,
1421                   Just obj_date <- mb_obj_date, obj_date >= hs_date -> do
1422                      case old_hmi of
1423                         Just hmi 
1424                           | Just l <- hm_linkable hmi,
1425                             isObjectLinkable l && linkableTime l == obj_date
1426                             -> compile_it (Just l)
1427                         _otherwise -> do
1428                           linkable <- findObjectLinkable this_mod obj_fn obj_date
1429                           compile_it_discard_iface (Just linkable)
1430
1431             _otherwise ->
1432                   compile_it Nothing
1433
1434
1435
1436 -- Filter modules in the HPT
1437 retainInTopLevelEnvs :: [ModuleName] -> HomePackageTable -> HomePackageTable
1438 retainInTopLevelEnvs keep_these hpt
1439    = listToUFM   [ (mod, expectJust "retain" mb_mod_info)
1440                  | mod <- keep_these
1441                  , let mb_mod_info = lookupUFM hpt mod
1442                  , isJust mb_mod_info ]
1443
1444 -- ---------------------------------------------------------------------------
1445 -- Typecheck module loops
1446
1447 {-
1448 See bug #930.  This code fixes a long-standing bug in --make.  The
1449 problem is that when compiling the modules *inside* a loop, a data
1450 type that is only defined at the top of the loop looks opaque; but
1451 after the loop is done, the structure of the data type becomes
1452 apparent.
1453
1454 The difficulty is then that two different bits of code have
1455 different notions of what the data type looks like.
1456
1457 The idea is that after we compile a module which also has an .hs-boot
1458 file, we re-generate the ModDetails for each of the modules that
1459 depends on the .hs-boot file, so that everyone points to the proper
1460 TyCons, Ids etc. defined by the real module, not the boot module.
1461 Fortunately re-generating a ModDetails from a ModIface is easy: the
1462 function TcIface.typecheckIface does exactly that.
1463
1464 Picking the modules to re-typecheck is slightly tricky.  Starting from
1465 the module graph consisting of the modules that have already been
1466 compiled, we reverse the edges (so they point from the imported module
1467 to the importing module), and depth-first-search from the .hs-boot
1468 node.  This gives us all the modules that depend transitively on the
1469 .hs-boot module, and those are exactly the modules that we need to
1470 re-typecheck.
1471
1472 Following this fix, GHC can compile itself with --make -O2.
1473 -}
1474
1475 reTypecheckLoop :: HscEnv -> ModSummary -> ModuleGraph -> IO HscEnv
1476 reTypecheckLoop hsc_env ms graph
1477   | not (isBootSummary ms) && 
1478     any (\m -> ms_mod m == this_mod && isBootSummary m) graph
1479   = do
1480         let mss = reachableBackwards (ms_mod_name ms) graph
1481             non_boot = filter (not.isBootSummary) mss
1482         debugTraceMsg (hsc_dflags hsc_env) 2 $
1483            text "Re-typechecking loop: " <> ppr (map ms_mod_name non_boot)
1484         typecheckLoop hsc_env (map ms_mod_name non_boot)
1485   | otherwise
1486   = return hsc_env
1487  where
1488   this_mod = ms_mod ms
1489
1490 typecheckLoop :: HscEnv -> [ModuleName] -> IO HscEnv
1491 typecheckLoop hsc_env mods = do
1492   new_hpt <-
1493     fixIO $ \new_hpt -> do
1494       let new_hsc_env = hsc_env{ hsc_HPT = new_hpt }
1495       mds <- initIfaceCheck new_hsc_env $ 
1496                 mapM (typecheckIface . hm_iface) hmis
1497       let new_hpt = addListToUFM old_hpt 
1498                         (zip mods [ hmi{ hm_details = details }
1499                                   | (hmi,details) <- zip hmis mds ])
1500       return new_hpt
1501   return hsc_env{ hsc_HPT = new_hpt }
1502   where
1503     old_hpt = hsc_HPT hsc_env
1504     hmis    = map (expectJust "typecheckLoop" . lookupUFM old_hpt) mods
1505
1506 reachableBackwards :: ModuleName -> [ModSummary] -> [ModSummary]
1507 reachableBackwards mod summaries
1508   = [ ms | (ms,_,_) <- map vertex_fn nodes_we_want ]
1509   where          
1510         -- all the nodes reachable by traversing the edges backwards
1511         -- from the root node:
1512         nodes_we_want = reachable (transposeG graph) root
1513
1514         -- the rest just sets up the graph:
1515         (nodes, lookup_key) = moduleGraphNodes False summaries
1516         (graph, vertex_fn, key_fn) = graphFromEdges' nodes
1517         root 
1518           | Just key <- lookup_key HsBootFile mod, Just v <- key_fn key = v
1519           | otherwise = panic "reachableBackwards"
1520
1521 -- ---------------------------------------------------------------------------
1522 -- Topological sort of the module graph
1523
1524 topSortModuleGraph
1525           :: Bool               -- Drop hi-boot nodes? (see below)
1526           -> [ModSummary]
1527           -> Maybe ModuleName
1528           -> [SCC ModSummary]
1529 -- Calculate SCCs of the module graph, possibly dropping the hi-boot nodes
1530 -- The resulting list of strongly-connected-components is in topologically
1531 -- sorted order, starting with the module(s) at the bottom of the
1532 -- dependency graph (ie compile them first) and ending with the ones at
1533 -- the top.
1534 --
1535 -- Drop hi-boot nodes (first boolean arg)? 
1536 --
1537 --   False:     treat the hi-boot summaries as nodes of the graph,
1538 --              so the graph must be acyclic
1539 --
1540 --   True:      eliminate the hi-boot nodes, and instead pretend
1541 --              the a source-import of Foo is an import of Foo
1542 --              The resulting graph has no hi-boot nodes, but can by cyclic
1543
1544 topSortModuleGraph drop_hs_boot_nodes summaries Nothing
1545   = stronglyConnComp (fst (moduleGraphNodes drop_hs_boot_nodes summaries))
1546 topSortModuleGraph drop_hs_boot_nodes summaries (Just mod)
1547   = stronglyConnComp (map vertex_fn (reachable graph root))
1548   where 
1549         -- restrict the graph to just those modules reachable from
1550         -- the specified module.  We do this by building a graph with
1551         -- the full set of nodes, and determining the reachable set from
1552         -- the specified node.
1553         (nodes, lookup_key) = moduleGraphNodes drop_hs_boot_nodes summaries
1554         (graph, vertex_fn, key_fn) = graphFromEdges' nodes
1555         root 
1556           | Just key <- lookup_key HsSrcFile mod, Just v <- key_fn key = v
1557           | otherwise  = throwDyn (ProgramError "module does not exist")
1558
1559 moduleGraphNodes :: Bool -> [ModSummary]
1560   -> ([(ModSummary, Int, [Int])], HscSource -> ModuleName -> Maybe Int)
1561 moduleGraphNodes drop_hs_boot_nodes summaries = (nodes, lookup_key)
1562    where
1563         -- Drop hs-boot nodes by using HsSrcFile as the key
1564         hs_boot_key | drop_hs_boot_nodes = HsSrcFile
1565                     | otherwise          = HsBootFile   
1566
1567         -- We use integers as the keys for the SCC algorithm
1568         nodes :: [(ModSummary, Int, [Int])]     
1569         nodes = [(s, expectJust "topSort" $ 
1570                         lookup_key (ms_hsc_src s) (ms_mod_name s),
1571                      out_edge_keys hs_boot_key (map unLoc (ms_srcimps s)) ++
1572                      out_edge_keys HsSrcFile   (map unLoc (ms_imps s)) ++
1573                      (-- see [boot-edges] below
1574                       if drop_hs_boot_nodes || ms_hsc_src s == HsBootFile 
1575                         then [] 
1576                         else case lookup_key HsBootFile (ms_mod_name s) of
1577                                 Nothing -> []
1578                                 Just k  -> [k])
1579                  )
1580                 | s <- summaries
1581                 , not (isBootSummary s && drop_hs_boot_nodes) ]
1582                 -- Drop the hi-boot ones if told to do so
1583
1584         -- [boot-edges] if this is a .hs and there is an equivalent
1585         -- .hs-boot, add a link from the former to the latter.  This
1586         -- has the effect of detecting bogus cases where the .hs-boot
1587         -- depends on the .hs, by introducing a cycle.  Additionally,
1588         -- it ensures that we will always process the .hs-boot before
1589         -- the .hs, and so the HomePackageTable will always have the
1590         -- most up to date information.
1591
1592         key_map :: NodeMap Int
1593         key_map = listToFM ([(moduleName (ms_mod s), ms_hsc_src s)
1594                             | s <- summaries]
1595                            `zip` [1..])
1596
1597         lookup_key :: HscSource -> ModuleName -> Maybe Int
1598         lookup_key hs_src mod = lookupFM key_map (mod, hs_src)
1599
1600         out_edge_keys :: HscSource -> [ModuleName] -> [Int]
1601         out_edge_keys hi_boot ms = mapCatMaybes (lookup_key hi_boot) ms
1602                 -- If we want keep_hi_boot_nodes, then we do lookup_key with
1603                 -- the IsBootInterface parameter True; else False
1604
1605
1606 type NodeKey   = (ModuleName, HscSource)  -- The nodes of the graph are 
1607 type NodeMap a = FiniteMap NodeKey a      -- keyed by (mod, src_file_type) pairs
1608
1609 msKey :: ModSummary -> NodeKey
1610 msKey (ModSummary { ms_mod = mod, ms_hsc_src = boot }) = (moduleName mod,boot)
1611
1612 mkNodeMap :: [ModSummary] -> NodeMap ModSummary
1613 mkNodeMap summaries = listToFM [ (msKey s, s) | s <- summaries]
1614         
1615 nodeMapElts :: NodeMap a -> [a]
1616 nodeMapElts = eltsFM
1617
1618 -- If there are {-# SOURCE #-} imports between strongly connected
1619 -- components in the topological sort, then those imports can
1620 -- definitely be replaced by ordinary non-SOURCE imports: if SOURCE
1621 -- were necessary, then the edge would be part of a cycle.
1622 warnUnnecessarySourceImports :: DynFlags -> [SCC ModSummary] -> IO ()
1623 warnUnnecessarySourceImports dflags sccs = 
1624   printBagOfWarnings dflags (listToBag (concat (map (check.flattenSCC) sccs)))
1625   where check ms =
1626            let mods_in_this_cycle = map ms_mod_name ms in
1627            [ warn i | m <- ms, i <- ms_srcimps m,
1628                         unLoc i `notElem`  mods_in_this_cycle ]
1629
1630         warn :: Located ModuleName -> WarnMsg
1631         warn (L loc mod) = 
1632            mkPlainErrMsg loc
1633                 (ptext (sLit "Warning: {-# SOURCE #-} unnecessary in import of ")
1634                  <+> quotes (ppr mod))
1635
1636 -----------------------------------------------------------------------------
1637 -- Downsweep (dependency analysis)
1638
1639 -- Chase downwards from the specified root set, returning summaries
1640 -- for all home modules encountered.  Only follow source-import
1641 -- links.
1642
1643 -- We pass in the previous collection of summaries, which is used as a
1644 -- cache to avoid recalculating a module summary if the source is
1645 -- unchanged.
1646 --
1647 -- The returned list of [ModSummary] nodes has one node for each home-package
1648 -- module, plus one for any hs-boot files.  The imports of these nodes 
1649 -- are all there, including the imports of non-home-package modules.
1650
1651 downsweep :: HscEnv
1652           -> [ModSummary]       -- Old summaries
1653           -> [ModuleName]       -- Ignore dependencies on these; treat
1654                                 -- them as if they were package modules
1655           -> Bool               -- True <=> allow multiple targets to have 
1656                                 --          the same module name; this is 
1657                                 --          very useful for ghc -M
1658           -> IO (Maybe [ModSummary])
1659                 -- The elts of [ModSummary] all have distinct
1660                 -- (Modules, IsBoot) identifiers, unless the Bool is true
1661                 -- in which case there can be repeats
1662 downsweep hsc_env old_summaries excl_mods allow_dup_roots
1663    = -- catch error messages and return them
1664      handleDyn (\err_msg -> printBagOfErrors (hsc_dflags hsc_env) (unitBag err_msg) >> return Nothing) $ do
1665        rootSummaries <- mapM getRootSummary roots
1666        let root_map = mkRootMap rootSummaries
1667        checkDuplicates root_map
1668        summs <- loop (concatMap msDeps rootSummaries) root_map
1669        return (Just summs)
1670      where
1671         roots = hsc_targets hsc_env
1672
1673         old_summary_map :: NodeMap ModSummary
1674         old_summary_map = mkNodeMap old_summaries
1675
1676         getRootSummary :: Target -> IO ModSummary
1677         getRootSummary (Target (TargetFile file mb_phase) maybe_buf)
1678            = do exists <- doesFileExist file
1679                 if exists 
1680                     then summariseFile hsc_env old_summaries file mb_phase maybe_buf
1681                     else throwDyn $ mkPlainErrMsg noSrcSpan $
1682                            text "can't find file:" <+> text file
1683         getRootSummary (Target (TargetModule modl) maybe_buf)
1684            = do maybe_summary <- summariseModule hsc_env old_summary_map False 
1685                                            (L rootLoc modl) maybe_buf excl_mods
1686                 case maybe_summary of
1687                    Nothing -> packageModErr modl
1688                    Just s  -> return s
1689
1690         rootLoc = mkGeneralSrcSpan (fsLit "<command line>")
1691
1692         -- In a root module, the filename is allowed to diverge from the module
1693         -- name, so we have to check that there aren't multiple root files
1694         -- defining the same module (otherwise the duplicates will be silently
1695         -- ignored, leading to confusing behaviour).
1696         checkDuplicates :: NodeMap [ModSummary] -> IO ()
1697         checkDuplicates root_map 
1698            | allow_dup_roots = return ()
1699            | null dup_roots  = return ()
1700            | otherwise       = multiRootsErr (head dup_roots)
1701            where
1702              dup_roots :: [[ModSummary]]        -- Each at least of length 2
1703              dup_roots = filterOut isSingleton (nodeMapElts root_map)
1704
1705         loop :: [(Located ModuleName,IsBootInterface)]
1706                         -- Work list: process these modules
1707              -> NodeMap [ModSummary]
1708                         -- Visited set; the range is a list because
1709                         -- the roots can have the same module names
1710                         -- if allow_dup_roots is True
1711              -> IO [ModSummary]
1712                         -- The result includes the worklist, except
1713                         -- for those mentioned in the visited set
1714         loop [] done      = return (concat (nodeMapElts done))
1715         loop ((wanted_mod, is_boot) : ss) done 
1716           | Just summs <- lookupFM done key
1717           = if isSingleton summs then
1718                 loop ss done
1719             else
1720                 do { multiRootsErr summs; return [] }
1721           | otherwise         = do { mb_s <- summariseModule hsc_env old_summary_map 
1722                                                  is_boot wanted_mod Nothing excl_mods
1723                                    ; case mb_s of
1724                                         Nothing -> loop ss done
1725                                         Just s  -> loop (msDeps s ++ ss) 
1726                                                         (addToFM done key [s]) }
1727           where
1728             key = (unLoc wanted_mod, if is_boot then HsBootFile else HsSrcFile)
1729
1730 mkRootMap :: [ModSummary] -> NodeMap [ModSummary]
1731 mkRootMap summaries = addListToFM_C (++) emptyFM 
1732                         [ (msKey s, [s]) | s <- summaries ]
1733
1734 msDeps :: ModSummary -> [(Located ModuleName, IsBootInterface)]
1735 -- (msDeps s) returns the dependencies of the ModSummary s.
1736 -- A wrinkle is that for a {-# SOURCE #-} import we return
1737 --      *both* the hs-boot file
1738 --      *and* the source file
1739 -- as "dependencies".  That ensures that the list of all relevant
1740 -- modules always contains B.hs if it contains B.hs-boot.
1741 -- Remember, this pass isn't doing the topological sort.  It's
1742 -- just gathering the list of all relevant ModSummaries
1743 msDeps s = 
1744     concat [ [(m,True), (m,False)] | m <- ms_srcimps s ] 
1745          ++ [ (m,False) | m <- ms_imps s ] 
1746
1747 -----------------------------------------------------------------------------
1748 -- Summarising modules
1749
1750 -- We have two types of summarisation:
1751 --
1752 --    * Summarise a file.  This is used for the root module(s) passed to
1753 --      cmLoadModules.  The file is read, and used to determine the root
1754 --      module name.  The module name may differ from the filename.
1755 --
1756 --    * Summarise a module.  We are given a module name, and must provide
1757 --      a summary.  The finder is used to locate the file in which the module
1758 --      resides.
1759
1760 summariseFile
1761         :: HscEnv
1762         -> [ModSummary]                 -- old summaries
1763         -> FilePath                     -- source file name
1764         -> Maybe Phase                  -- start phase
1765         -> Maybe (StringBuffer,ClockTime)
1766         -> IO ModSummary
1767
1768 summariseFile hsc_env old_summaries file mb_phase maybe_buf
1769         -- we can use a cached summary if one is available and the
1770         -- source file hasn't changed,  But we have to look up the summary
1771         -- by source file, rather than module name as we do in summarise.
1772    | Just old_summary <- findSummaryBySourceFile old_summaries file
1773    = do
1774         let location = ms_location old_summary
1775
1776                 -- return the cached summary if the source didn't change
1777         src_timestamp <- case maybe_buf of
1778                            Just (_,t) -> return t
1779                            Nothing    -> getModificationTime file
1780                 -- The file exists; we checked in getRootSummary above.
1781                 -- If it gets removed subsequently, then this 
1782                 -- getModificationTime may fail, but that's the right
1783                 -- behaviour.
1784
1785         if ms_hs_date old_summary == src_timestamp 
1786            then do -- update the object-file timestamp
1787                   obj_timestamp <-
1788                     if isObjectTarget (hscTarget (hsc_dflags hsc_env)) -- bug #1205
1789                         then getObjTimestamp location False
1790                         else return Nothing
1791                   return old_summary{ ms_obj_date = obj_timestamp }
1792            else
1793                 new_summary
1794
1795    | otherwise
1796    = new_summary
1797   where
1798     new_summary = do
1799         let dflags = hsc_dflags hsc_env
1800
1801         (dflags', hspp_fn, buf)
1802             <- preprocessFile hsc_env file mb_phase maybe_buf
1803
1804         (srcimps,the_imps, L _ mod_name) <- getImports dflags' buf hspp_fn file
1805
1806         -- Make a ModLocation for this file
1807         location <- mkHomeModLocation dflags mod_name file
1808
1809         -- Tell the Finder cache where it is, so that subsequent calls
1810         -- to findModule will find it, even if it's not on any search path
1811         mod <- addHomeModuleToFinder hsc_env mod_name location
1812
1813         src_timestamp <- case maybe_buf of
1814                            Just (_,t) -> return t
1815                            Nothing    -> getModificationTime file
1816                         -- getMofificationTime may fail
1817
1818         -- when the user asks to load a source file by name, we only
1819         -- use an object file if -fobject-code is on.  See #1205.
1820         obj_timestamp <-
1821             if isObjectTarget (hscTarget (hsc_dflags hsc_env))
1822                 then modificationTimeIfExists (ml_obj_file location)
1823                 else return Nothing
1824
1825         return (ModSummary { ms_mod = mod, ms_hsc_src = HsSrcFile,
1826                              ms_location = location,
1827                              ms_hspp_file = hspp_fn,
1828                              ms_hspp_opts = dflags',
1829                              ms_hspp_buf  = Just buf,
1830                              ms_srcimps = srcimps, ms_imps = the_imps,
1831                              ms_hs_date = src_timestamp,
1832                              ms_obj_date = obj_timestamp })
1833
1834 findSummaryBySourceFile :: [ModSummary] -> FilePath -> Maybe ModSummary
1835 findSummaryBySourceFile summaries file
1836   = case [ ms | ms <- summaries, HsSrcFile <- [ms_hsc_src ms],
1837                                  expectJust "findSummaryBySourceFile" (ml_hs_file (ms_location ms)) == file ] of
1838         [] -> Nothing
1839         (x:_) -> Just x
1840
1841 -- Summarise a module, and pick up source and timestamp.
1842 summariseModule
1843           :: HscEnv
1844           -> NodeMap ModSummary -- Map of old summaries
1845           -> IsBootInterface    -- True <=> a {-# SOURCE #-} import
1846           -> Located ModuleName -- Imported module to be summarised
1847           -> Maybe (StringBuffer, ClockTime)
1848           -> [ModuleName]               -- Modules to exclude
1849           -> IO (Maybe ModSummary)      -- Its new summary
1850
1851 summariseModule hsc_env old_summary_map is_boot (L loc wanted_mod) maybe_buf excl_mods
1852   | wanted_mod `elem` excl_mods
1853   = return Nothing
1854
1855   | Just old_summary <- lookupFM old_summary_map (wanted_mod, hsc_src)
1856   = do          -- Find its new timestamp; all the 
1857                 -- ModSummaries in the old map have valid ml_hs_files
1858         let location = ms_location old_summary
1859             src_fn = expectJust "summariseModule" (ml_hs_file location)
1860
1861                 -- check the modification time on the source file, and
1862                 -- return the cached summary if it hasn't changed.  If the
1863                 -- file has disappeared, we need to call the Finder again.
1864         case maybe_buf of
1865            Just (_,t) -> check_timestamp old_summary location src_fn t
1866            Nothing    -> do
1867                 m <- System.IO.Error.try (getModificationTime src_fn)
1868                 case m of
1869                    Right t -> check_timestamp old_summary location src_fn t
1870                    Left e | isDoesNotExistError e -> find_it
1871                           | otherwise             -> ioError e
1872
1873   | otherwise  = find_it
1874   where
1875     dflags = hsc_dflags hsc_env
1876
1877     hsc_src = if is_boot then HsBootFile else HsSrcFile
1878
1879     check_timestamp old_summary location src_fn src_timestamp
1880         | ms_hs_date old_summary == src_timestamp = do
1881                 -- update the object-file timestamp
1882                 obj_timestamp <- getObjTimestamp location is_boot
1883                 return (Just old_summary{ ms_obj_date = obj_timestamp })
1884         | otherwise = 
1885                 -- source changed: re-summarise.
1886                 new_summary location (ms_mod old_summary) src_fn src_timestamp
1887
1888     find_it = do
1889         -- Don't use the Finder's cache this time.  If the module was
1890         -- previously a package module, it may have now appeared on the
1891         -- search path, so we want to consider it to be a home module.  If
1892         -- the module was previously a home module, it may have moved.
1893         uncacheModule hsc_env wanted_mod
1894         found <- findImportedModule hsc_env wanted_mod Nothing
1895         case found of
1896              Found location mod 
1897                 | isJust (ml_hs_file location) ->
1898                         -- Home package
1899                          just_found location mod
1900                 | otherwise -> 
1901                         -- Drop external-pkg
1902                         ASSERT(modulePackageId mod /= thisPackage dflags)
1903                         return Nothing
1904                         
1905              err -> noModError dflags loc wanted_mod err
1906                         -- Not found
1907
1908     just_found location mod = do
1909                 -- Adjust location to point to the hs-boot source file, 
1910                 -- hi file, object file, when is_boot says so
1911         let location' | is_boot   = addBootSuffixLocn location
1912                       | otherwise = location
1913             src_fn = expectJust "summarise2" (ml_hs_file location')
1914
1915                 -- Check that it exists
1916                 -- It might have been deleted since the Finder last found it
1917         maybe_t <- modificationTimeIfExists src_fn
1918         case maybe_t of
1919           Nothing -> noHsFileErr loc src_fn
1920           Just t  -> new_summary location' mod src_fn t
1921
1922
1923     new_summary location mod src_fn src_timestamp
1924       = do
1925         -- Preprocess the source file and get its imports
1926         -- The dflags' contains the OPTIONS pragmas
1927         (dflags', hspp_fn, buf) <- preprocessFile hsc_env src_fn Nothing maybe_buf
1928         (srcimps, the_imps, L mod_loc mod_name) <- getImports dflags' buf hspp_fn src_fn
1929
1930         when (mod_name /= wanted_mod) $
1931                 throwDyn $ mkPlainErrMsg mod_loc $ 
1932                               text "File name does not match module name:" 
1933                               $$ text "Saw:" <+> quotes (ppr mod_name)
1934                               $$ text "Expected:" <+> quotes (ppr wanted_mod)
1935
1936                 -- Find the object timestamp, and return the summary
1937         obj_timestamp <- getObjTimestamp location is_boot
1938
1939         return (Just ( ModSummary { ms_mod       = mod, 
1940                                     ms_hsc_src   = hsc_src,
1941                                     ms_location  = location,
1942                                     ms_hspp_file = hspp_fn,
1943                                     ms_hspp_opts = dflags',
1944                                     ms_hspp_buf  = Just buf,
1945                                     ms_srcimps   = srcimps,
1946                                     ms_imps      = the_imps,
1947                                     ms_hs_date   = src_timestamp,
1948                                     ms_obj_date  = obj_timestamp }))
1949
1950
1951 getObjTimestamp :: ModLocation -> Bool -> IO (Maybe ClockTime)
1952 getObjTimestamp location is_boot
1953   = if is_boot then return Nothing
1954                else modificationTimeIfExists (ml_obj_file location)
1955
1956
1957 preprocessFile :: HscEnv -> FilePath -> Maybe Phase -> Maybe (StringBuffer,ClockTime)
1958   -> IO (DynFlags, FilePath, StringBuffer)
1959 preprocessFile hsc_env src_fn mb_phase Nothing
1960   = do
1961         (dflags', hspp_fn) <- preprocess hsc_env (src_fn, mb_phase)
1962         buf <- hGetStringBuffer hspp_fn
1963         return (dflags', hspp_fn, buf)
1964
1965 preprocessFile hsc_env src_fn mb_phase (Just (buf, _time))
1966   = do
1967         let dflags = hsc_dflags hsc_env
1968         -- case we bypass the preprocessing stage?
1969         let 
1970             local_opts = getOptions dflags buf src_fn
1971         --
1972         (dflags', leftovers, warns) <- parseDynamicFlags dflags (map unLoc local_opts)
1973         checkProcessArgsResult leftovers src_fn
1974         handleFlagWarnings dflags' warns
1975
1976         let
1977             needs_preprocessing
1978                 | Just (Unlit _) <- mb_phase    = True
1979                 | Nothing <- mb_phase, Unlit _ <- startPhase src_fn  = True
1980                   -- note: local_opts is only required if there's no Unlit phase
1981                 | dopt Opt_Cpp dflags'          = True
1982                 | dopt Opt_Pp  dflags'          = True
1983                 | otherwise                     = False
1984
1985         when needs_preprocessing $
1986            ghcError (ProgramError "buffer needs preprocesing; interactive check disabled")
1987
1988         return (dflags', src_fn, buf)
1989
1990
1991 -----------------------------------------------------------------------------
1992 --                      Error messages
1993 -----------------------------------------------------------------------------
1994
1995 noModError :: DynFlags -> SrcSpan -> ModuleName -> FindResult -> IO ab
1996 -- ToDo: we don't have a proper line number for this error
1997 noModError dflags loc wanted_mod err
1998   = throwDyn $ mkPlainErrMsg loc $ cannotFindModule dflags wanted_mod err
1999                                 
2000 noHsFileErr :: SrcSpan -> String -> a
2001 noHsFileErr loc path
2002   = throwDyn $ mkPlainErrMsg loc $ text "Can't find" <+> text path
2003  
2004 packageModErr :: ModuleName -> a
2005 packageModErr mod
2006   = throwDyn $ mkPlainErrMsg noSrcSpan $
2007         text "module" <+> quotes (ppr mod) <+> text "is a package module"
2008
2009 multiRootsErr :: [ModSummary] -> IO ()
2010 multiRootsErr [] = panic "multiRootsErr"
2011 multiRootsErr summs@(summ1:_)
2012   = throwDyn $ mkPlainErrMsg noSrcSpan $
2013         text "module" <+> quotes (ppr mod) <+> 
2014         text "is defined in multiple files:" <+>
2015         sep (map text files)
2016   where
2017     mod = ms_mod summ1
2018     files = map (expectJust "checkDup" . ml_hs_file . ms_location) summs
2019
2020 cyclicModuleErr :: [ModSummary] -> SDoc
2021 cyclicModuleErr ms
2022   = hang (ptext (sLit "Module imports form a cycle for modules:"))
2023        2 (vcat (map show_one ms))
2024   where
2025     show_one ms = sep [ show_mod (ms_hsc_src ms) (ms_mod ms),
2026                         nest 2 $ ptext (sLit "imports:") <+> 
2027                                    (pp_imps HsBootFile (ms_srcimps ms)
2028                                    $$ pp_imps HsSrcFile  (ms_imps ms))]
2029     show_mod hsc_src mod = ppr mod <> text (hscSourceString hsc_src)
2030     pp_imps src mods = fsep (map (show_mod src) mods)
2031
2032
2033 -- | Inform GHC that the working directory has changed.  GHC will flush
2034 -- its cache of module locations, since it may no longer be valid.
2035 -- Note: if you change the working directory, you should also unload
2036 -- the current program (set targets to empty, followed by load).
2037 workingDirectoryChanged :: Session -> IO ()
2038 workingDirectoryChanged s = withSession s $ flushFinderCaches
2039
2040 -- -----------------------------------------------------------------------------
2041 -- inspecting the session
2042
2043 -- | Get the module dependency graph.
2044 getModuleGraph :: Session -> IO ModuleGraph -- ToDo: DiGraph ModSummary
2045 getModuleGraph s = withSession s (return . hsc_mod_graph)
2046
2047 isLoaded :: Session -> ModuleName -> IO Bool
2048 isLoaded s m = withSession s $ \hsc_env ->
2049   return $! isJust (lookupUFM (hsc_HPT hsc_env) m)
2050
2051 getBindings :: Session -> IO [TyThing]
2052 getBindings s = withSession s $ \hsc_env ->
2053    -- we have to implement the shadowing behaviour of ic_tmp_ids here
2054    -- (see InteractiveContext) and the quickest way is to use an OccEnv.
2055    let 
2056        tmp_ids = ic_tmp_ids (hsc_IC hsc_env)
2057        filtered = foldr f (const []) tmp_ids emptyUniqSet
2058        f id rest set 
2059            | uniq `elementOfUniqSet` set = rest set
2060            | otherwise  = AnId id : rest (addOneToUniqSet set uniq)
2061            where uniq = getUnique (nameOccName (idName id))
2062    in
2063    return filtered
2064
2065 getPrintUnqual :: Session -> IO PrintUnqualified
2066 getPrintUnqual s = withSession s $ \hsc_env ->
2067   return (icPrintUnqual (hsc_dflags hsc_env) (hsc_IC hsc_env))
2068
2069 -- | Container for information about a 'Module'.
2070 data ModuleInfo = ModuleInfo {
2071         minf_type_env  :: TypeEnv,
2072         minf_exports   :: NameSet, -- ToDo, [AvailInfo] like ModDetails?
2073         minf_rdr_env   :: Maybe GlobalRdrEnv,   -- Nothing for a compiled/package mod
2074         minf_instances :: [Instance]
2075 #ifdef GHCI
2076         ,minf_modBreaks :: ModBreaks 
2077 #endif
2078         -- ToDo: this should really contain the ModIface too
2079   }
2080         -- We don't want HomeModInfo here, because a ModuleInfo applies
2081         -- to package modules too.
2082
2083 -- | Request information about a loaded 'Module'
2084 getModuleInfo :: Session -> Module -> IO (Maybe ModuleInfo)
2085 getModuleInfo s mdl = withSession s $ \hsc_env -> do
2086   let mg = hsc_mod_graph hsc_env
2087   if mdl `elem` map ms_mod mg
2088         then getHomeModuleInfo hsc_env (moduleName mdl)
2089         else do
2090   {- if isHomeModule (hsc_dflags hsc_env) mdl
2091         then return Nothing
2092         else -} getPackageModuleInfo hsc_env mdl
2093    -- getPackageModuleInfo will attempt to find the interface, so
2094    -- we don't want to call it for a home module, just in case there
2095    -- was a problem loading the module and the interface doesn't
2096    -- exist... hence the isHomeModule test here.  (ToDo: reinstate)
2097
2098 getPackageModuleInfo :: HscEnv -> Module -> IO (Maybe ModuleInfo)
2099 #ifdef GHCI
2100 getPackageModuleInfo hsc_env mdl = do
2101   (_msgs, mb_avails) <- getModuleExports hsc_env mdl
2102   case mb_avails of
2103     Nothing -> return Nothing
2104     Just avails -> do
2105         eps <- readIORef (hsc_EPS hsc_env)
2106         let 
2107             names  = availsToNameSet avails
2108             pte    = eps_PTE eps
2109             tys    = [ ty | name <- concatMap availNames avails,
2110                             Just ty <- [lookupTypeEnv pte name] ]
2111         --
2112         return (Just (ModuleInfo {
2113                         minf_type_env  = mkTypeEnv tys,
2114                         minf_exports   = names,
2115                         minf_rdr_env   = Just $! nameSetToGlobalRdrEnv names (moduleName mdl),
2116                         minf_instances = error "getModuleInfo: instances for package module unimplemented",
2117                         minf_modBreaks = emptyModBreaks  
2118                 }))
2119 #else
2120 getPackageModuleInfo _hsc_env _mdl = do
2121   -- bogusly different for non-GHCI (ToDo)
2122   return Nothing
2123 #endif
2124
2125 getHomeModuleInfo :: HscEnv -> ModuleName -> IO (Maybe ModuleInfo)
2126 getHomeModuleInfo hsc_env mdl = 
2127   case lookupUFM (hsc_HPT hsc_env) mdl of
2128     Nothing  -> return Nothing
2129     Just hmi -> do
2130       let details = hm_details hmi
2131       return (Just (ModuleInfo {
2132                         minf_type_env  = md_types details,
2133                         minf_exports   = availsToNameSet (md_exports details),
2134                         minf_rdr_env   = mi_globals $! hm_iface hmi,
2135                         minf_instances = md_insts details
2136 #ifdef GHCI
2137                        ,minf_modBreaks = getModBreaks hmi
2138 #endif
2139                         }))
2140
2141 -- | The list of top-level entities defined in a module
2142 modInfoTyThings :: ModuleInfo -> [TyThing]
2143 modInfoTyThings minf = typeEnvElts (minf_type_env minf)
2144
2145 modInfoTopLevelScope :: ModuleInfo -> Maybe [Name]
2146 modInfoTopLevelScope minf
2147   = fmap (map gre_name . globalRdrEnvElts) (minf_rdr_env minf)
2148
2149 modInfoExports :: ModuleInfo -> [Name]
2150 modInfoExports minf = nameSetToList $! minf_exports minf
2151
2152 -- | Returns the instances defined by the specified module.
2153 -- Warning: currently unimplemented for package modules.
2154 modInfoInstances :: ModuleInfo -> [Instance]
2155 modInfoInstances = minf_instances
2156
2157 modInfoIsExportedName :: ModuleInfo -> Name -> Bool
2158 modInfoIsExportedName minf name = elemNameSet name (minf_exports minf)
2159
2160 mkPrintUnqualifiedForModule :: Session -> ModuleInfo -> IO (Maybe PrintUnqualified)
2161 mkPrintUnqualifiedForModule s minf = withSession s $ \hsc_env -> do
2162   return (fmap (mkPrintUnqualified (hsc_dflags hsc_env)) (minf_rdr_env minf))
2163
2164 modInfoLookupName :: Session -> ModuleInfo -> Name -> IO (Maybe TyThing)
2165 modInfoLookupName s minf name = withSession s $ \hsc_env -> do
2166    case lookupTypeEnv (minf_type_env minf) name of
2167      Just tyThing -> return (Just tyThing)
2168      Nothing      -> do
2169        eps <- readIORef (hsc_EPS hsc_env)
2170        return $! lookupType (hsc_dflags hsc_env) 
2171                             (hsc_HPT hsc_env) (eps_PTE eps) name
2172
2173 #ifdef GHCI
2174 modInfoModBreaks :: ModuleInfo -> ModBreaks
2175 modInfoModBreaks = minf_modBreaks  
2176 #endif
2177
2178 isDictonaryId :: Id -> Bool
2179 isDictonaryId id
2180   = case tcSplitSigmaTy (idType id) of { (_tvs, _theta, tau) -> isDictTy tau }
2181
2182 -- | Looks up a global name: that is, any top-level name in any
2183 -- visible module.  Unlike 'lookupName', lookupGlobalName does not use
2184 -- the interactive context, and therefore does not require a preceding
2185 -- 'setContext'.
2186 lookupGlobalName :: Session -> Name -> IO (Maybe TyThing)
2187 lookupGlobalName s name = withSession s $ \hsc_env -> do
2188    eps <- readIORef (hsc_EPS hsc_env)
2189    return $! lookupType (hsc_dflags hsc_env) 
2190                         (hsc_HPT hsc_env) (eps_PTE eps) name
2191
2192 #ifdef GHCI
2193 -- | get the GlobalRdrEnv for a session
2194 getGRE :: Session -> IO GlobalRdrEnv
2195 getGRE s = withSession s $ \hsc_env-> return $ ic_rn_gbl_env (hsc_IC hsc_env)
2196 #endif
2197
2198 -- -----------------------------------------------------------------------------
2199 -- Misc exported utils
2200
2201 dataConType :: DataCon -> Type
2202 dataConType dc = idType (dataConWrapId dc)
2203
2204 -- | print a 'NamedThing', adding parentheses if the name is an operator.
2205 pprParenSymName :: NamedThing a => a -> SDoc
2206 pprParenSymName a = parenSymOcc (getOccName a) (ppr (getName a))
2207
2208 -- ----------------------------------------------------------------------------
2209
2210 #if 0
2211
2212 -- ToDo:
2213 --   - Data and Typeable instances for HsSyn.
2214
2215 -- ToDo: check for small transformations that happen to the syntax in
2216 -- the typechecker (eg. -e ==> negate e, perhaps for fromIntegral)
2217
2218 -- ToDo: maybe use TH syntax instead of IfaceSyn?  There's already a way
2219 -- to get from TyCons, Ids etc. to TH syntax (reify).
2220
2221 -- :browse will use either lm_toplev or inspect lm_interface, depending
2222 -- on whether the module is interpreted or not.
2223
2224 -- This is for reconstructing refactored source code
2225 -- Calls the lexer repeatedly.
2226 -- ToDo: add comment tokens to token stream
2227 getTokenStream :: Session -> Module -> IO [Located Token]
2228 #endif
2229
2230 -- -----------------------------------------------------------------------------
2231 -- Interactive evaluation
2232
2233 -- | Takes a 'ModuleName' and possibly a 'PackageId', and consults the
2234 -- filesystem and package database to find the corresponding 'Module', 
2235 -- using the algorithm that is used for an @import@ declaration.
2236 findModule :: Session -> ModuleName -> Maybe PackageId -> IO Module
2237 findModule s mod_name maybe_pkg = withSession s $ \hsc_env ->
2238   let
2239         dflags = hsc_dflags hsc_env
2240         hpt    = hsc_HPT hsc_env
2241         this_pkg = thisPackage dflags
2242   in
2243   case lookupUFM hpt mod_name of
2244     Just mod_info -> return (mi_module (hm_iface mod_info))
2245     _not_a_home_module -> do
2246           res <- findImportedModule hsc_env mod_name maybe_pkg
2247           case res of
2248             Found _ m | modulePackageId m /= this_pkg -> return m
2249                       | otherwise -> throwDyn (CmdLineError (showSDoc $
2250                                         text "module" <+> quotes (ppr (moduleName m)) <+>
2251                                         text "is not loaded"))
2252             err -> let msg = cannotFindModule dflags mod_name err in
2253                    throwDyn (CmdLineError (showSDoc msg))
2254
2255 #ifdef GHCI
2256 getHistorySpan :: Session -> History -> IO SrcSpan
2257 getHistorySpan sess h = withSession sess $ \hsc_env -> 
2258                           return$ InteractiveEval.getHistorySpan hsc_env h
2259
2260 obtainTerm :: Session -> Bool -> Id -> IO Term
2261 obtainTerm sess force id = withSession sess $ \hsc_env ->
2262                             InteractiveEval.obtainTerm hsc_env force id
2263
2264 obtainTerm1 :: Session -> Bool -> Maybe Type -> a -> IO Term
2265 obtainTerm1 sess force mb_ty a = withSession sess $ \hsc_env ->
2266                                InteractiveEval.obtainTerm1 hsc_env force mb_ty a
2267
2268 obtainTermB :: Session -> Int -> Bool -> Id -> IO Term
2269 obtainTermB sess bound force id = withSession sess $ \hsc_env ->
2270                             InteractiveEval.obtainTermB hsc_env bound force id
2271
2272 #endif