1 {-# OPTIONS -fno-warn-incomplete-patterns -optc-DNON_POSIX_SOURCE #-}
3 -----------------------------------------------------------------------------
7 -- (c) The University of Glasgow 2005
9 -----------------------------------------------------------------------------
11 module Main (main) where
13 -- The official GHC API
15 import GHC ( -- DynFlags(..), HscTarget(..),
16 -- GhcMode(..), GhcLink(..),
17 LoadHowMuch(..), -- dopt, DynFlag(..),
21 -- Implementations of the various modes (--show-iface, mkdependHS. etc.)
22 import LoadIface ( showIface )
23 import HscMain ( newHscEnv )
24 import DriverPipeline ( oneShot, compileFile )
25 import DriverMkDepend ( doMkDependHS )
27 import InteractiveUI ( interactiveUI, ghciWelcomeMsg )
31 -- Various other random stuff that we need
34 import Packages ( dumpPackages )
35 import DriverPhases ( Phase(..), isSourceFilename, anyHsc,
36 startPhase, isHaskellSrcFilename )
37 import BasicTypes ( failed )
39 import StaticFlagParser
47 -- import MonadUtils ( liftIO )
49 -- Imports for --abi-hash
50 import LoadIface ( loadUserInterface )
51 import Module ( mkModuleName )
52 import Finder ( findImportedModule, cannotFindInterface )
53 import TcRnMonad ( initIfaceCheck )
54 import Binary ( openBinMem, put_, fingerprintBinMem )
56 -- Standard Haskell libraries
58 import System.Environment
60 import System.FilePath
66 -----------------------------------------------------------------------------
69 -- time commands when run with -v
71 -- Win32 support: proper signal handling
72 -- reading the package configuration file is too slow
75 -----------------------------------------------------------------------------
76 -- GHC's command-line interface
80 hSetBuffering stdout NoBuffering
81 GHC.defaultErrorHandler defaultDynFlags $ do
82 -- 1. extract the -B flag from the args
85 let (minusB_args, argv1) = partition ("-B" `isPrefixOf`) argv0
86 mbMinusB | null minusB_args = Nothing
87 | otherwise = Just (drop 2 (last minusB_args))
89 let argv1' = map (mkGeneralLocated "on the commandline") argv1
90 (argv2, staticFlagWarnings) <- parseStaticFlags argv1'
92 -- 2. Parse the "mode" flags (--make, --interactive etc.)
93 (mode, argv3, modeFlagWarnings) <- parseModeFlags argv2
95 let flagWarnings = staticFlagWarnings ++ modeFlagWarnings
97 -- If all we want to do is something like showing the version number
98 -- then do it now, before we start a GHC session etc. This makes
99 -- getting basic information much more resilient.
101 -- In particular, if we wait until later before giving the version
102 -- number then bootstrapping gets confused, as it tries to find out
103 -- what version of GHC it's using before package.conf exists, so
104 -- starting the session fails.
106 Left preStartupMode ->
107 do case preStartupMode of
108 ShowSupportedExtensions -> showSupportedExtensions
109 ShowVersion -> showVersion
110 ShowNumVersion -> putStrLn cProjectVersion
111 Print str -> putStrLn str
112 Right postStartupMode ->
113 -- start our GHC session
114 GHC.runGhc mbMinusB $ do
116 dflags <- GHC.getSessionDynFlags
118 case postStartupMode of
122 ShowInfo -> showInfo dflags
123 ShowGhcUsage -> showGhcUsage dflags
124 ShowGhciUsage -> showGhciUsage dflags
125 PrintWithDynFlags f -> putStrLn (f dflags)
126 Right postLoadMode ->
127 main' postLoadMode dflags argv3 flagWarnings
129 main' :: PostLoadMode -> DynFlags -> [Located String] -> [Located String]
131 main' postLoadMode dflags0 args flagWarnings = do
132 -- set the default GhcMode, HscTarget and GhcLink. The HscTarget
133 -- can be further adjusted on a module by module basis, using only
134 -- the -fvia-C and -fasm flags. If the default HscTarget is not
135 -- HscC or HscAsm, -fvia-C and -fasm have no effect.
136 let dflt_target = hscTarget dflags0
138 = case postLoadMode of
139 DoInteractive -> (CompManager, HscInterpreted, LinkInMemory)
140 DoEval _ -> (CompManager, HscInterpreted, LinkInMemory)
141 DoMake -> (CompManager, dflt_target, LinkBinary)
142 DoMkDependHS -> (MkDepend, dflt_target, LinkBinary)
143 DoAbiHash -> (OneShot, dflt_target, LinkBinary)
144 _ -> (OneShot, dflt_target, LinkBinary)
146 let dflags1 = dflags0{ ghcMode = mode,
149 -- leave out hscOutName for now
150 hscOutName = panic "Main.main:hscOutName not set",
151 verbosity = case postLoadMode of
156 -- turn on -fimplicit-import-qualified for GHCi now, so that it
157 -- can be overriden from the command-line
158 dflags1a | DoInteractive <- postLoadMode = imp_qual_enabled
159 | DoEval _ <- postLoadMode = imp_qual_enabled
160 | otherwise = dflags1
161 where imp_qual_enabled = dflags1 `dopt_set` Opt_ImplicitImportQualified
163 -- The rest of the arguments are "dynamic"
164 -- Leftover ones are presumably files
165 (dflags2, fileish_args, dynamicFlagWarnings) <- GHC.parseDynamicFlags dflags1a args
167 let flagWarnings' = flagWarnings ++ dynamicFlagWarnings
169 handleSourceError (\e -> do
170 GHC.printExceptionAndWarnings e
171 liftIO $ exitWith (ExitFailure 1)) $
172 handleFlagWarnings dflags2 flagWarnings'
174 -- make sure we clean up after ourselves
175 GHC.defaultCleanupHandler dflags2 $ do
177 liftIO $ showBanner postLoadMode dflags2
179 -- we've finished manipulating the DynFlags, update the session
180 _ <- GHC.setSessionDynFlags dflags2
181 dflags3 <- GHC.getSessionDynFlags
182 hsc_env <- GHC.getSession
185 -- To simplify the handling of filepaths, we normalise all filepaths right
186 -- away - e.g., for win32 platforms, backslashes are converted
187 -- into forward slashes.
188 normal_fileish_paths = map (normalise . unLoc) fileish_args
189 (srcs, objs) = partition_args normal_fileish_paths [] []
191 -- Note: have v_Ld_inputs maintain the order in which 'objs' occurred on
193 liftIO $ mapM_ (consIORef v_Ld_inputs) (reverse objs)
195 ---------------- Display configuration -----------
196 when (verbosity dflags3 >= 4) $
197 liftIO $ dumpPackages dflags3
199 when (verbosity dflags3 >= 3) $ do
200 liftIO $ hPutStrLn stderr ("Hsc static flags: " ++ unwords staticFlags)
202 ---------------- Final sanity checking -----------
203 liftIO $ checkOptions postLoadMode dflags3 srcs objs
205 ---------------- Do the business -----------
206 handleSourceError (\e -> do
207 GHC.printExceptionAndWarnings e
208 liftIO $ exitWith (ExitFailure 1)) $ do
210 ShowInterface f -> liftIO $ doShowIface dflags3 f
211 DoMake -> doMake srcs
212 DoMkDependHS -> do doMkDependHS (map fst srcs)
214 StopBefore p -> oneShot hsc_env p srcs >> GHC.printWarnings
215 DoInteractive -> interactiveUI srcs Nothing
216 DoEval exprs -> interactiveUI srcs $ Just $ reverse exprs
217 DoAbiHash -> abiHash srcs
219 liftIO $ dumpFinalStats dflags3
222 interactiveUI :: b -> c -> Ghc ()
224 ghcError (CmdLineError "not built for interactive use")
227 -- -----------------------------------------------------------------------------
228 -- Splitting arguments into source files and object files. This is where we
229 -- interpret the -x <suffix> option, and attach a (Maybe Phase) to each source
230 -- file indicating the phase specified by the -x option in force, if any.
232 partition_args :: [String] -> [(String, Maybe Phase)] -> [String]
233 -> ([(String, Maybe Phase)], [String])
234 partition_args [] srcs objs = (reverse srcs, reverse objs)
235 partition_args ("-x":suff:args) srcs objs
236 | "none" <- suff = partition_args args srcs objs
237 | StopLn <- phase = partition_args args srcs (slurp ++ objs)
238 | otherwise = partition_args rest (these_srcs ++ srcs) objs
239 where phase = startPhase suff
240 (slurp,rest) = break (== "-x") args
241 these_srcs = zip slurp (repeat (Just phase))
242 partition_args (arg:args) srcs objs
243 | looks_like_an_input arg = partition_args args ((arg,Nothing):srcs) objs
244 | otherwise = partition_args args srcs (arg:objs)
247 We split out the object files (.o, .dll) and add them
248 to v_Ld_inputs for use by the linker.
250 The following things should be considered compilation manager inputs:
252 - haskell source files (strings ending in .hs, .lhs or other
253 haskellish extension),
255 - module names (not forgetting hierarchical module names),
257 - and finally we consider everything not containing a '.' to be
258 a comp manager input, as shorthand for a .hs or .lhs filename.
260 Everything else is considered to be a linker object, and passed
261 straight through to the linker.
263 looks_like_an_input :: String -> Bool
264 looks_like_an_input m = isSourceFilename m
265 || looksLikeModuleName m
268 -- -----------------------------------------------------------------------------
269 -- Option sanity checks
271 -- | Ensure sanity of options.
273 -- Throws 'UsageError' or 'CmdLineError' if not.
274 checkOptions :: PostLoadMode -> DynFlags -> [(String,Maybe Phase)] -> [String] -> IO ()
275 -- Final sanity checking before kicking off a compilation (pipeline).
276 checkOptions mode dflags srcs objs = do
277 -- Complain about any unknown flags
278 let unknown_opts = [ f | (f@('-':_), _) <- srcs ]
279 when (notNull unknown_opts) (unknownFlagsErr unknown_opts)
281 when (notNull (filter isRTSWay (wayNames dflags))
282 && isInterpretiveMode mode) $
283 hPutStrLn stderr ("Warning: -debug, -threaded and -ticky are ignored by GHCi")
285 -- -prof and --interactive are not a good combination
286 when (notNull (filter (not . isRTSWay) (wayNames dflags))
287 && isInterpretiveMode mode) $
288 do ghcError (UsageError
289 "--interactive can't be used with -prof or -unreg.")
291 if (isJust (outputHi dflags) &&
292 (isCompManagerMode mode || srcs `lengthExceeds` 1))
293 then ghcError (UsageError "-ohi can only be used when compiling a single source file")
296 -- -o sanity checking
297 if (srcs `lengthExceeds` 1 && isJust (outputFile dflags)
298 && not (isLinkMode mode))
299 then ghcError (UsageError "can't apply -o to multiple source files")
302 let not_linking = not (isLinkMode mode) || isNoLink (ghcLink dflags)
304 when (not_linking && not (null objs)) $
305 hPutStrLn stderr ("Warning: the following files would be used as linker inputs, but linking is not being done: " ++ unwords objs)
307 -- Check that there are some input files
308 -- (except in the interactive case)
309 if null srcs && (null objs || not_linking) && needsInputsMode mode
310 then ghcError (UsageError "no input files")
313 -- Verify that output files point somewhere sensible.
314 verifyOutputFiles dflags
317 -- Compiler output options
319 -- called to verify that the output files & directories
320 -- point somewhere valid.
322 -- The assumption is that the directory portion of these output
323 -- options will have to exist by the time 'verifyOutputFiles'
326 verifyOutputFiles :: DynFlags -> IO ()
327 verifyOutputFiles dflags = do
328 -- not -odir: we create the directory for -odir if it doesn't exist (#2278).
329 let ofile = outputFile dflags
330 when (isJust ofile) $ do
331 let fn = fromJust ofile
332 flg <- doesDirNameExist fn
333 when (not flg) (nonExistentDir "-o" fn)
334 let ohi = outputHi dflags
335 when (isJust ohi) $ do
336 let hi = fromJust ohi
337 flg <- doesDirNameExist hi
338 when (not flg) (nonExistentDir "-ohi" hi)
340 nonExistentDir flg dir =
341 ghcError (CmdLineError ("error: directory portion of " ++
342 show dir ++ " does not exist (used with " ++
343 show flg ++ " option.)"))
345 -----------------------------------------------------------------------------
346 -- GHC modes of operation
348 type Mode = Either PreStartupMode PostStartupMode
349 type PostStartupMode = Either PreLoadMode PostLoadMode
352 = ShowVersion -- ghc -V/--version
353 | ShowNumVersion -- ghc --numeric-version
354 | ShowSupportedExtensions -- ghc --supported-extensions
355 | Print String -- ghc --print-foo
357 showVersionMode, showNumVersionMode, showSupportedExtensionsMode :: Mode
358 showVersionMode = mkPreStartupMode ShowVersion
359 showNumVersionMode = mkPreStartupMode ShowNumVersion
360 showSupportedExtensionsMode = mkPreStartupMode ShowSupportedExtensions
362 printMode :: String -> Mode
363 printMode str = mkPreStartupMode (Print str)
365 mkPreStartupMode :: PreStartupMode -> Mode
366 mkPreStartupMode = Left
368 isShowVersionMode :: Mode -> Bool
369 isShowVersionMode (Left ShowVersion) = True
370 isShowVersionMode _ = False
372 isShowNumVersionMode :: Mode -> Bool
373 isShowNumVersionMode (Left ShowNumVersion) = True
374 isShowNumVersionMode _ = False
377 = ShowGhcUsage -- ghc -?
378 | ShowGhciUsage -- ghci -?
379 | ShowInfo -- ghc --info
380 | PrintWithDynFlags (DynFlags -> String) -- ghc --print-foo
382 showGhcUsageMode, showGhciUsageMode, showInfoMode :: Mode
383 showGhcUsageMode = mkPreLoadMode ShowGhcUsage
384 showGhciUsageMode = mkPreLoadMode ShowGhciUsage
385 showInfoMode = mkPreLoadMode ShowInfo
387 printWithDynFlagsMode :: (DynFlags -> String) -> Mode
388 printWithDynFlagsMode f = mkPreLoadMode (PrintWithDynFlags f)
390 mkPreLoadMode :: PreLoadMode -> Mode
391 mkPreLoadMode = Right . Left
393 isShowGhcUsageMode :: Mode -> Bool
394 isShowGhcUsageMode (Right (Left ShowGhcUsage)) = True
395 isShowGhcUsageMode _ = False
397 isShowGhciUsageMode :: Mode -> Bool
398 isShowGhciUsageMode (Right (Left ShowGhciUsage)) = True
399 isShowGhciUsageMode _ = False
402 = ShowInterface FilePath -- ghc --show-iface
403 | DoMkDependHS -- ghc -M
404 | StopBefore Phase -- ghc -E | -C | -S
405 -- StopBefore StopLn is the default
406 | DoMake -- ghc --make
407 | DoInteractive -- ghc --interactive
408 | DoEval [String] -- ghc -e foo -e bar => DoEval ["bar", "foo"]
409 | DoAbiHash -- ghc --abi-hash
411 doMkDependHSMode, doMakeMode, doInteractiveMode, doAbiHashMode :: Mode
412 doMkDependHSMode = mkPostLoadMode DoMkDependHS
413 doMakeMode = mkPostLoadMode DoMake
414 doInteractiveMode = mkPostLoadMode DoInteractive
415 doAbiHashMode = mkPostLoadMode DoAbiHash
417 showInterfaceMode :: FilePath -> Mode
418 showInterfaceMode fp = mkPostLoadMode (ShowInterface fp)
420 stopBeforeMode :: Phase -> Mode
421 stopBeforeMode phase = mkPostLoadMode (StopBefore phase)
423 doEvalMode :: String -> Mode
424 doEvalMode str = mkPostLoadMode (DoEval [str])
426 mkPostLoadMode :: PostLoadMode -> Mode
427 mkPostLoadMode = Right . Right
429 isDoInteractiveMode :: Mode -> Bool
430 isDoInteractiveMode (Right (Right DoInteractive)) = True
431 isDoInteractiveMode _ = False
433 isStopLnMode :: Mode -> Bool
434 isStopLnMode (Right (Right (StopBefore StopLn))) = True
435 isStopLnMode _ = False
437 isDoMakeMode :: Mode -> Bool
438 isDoMakeMode (Right (Right DoMake)) = True
439 isDoMakeMode _ = False
442 isInteractiveMode :: PostLoadMode -> Bool
443 isInteractiveMode DoInteractive = True
444 isInteractiveMode _ = False
447 -- isInterpretiveMode: byte-code compiler involved
448 isInterpretiveMode :: PostLoadMode -> Bool
449 isInterpretiveMode DoInteractive = True
450 isInterpretiveMode (DoEval _) = True
451 isInterpretiveMode _ = False
453 needsInputsMode :: PostLoadMode -> Bool
454 needsInputsMode DoMkDependHS = True
455 needsInputsMode (StopBefore _) = True
456 needsInputsMode DoMake = True
457 needsInputsMode _ = False
459 -- True if we are going to attempt to link in this mode.
460 -- (we might not actually link, depending on the GhcLink flag)
461 isLinkMode :: PostLoadMode -> Bool
462 isLinkMode (StopBefore StopLn) = True
463 isLinkMode DoMake = True
464 isLinkMode DoInteractive = True
465 isLinkMode (DoEval _) = True
468 isCompManagerMode :: PostLoadMode -> Bool
469 isCompManagerMode DoMake = True
470 isCompManagerMode DoInteractive = True
471 isCompManagerMode (DoEval _) = True
472 isCompManagerMode _ = False
474 -- -----------------------------------------------------------------------------
475 -- Parsing the mode flag
477 parseModeFlags :: [Located String]
481 parseModeFlags args = do
482 let ((leftover, errs1, warns), (mModeFlag, errs2, flags')) =
483 runCmdLine (processArgs mode_flags args)
485 mode = case mModeFlag of
486 Nothing -> doMakeMode
488 errs = errs1 ++ map (mkGeneralLocated "on the commandline") errs2
489 when (not (null errs)) $ ghcError $ errorsToGhcException errs
490 return (mode, flags' ++ leftover, warns)
492 type ModeM = CmdLineP (Maybe (Mode, String), [String], [Located String])
493 -- mode flags sometimes give rise to new DynFlags (eg. -C, see below)
494 -- so we collect the new ones and return them.
496 mode_flags :: [Flag ModeM]
498 [ ------- help / version ----------------------------------------------
499 Flag "?" (PassFlag (setMode showGhcUsageMode))
500 , Flag "-help" (PassFlag (setMode showGhcUsageMode))
501 , Flag "V" (PassFlag (setMode showVersionMode))
502 , Flag "-version" (PassFlag (setMode showVersionMode))
503 , Flag "-numeric-version" (PassFlag (setMode showNumVersionMode))
504 , Flag "-info" (PassFlag (setMode showInfoMode))
505 , Flag "-supported-languages" (PassFlag (setMode showSupportedExtensionsMode))
506 , Flag "-supported-extensions" (PassFlag (setMode showSupportedExtensionsMode))
508 [ Flag k' (PassFlag (setMode mode))
509 | (k, v) <- compilerInfo,
510 let k' = "-print-" ++ map (replaceSpace . toLower) k
511 replaceSpace ' ' = '-'
514 String str -> printMode str
515 FromDynFlags f -> printWithDynFlagsMode f
517 ------- interfaces ----------------------------------------------------
518 [ Flag "-show-iface" (HasArg (\f -> setMode (showInterfaceMode f)
521 ------- primary modes ------------------------------------------------
522 , Flag "c" (PassFlag (\f -> do setMode (stopBeforeMode StopLn) f
523 addFlag "-no-link" f))
524 , Flag "M" (PassFlag (setMode doMkDependHSMode))
525 , Flag "E" (PassFlag (setMode (stopBeforeMode anyHsc)))
526 , Flag "C" (PassFlag (\f -> do setMode (stopBeforeMode HCc) f
527 addFlag "-fvia-C" f))
528 , Flag "S" (PassFlag (setMode (stopBeforeMode As)))
529 , Flag "-make" (PassFlag (setMode doMakeMode))
530 , Flag "-interactive" (PassFlag (setMode doInteractiveMode))
531 , Flag "-abi-hash" (PassFlag (setMode doAbiHashMode))
532 , Flag "e" (SepArg (\s -> setMode (doEvalMode s) "-e"))
535 setMode :: Mode -> String -> EwM ModeM ()
536 setMode newMode newFlag = liftEwM $ do
537 (mModeFlag, errs, flags') <- getCmdLineState
538 let (modeFlag', errs') =
540 Nothing -> ((newMode, newFlag), errs)
541 Just (oldMode, oldFlag) ->
542 case (oldMode, newMode) of
543 -- -c/--make are allowed together, and mean --make -no-link
544 _ | isStopLnMode oldMode && isDoMakeMode newMode
545 || isStopLnMode newMode && isDoMakeMode oldMode ->
546 ((doMakeMode, "--make"), [])
548 -- If we have both --help and --interactive then we
549 -- want showGhciUsage
550 _ | isShowGhcUsageMode oldMode &&
551 isDoInteractiveMode newMode ->
552 ((showGhciUsageMode, oldFlag), [])
553 | isShowGhcUsageMode newMode &&
554 isDoInteractiveMode oldMode ->
555 ((showGhciUsageMode, newFlag), [])
556 -- Otherwise, --help/--version/--numeric-version always win
557 | isDominantFlag oldMode -> ((oldMode, oldFlag), [])
558 | isDominantFlag newMode -> ((newMode, newFlag), [])
559 -- We need to accumulate eval flags like "-e foo -e bar"
560 (Right (Right (DoEval esOld)),
561 Right (Right (DoEval [eNew]))) ->
562 ((Right (Right (DoEval (eNew : esOld))), oldFlag),
564 -- Saying e.g. --interactive --interactive is OK
565 _ | oldFlag == newFlag -> ((oldMode, oldFlag), errs)
566 -- Otherwise, complain
567 _ -> let err = flagMismatchErr oldFlag newFlag
568 in ((oldMode, oldFlag), err : errs)
569 putCmdLineState (Just modeFlag', errs', flags')
570 where isDominantFlag f = isShowGhcUsageMode f ||
571 isShowGhciUsageMode f ||
572 isShowVersionMode f ||
573 isShowNumVersionMode f
575 flagMismatchErr :: String -> String -> String
576 flagMismatchErr oldFlag newFlag
577 = "cannot use `" ++ oldFlag ++ "' with `" ++ newFlag ++ "'"
579 addFlag :: String -> String -> EwM ModeM ()
580 addFlag s flag = liftEwM $ do
581 (m, e, flags') <- getCmdLineState
582 putCmdLineState (m, e, mkGeneralLocated loc s : flags')
583 where loc = "addFlag by " ++ flag ++ " on the commandline"
585 -- ----------------------------------------------------------------------------
588 doMake :: [(String,Maybe Phase)] -> Ghc ()
590 let (hs_srcs, non_hs_srcs) = partition haskellish srcs
592 haskellish (f,Nothing) =
593 looksLikeModuleName f || isHaskellSrcFilename f || '.' `notElem` f
594 haskellish (_,Just phase) =
595 phase `notElem` [As, Cc, CmmCpp, Cmm, StopLn]
597 hsc_env <- GHC.getSession
599 -- if we have no haskell sources from which to do a dependency
600 -- analysis, then just do one-shot compilation and/or linking.
601 -- This means that "ghc Foo.o Bar.o -o baz" links the program as
604 then oneShot hsc_env StopLn srcs >> GHC.printWarnings
607 o_files <- mapM (\x -> do
608 f <- compileFile hsc_env StopLn x
612 liftIO $ mapM_ (consIORef v_Ld_inputs) (reverse o_files)
614 targets <- mapM (uncurry GHC.guessTarget) hs_srcs
615 GHC.setTargets targets
616 ok_flag <- GHC.load LoadAllTargets
618 when (failed ok_flag) (liftIO $ exitWith (ExitFailure 1))
622 -- ---------------------------------------------------------------------------
625 doShowIface :: DynFlags -> FilePath -> IO ()
626 doShowIface dflags file = do
627 hsc_env <- newHscEnv defaultCallbacks dflags
628 showIface hsc_env file
630 -- ---------------------------------------------------------------------------
631 -- Various banners and verbosity output.
633 showBanner :: PostLoadMode -> DynFlags -> IO ()
634 showBanner _postLoadMode dflags = do
635 let verb = verbosity dflags
638 -- Show the GHCi banner
639 when (isInteractiveMode _postLoadMode && verb >= 1) $ putStrLn ghciWelcomeMsg
642 -- Display details of the configuration in verbose mode
644 do hPutStr stderr "Glasgow Haskell Compiler, Version "
645 hPutStr stderr cProjectVersion
646 hPutStr stderr ", for Haskell 98, stage "
647 hPutStr stderr cStage
648 hPutStr stderr " booted by GHC version "
649 hPutStrLn stderr cBooterVersion
651 -- We print out a Read-friendly string, but a prettier one than the
652 -- Show instance gives us
653 showInfo :: DynFlags -> IO ()
655 let sq x = " [" ++ x ++ "\n ]"
656 putStrLn $ sq $ concat $ intersperse "\n ," $ map (show . flatten) compilerInfo
657 where flatten (k, String v) = (k, v)
658 flatten (k, FromDynFlags f) = (k, f dflags)
660 showSupportedExtensions :: IO ()
661 showSupportedExtensions = mapM_ putStrLn supportedLanguagesAndExtensions
664 showVersion = putStrLn (cProjectName ++ ", version " ++ cProjectVersion)
666 showGhcUsage :: DynFlags -> IO ()
667 showGhcUsage = showUsage False
669 showGhciUsage :: DynFlags -> IO ()
670 showGhciUsage = showUsage True
672 showUsage :: Bool -> DynFlags -> IO ()
673 showUsage ghci dflags = do
674 let usage_path = if ghci then ghciUsagePath dflags
675 else ghcUsagePath dflags
676 usage <- readFile usage_path
680 dump ('$':'$':s) = putStr progName >> dump s
681 dump (c:s) = putChar c >> dump s
683 dumpFinalStats :: DynFlags -> IO ()
684 dumpFinalStats dflags =
685 when (dopt Opt_D_faststring_stats dflags) $ dumpFastStringStats dflags
687 dumpFastStringStats :: DynFlags -> IO ()
688 dumpFastStringStats dflags = do
689 buckets <- getFastStringTable
690 let (entries, longest, is_z, has_z) = countFS 0 0 0 0 buckets
691 msg = text "FastString stats:" $$
692 nest 4 (vcat [text "size: " <+> int (length buckets),
693 text "entries: " <+> int entries,
694 text "longest chain: " <+> int longest,
695 text "z-encoded: " <+> (is_z `pcntOf` entries),
696 text "has z-encoding: " <+> (has_z `pcntOf` entries)
698 -- we usually get more "has z-encoding" than "z-encoded", because
699 -- when we z-encode a string it might hash to the exact same string,
700 -- which will is not counted as "z-encoded". Only strings whose
701 -- Z-encoding is different from the original string are counted in
702 -- the "z-encoded" total.
705 x `pcntOf` y = int ((x * 100) `quot` y) <> char '%'
707 countFS :: Int -> Int -> Int -> Int -> [[FastString]] -> (Int, Int, Int, Int)
708 countFS entries longest is_z has_z [] = (entries, longest, is_z, has_z)
709 countFS entries longest is_z has_z (b:bs) =
712 longest' = max len longest
713 entries' = entries + len
714 is_zs = length (filter isZEncoded b)
715 has_zs = length (filter hasZEncoding b)
717 countFS entries' longest' (is_z + is_zs) (has_z + has_zs) bs
719 -- -----------------------------------------------------------------------------
723 ghc --abi-hash Data.Foo System.Bar
725 Generates a combined hash of the ABI for modules Data.Foo and
726 System.Bar. The modules must already be compiled, and appropriate -i
727 options may be necessary in order to find the .hi files.
729 This is used by Cabal for generating the InstalledPackageId for a
730 package. The InstalledPackageId must change when the visible ABI of
731 the package chagnes, so during registration Cabal calls ghc --abi-hash
732 to get a hash of the package's ABI.
735 abiHash :: [(String, Maybe Phase)] -> Ghc ()
737 hsc_env <- getSession
738 let dflags = hsc_dflags hsc_env
743 let modname = mkModuleName str
744 r <- findImportedModule hsc_env modname Nothing
746 Found _ m -> return m
747 _error -> ghcError $ CmdLineError $ showSDoc $
748 cannotFindInterface dflags modname r
750 mods <- mapM find_it (map fst strs)
752 let get_iface modl = loadUserInterface False (text "abiHash") modl
753 ifaces <- initIfaceCheck hsc_env $ mapM get_iface mods
755 bh <- openBinMem (3*1024) -- just less than a block
756 mapM_ (put_ bh . mi_mod_hash) ifaces
757 f <- fingerprintBinMem bh
759 putStrLn (showSDoc (ppr f))
761 -- -----------------------------------------------------------------------------
764 unknownFlagsErr :: [String] -> a
765 unknownFlagsErr fs = ghcError (UsageError ("unrecognised flags: " ++ unwords fs))