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