ghc: allow --show-options and --interactive together
[ghc.git] / ghc / Main.hs
1 {-# LANGUAGE CPP, NondecreasingIndentation #-}
2 {-# OPTIONS -fno-warn-incomplete-patterns -optc-DNON_POSIX_SOURCE #-}
3
4 -----------------------------------------------------------------------------
5 --
6 -- GHC Driver program
7 --
8 -- (c) The University of Glasgow 2005
9 --
10 -----------------------------------------------------------------------------
11
12 module Main (main) where
13
14 -- The official GHC API
15 import qualified GHC
16 import GHC ( -- DynFlags(..), HscTarget(..),
17 -- GhcMode(..), GhcLink(..),
18 Ghc, GhcMonad(..),
19 LoadHowMuch(..) )
20 import CmdLineParser
21
22 -- Implementations of the various modes (--show-iface, mkdependHS. etc.)
23 import LoadIface ( showIface )
24 import HscMain ( newHscEnv )
25 import DriverPipeline ( oneShot, compileFile )
26 import DriverMkDepend ( doMkDependHS )
27 #ifdef GHCI
28 import InteractiveUI ( interactiveUI, ghciWelcomeMsg, defaultGhciSettings )
29 #endif
30
31
32 -- Various other random stuff that we need
33 import Config
34 import Constants
35 import HscTypes
36 import Packages ( pprPackages, pprPackagesSimple, pprModuleMap )
37 import DriverPhases
38 import BasicTypes ( failed )
39 import StaticFlags
40 import DynFlags
41 import ErrUtils
42 import FastString
43 import Outputable
44 import SrcLoc
45 import Util
46 import Panic
47 import MonadUtils ( liftIO )
48
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 )
55
56 -- Standard Haskell libraries
57 import System.IO
58 import System.Environment
59 import System.Exit
60 import System.FilePath
61 import Control.Monad
62 import Data.Char
63 import Data.List
64 import Data.Maybe
65
66 -----------------------------------------------------------------------------
67 -- ToDo:
68
69 -- time commands when run with -v
70 -- user ways
71 -- Win32 support: proper signal handling
72 -- reading the package configuration file is too slow
73 -- -K<size>
74
75 -----------------------------------------------------------------------------
76 -- GHC's command-line interface
77
78 main :: IO ()
79 main = do
80 initGCStatistics -- See Note [-Bsymbolic and hooks]
81 hSetBuffering stdout LineBuffering
82 hSetBuffering stderr LineBuffering
83 GHC.defaultErrorHandler defaultFatalMessager defaultFlushOut $ do
84 -- 1. extract the -B flag from the args
85 argv0 <- getArgs
86
87 let (minusB_args, argv1) = partition ("-B" `isPrefixOf`) argv0
88 mbMinusB | null minusB_args = Nothing
89 | otherwise = Just (drop 2 (last minusB_args))
90
91 let argv1' = map (mkGeneralLocated "on the commandline") argv1
92 (argv2, staticFlagWarnings) <- parseStaticFlags argv1'
93
94 -- 2. Parse the "mode" flags (--make, --interactive etc.)
95 (mode, argv3, modeFlagWarnings) <- parseModeFlags argv2
96
97 let flagWarnings = staticFlagWarnings ++ modeFlagWarnings
98
99 -- If all we want to do is something like showing the version number
100 -- then do it now, before we start a GHC session etc. This makes
101 -- getting basic information much more resilient.
102
103 -- In particular, if we wait until later before giving the version
104 -- number then bootstrapping gets confused, as it tries to find out
105 -- what version of GHC it's using before package.conf exists, so
106 -- starting the session fails.
107 case mode of
108 Left preStartupMode ->
109 do case preStartupMode of
110 ShowSupportedExtensions -> showSupportedExtensions
111 ShowVersion -> showVersion
112 ShowNumVersion -> putStrLn cProjectVersion
113 ShowOptions isInteractive -> showOptions isInteractive
114 Right postStartupMode ->
115 -- start our GHC session
116 GHC.runGhc mbMinusB $ do
117
118 dflags <- GHC.getSessionDynFlags
119
120 case postStartupMode of
121 Left preLoadMode ->
122 liftIO $ do
123 case preLoadMode of
124 ShowInfo -> showInfo dflags
125 ShowGhcUsage -> showGhcUsage dflags
126 ShowGhciUsage -> showGhciUsage dflags
127 PrintWithDynFlags f -> putStrLn (f dflags)
128 Right postLoadMode ->
129 main' postLoadMode dflags argv3 flagWarnings
130
131 main' :: PostLoadMode -> DynFlags -> [Located String] -> [Located String]
132 -> Ghc ()
133 main' postLoadMode dflags0 args flagWarnings = do
134 -- set the default GhcMode, HscTarget and GhcLink. The HscTarget
135 -- can be further adjusted on a module by module basis, using only
136 -- the -fvia-C and -fasm flags. If the default HscTarget is not
137 -- HscC or HscAsm, -fvia-C and -fasm have no effect.
138 let dflt_target = hscTarget dflags0
139 (mode, lang, link)
140 = case postLoadMode of
141 DoInteractive -> (CompManager, HscInterpreted, LinkInMemory)
142 DoEval _ -> (CompManager, HscInterpreted, LinkInMemory)
143 DoMake -> (CompManager, dflt_target, LinkBinary)
144 DoMkDependHS -> (MkDepend, dflt_target, LinkBinary)
145 DoAbiHash -> (OneShot, dflt_target, LinkBinary)
146 _ -> (OneShot, dflt_target, LinkBinary)
147
148 let dflags1 = case lang of
149 HscInterpreted ->
150 let platform = targetPlatform dflags0
151 dflags0a = updateWays $ dflags0 { ways = interpWays }
152 dflags0b = foldl gopt_set dflags0a
153 $ concatMap (wayGeneralFlags platform)
154 interpWays
155 dflags0c = foldl gopt_unset dflags0b
156 $ concatMap (wayUnsetGeneralFlags platform)
157 interpWays
158 in dflags0c
159 _ ->
160 dflags0
161 dflags2 = dflags1{ ghcMode = mode,
162 hscTarget = lang,
163 ghcLink = link,
164 verbosity = case postLoadMode of
165 DoEval _ -> 0
166 _other -> 1
167 }
168
169 -- turn on -fimplicit-import-qualified for GHCi now, so that it
170 -- can be overriden from the command-line
171 -- XXX: this should really be in the interactive DynFlags, but
172 -- we don't set that until later in interactiveUI
173 dflags3 | DoInteractive <- postLoadMode = imp_qual_enabled
174 | DoEval _ <- postLoadMode = imp_qual_enabled
175 | otherwise = dflags2
176 where imp_qual_enabled = dflags2 `gopt_set` Opt_ImplicitImportQualified
177
178 -- The rest of the arguments are "dynamic"
179 -- Leftover ones are presumably files
180 (dflags4, fileish_args, dynamicFlagWarnings) <- GHC.parseDynamicFlags dflags3 args
181
182 GHC.prettyPrintGhcErrors dflags4 $ do
183
184 let flagWarnings' = flagWarnings ++ dynamicFlagWarnings
185
186 handleSourceError (\e -> do
187 GHC.printException e
188 liftIO $ exitWith (ExitFailure 1)) $ do
189 liftIO $ handleFlagWarnings dflags4 flagWarnings'
190
191 -- make sure we clean up after ourselves
192 GHC.defaultCleanupHandler dflags4 $ do
193
194 liftIO $ showBanner postLoadMode dflags4
195
196 let
197 -- To simplify the handling of filepaths, we normalise all filepaths right
198 -- away - e.g., for win32 platforms, backslashes are converted
199 -- into forward slashes.
200 normal_fileish_paths = map (normalise . unLoc) fileish_args
201 (srcs, objs) = partition_args normal_fileish_paths [] []
202
203 dflags5 = dflags4 { ldInputs = map (FileOption "") objs
204 ++ ldInputs dflags4 }
205
206 -- we've finished manipulating the DynFlags, update the session
207 _ <- GHC.setSessionDynFlags dflags5
208 dflags6 <- GHC.getSessionDynFlags
209 hsc_env <- GHC.getSession
210
211 ---------------- Display configuration -----------
212 case verbosity dflags6 of
213 v | v == 4 -> liftIO $ dumpPackagesSimple dflags6
214 | v >= 5 -> liftIO $ dumpPackages dflags6
215 | otherwise -> return ()
216
217 when (verbosity dflags6 >= 3) $ do
218 liftIO $ hPutStrLn stderr ("Hsc static flags: " ++ unwords staticFlags)
219
220
221 when (dopt Opt_D_dump_mod_map dflags6) . liftIO $
222 printInfoForUser (dflags6 { pprCols = 200 })
223 (pkgQual dflags6) (pprModuleMap dflags6)
224
225 ---------------- Final sanity checking -----------
226 liftIO $ checkOptions postLoadMode dflags6 srcs objs
227
228 ---------------- Do the business -----------
229 handleSourceError (\e -> do
230 GHC.printException e
231 liftIO $ exitWith (ExitFailure 1)) $ do
232 case postLoadMode of
233 ShowInterface f -> liftIO $ doShowIface dflags6 f
234 DoMake -> doMake srcs
235 DoMkDependHS -> doMkDependHS (map fst srcs)
236 StopBefore p -> liftIO (oneShot hsc_env p srcs)
237 DoInteractive -> ghciUI srcs Nothing
238 DoEval exprs -> ghciUI srcs $ Just $ reverse exprs
239 DoAbiHash -> abiHash (map fst srcs)
240 ShowPackages -> liftIO $ showPackages dflags6
241
242 liftIO $ dumpFinalStats dflags6
243
244 ghciUI :: [(FilePath, Maybe Phase)] -> Maybe [String] -> Ghc ()
245 #ifndef GHCI
246 ghciUI _ _ = throwGhcException (CmdLineError "not built for interactive use")
247 #else
248 ghciUI = interactiveUI defaultGhciSettings
249 #endif
250
251 -- -----------------------------------------------------------------------------
252 -- Splitting arguments into source files and object files. This is where we
253 -- interpret the -x <suffix> option, and attach a (Maybe Phase) to each source
254 -- file indicating the phase specified by the -x option in force, if any.
255
256 partition_args :: [String] -> [(String, Maybe Phase)] -> [String]
257 -> ([(String, Maybe Phase)], [String])
258 partition_args [] srcs objs = (reverse srcs, reverse objs)
259 partition_args ("-x":suff:args) srcs objs
260 | "none" <- suff = partition_args args srcs objs
261 | StopLn <- phase = partition_args args srcs (slurp ++ objs)
262 | otherwise = partition_args rest (these_srcs ++ srcs) objs
263 where phase = startPhase suff
264 (slurp,rest) = break (== "-x") args
265 these_srcs = zip slurp (repeat (Just phase))
266 partition_args (arg:args) srcs objs
267 | looks_like_an_input arg = partition_args args ((arg,Nothing):srcs) objs
268 | otherwise = partition_args args srcs (arg:objs)
269
270 {-
271 We split out the object files (.o, .dll) and add them
272 to ldInputs for use by the linker.
273
274 The following things should be considered compilation manager inputs:
275
276 - haskell source files (strings ending in .hs, .lhs or other
277 haskellish extension),
278
279 - module names (not forgetting hierarchical module names),
280
281 - things beginning with '-' are flags that were not recognised by
282 the flag parser, and we want them to generate errors later in
283 checkOptions, so we class them as source files (#5921)
284
285 - and finally we consider everything not containing a '.' to be
286 a comp manager input, as shorthand for a .hs or .lhs filename.
287
288 Everything else is considered to be a linker object, and passed
289 straight through to the linker.
290 -}
291 looks_like_an_input :: String -> Bool
292 looks_like_an_input m = isSourceFilename m
293 || looksLikeModuleName m
294 || "-" `isPrefixOf` m
295 || '.' `notElem` m
296
297 -- -----------------------------------------------------------------------------
298 -- Option sanity checks
299
300 -- | Ensure sanity of options.
301 --
302 -- Throws 'UsageError' or 'CmdLineError' if not.
303 checkOptions :: PostLoadMode -> DynFlags -> [(String,Maybe Phase)] -> [String] -> IO ()
304 -- Final sanity checking before kicking off a compilation (pipeline).
305 checkOptions mode dflags srcs objs = do
306 -- Complain about any unknown flags
307 let unknown_opts = [ f | (f@('-':_), _) <- srcs ]
308 when (notNull unknown_opts) (unknownFlagsErr unknown_opts)
309
310 when (notNull (filter wayRTSOnly (ways dflags))
311 && isInterpretiveMode mode) $
312 hPutStrLn stderr ("Warning: -debug, -threaded and -ticky are ignored by GHCi")
313
314 -- -prof and --interactive are not a good combination
315 when ((filter (not . wayRTSOnly) (ways dflags) /= interpWays)
316 && isInterpretiveMode mode) $
317 do throwGhcException (UsageError
318 "--interactive can't be used with -prof or -unreg.")
319 -- -ohi sanity check
320 if (isJust (outputHi dflags) &&
321 (isCompManagerMode mode || srcs `lengthExceeds` 1))
322 then throwGhcException (UsageError "-ohi can only be used when compiling a single source file")
323 else do
324
325 -- -o sanity checking
326 if (srcs `lengthExceeds` 1 && isJust (outputFile dflags)
327 && not (isLinkMode mode))
328 then throwGhcException (UsageError "can't apply -o to multiple source files")
329 else do
330
331 let not_linking = not (isLinkMode mode) || isNoLink (ghcLink dflags)
332
333 when (not_linking && not (null objs)) $
334 hPutStrLn stderr ("Warning: the following files would be used as linker inputs, but linking is not being done: " ++ unwords objs)
335
336 -- Check that there are some input files
337 -- (except in the interactive case)
338 if null srcs && (null objs || not_linking) && needsInputsMode mode
339 then throwGhcException (UsageError "no input files")
340 else do
341
342 -- Verify that output files point somewhere sensible.
343 verifyOutputFiles dflags
344
345
346 -- Compiler output options
347
348 -- Called to verify that the output files point somewhere valid.
349 --
350 -- The assumption is that the directory portion of these output
351 -- options will have to exist by the time 'verifyOutputFiles'
352 -- is invoked.
353 --
354 -- We create the directories for -odir, -hidir, -outputdir etc. ourselves if
355 -- they don't exist, so don't check for those here (#2278).
356 verifyOutputFiles :: DynFlags -> IO ()
357 verifyOutputFiles dflags = do
358 let ofile = outputFile dflags
359 when (isJust ofile) $ do
360 let fn = fromJust ofile
361 flg <- doesDirNameExist fn
362 when (not flg) (nonExistentDir "-o" fn)
363 let ohi = outputHi dflags
364 when (isJust ohi) $ do
365 let hi = fromJust ohi
366 flg <- doesDirNameExist hi
367 when (not flg) (nonExistentDir "-ohi" hi)
368 where
369 nonExistentDir flg dir =
370 throwGhcException (CmdLineError ("error: directory portion of " ++
371 show dir ++ " does not exist (used with " ++
372 show flg ++ " option.)"))
373
374 -----------------------------------------------------------------------------
375 -- GHC modes of operation
376
377 type Mode = Either PreStartupMode PostStartupMode
378 type PostStartupMode = Either PreLoadMode PostLoadMode
379
380 data PreStartupMode
381 = ShowVersion -- ghc -V/--version
382 | ShowNumVersion -- ghc --numeric-version
383 | ShowSupportedExtensions -- ghc --supported-extensions
384 | ShowOptions Bool {- isInteractive -} -- ghc --show-options
385
386 showVersionMode, showNumVersionMode, showSupportedExtensionsMode, showOptionsMode :: Mode
387 showVersionMode = mkPreStartupMode ShowVersion
388 showNumVersionMode = mkPreStartupMode ShowNumVersion
389 showSupportedExtensionsMode = mkPreStartupMode ShowSupportedExtensions
390 showOptionsMode = mkPreStartupMode (ShowOptions False)
391
392 mkPreStartupMode :: PreStartupMode -> Mode
393 mkPreStartupMode = Left
394
395 isShowVersionMode :: Mode -> Bool
396 isShowVersionMode (Left ShowVersion) = True
397 isShowVersionMode _ = False
398
399 isShowNumVersionMode :: Mode -> Bool
400 isShowNumVersionMode (Left ShowNumVersion) = True
401 isShowNumVersionMode _ = False
402
403 data PreLoadMode
404 = ShowGhcUsage -- ghc -?
405 | ShowGhciUsage -- ghci -?
406 | ShowInfo -- ghc --info
407 | PrintWithDynFlags (DynFlags -> String) -- ghc --print-foo
408
409 showGhcUsageMode, showGhciUsageMode, showInfoMode :: Mode
410 showGhcUsageMode = mkPreLoadMode ShowGhcUsage
411 showGhciUsageMode = mkPreLoadMode ShowGhciUsage
412 showInfoMode = mkPreLoadMode ShowInfo
413
414 printSetting :: String -> Mode
415 printSetting k = mkPreLoadMode (PrintWithDynFlags f)
416 where f dflags = fromMaybe (panic ("Setting not found: " ++ show k))
417 $ lookup k (compilerInfo dflags)
418
419 mkPreLoadMode :: PreLoadMode -> Mode
420 mkPreLoadMode = Right . Left
421
422 isShowGhcUsageMode :: Mode -> Bool
423 isShowGhcUsageMode (Right (Left ShowGhcUsage)) = True
424 isShowGhcUsageMode _ = False
425
426 isShowGhciUsageMode :: Mode -> Bool
427 isShowGhciUsageMode (Right (Left ShowGhciUsage)) = True
428 isShowGhciUsageMode _ = False
429
430 data PostLoadMode
431 = ShowInterface FilePath -- ghc --show-iface
432 | DoMkDependHS -- ghc -M
433 | StopBefore Phase -- ghc -E | -C | -S
434 -- StopBefore StopLn is the default
435 | DoMake -- ghc --make
436 | DoInteractive -- ghc --interactive
437 | DoEval [String] -- ghc -e foo -e bar => DoEval ["bar", "foo"]
438 | DoAbiHash -- ghc --abi-hash
439 | ShowPackages -- ghc --show-packages
440
441 doMkDependHSMode, doMakeMode, doInteractiveMode,
442 doAbiHashMode, showPackagesMode :: Mode
443 doMkDependHSMode = mkPostLoadMode DoMkDependHS
444 doMakeMode = mkPostLoadMode DoMake
445 doInteractiveMode = mkPostLoadMode DoInteractive
446 doAbiHashMode = mkPostLoadMode DoAbiHash
447 showPackagesMode = mkPostLoadMode ShowPackages
448
449 showInterfaceMode :: FilePath -> Mode
450 showInterfaceMode fp = mkPostLoadMode (ShowInterface fp)
451
452 stopBeforeMode :: Phase -> Mode
453 stopBeforeMode phase = mkPostLoadMode (StopBefore phase)
454
455 doEvalMode :: String -> Mode
456 doEvalMode str = mkPostLoadMode (DoEval [str])
457
458 mkPostLoadMode :: PostLoadMode -> Mode
459 mkPostLoadMode = Right . Right
460
461 isDoInteractiveMode :: Mode -> Bool
462 isDoInteractiveMode (Right (Right DoInteractive)) = True
463 isDoInteractiveMode _ = False
464
465 isStopLnMode :: Mode -> Bool
466 isStopLnMode (Right (Right (StopBefore StopLn))) = True
467 isStopLnMode _ = False
468
469 isDoMakeMode :: Mode -> Bool
470 isDoMakeMode (Right (Right DoMake)) = True
471 isDoMakeMode _ = False
472
473 #ifdef GHCI
474 isInteractiveMode :: PostLoadMode -> Bool
475 isInteractiveMode DoInteractive = True
476 isInteractiveMode _ = False
477 #endif
478
479 -- isInterpretiveMode: byte-code compiler involved
480 isInterpretiveMode :: PostLoadMode -> Bool
481 isInterpretiveMode DoInteractive = True
482 isInterpretiveMode (DoEval _) = True
483 isInterpretiveMode _ = False
484
485 needsInputsMode :: PostLoadMode -> Bool
486 needsInputsMode DoMkDependHS = True
487 needsInputsMode (StopBefore _) = True
488 needsInputsMode DoMake = True
489 needsInputsMode _ = False
490
491 -- True if we are going to attempt to link in this mode.
492 -- (we might not actually link, depending on the GhcLink flag)
493 isLinkMode :: PostLoadMode -> Bool
494 isLinkMode (StopBefore StopLn) = True
495 isLinkMode DoMake = True
496 isLinkMode DoInteractive = True
497 isLinkMode (DoEval _) = True
498 isLinkMode _ = False
499
500 isCompManagerMode :: PostLoadMode -> Bool
501 isCompManagerMode DoMake = True
502 isCompManagerMode DoInteractive = True
503 isCompManagerMode (DoEval _) = True
504 isCompManagerMode _ = False
505
506 -- -----------------------------------------------------------------------------
507 -- Parsing the mode flag
508
509 parseModeFlags :: [Located String]
510 -> IO (Mode,
511 [Located String],
512 [Located String])
513 parseModeFlags args = do
514 let ((leftover, errs1, warns), (mModeFlag, errs2, flags')) =
515 runCmdLine (processArgs mode_flags args)
516 (Nothing, [], [])
517 mode = case mModeFlag of
518 Nothing -> doMakeMode
519 Just (m, _) -> m
520 errs = errs1 ++ map (mkGeneralLocated "on the commandline") errs2
521 when (not (null errs)) $ throwGhcException $ errorsToGhcException errs
522 return (mode, flags' ++ leftover, warns)
523
524 type ModeM = CmdLineP (Maybe (Mode, String), [String], [Located String])
525 -- mode flags sometimes give rise to new DynFlags (eg. -C, see below)
526 -- so we collect the new ones and return them.
527
528 mode_flags :: [Flag ModeM]
529 mode_flags =
530 [ ------- help / version ----------------------------------------------
531 defFlag "?" (PassFlag (setMode showGhcUsageMode))
532 , defFlag "-help" (PassFlag (setMode showGhcUsageMode))
533 , defFlag "V" (PassFlag (setMode showVersionMode))
534 , defFlag "-version" (PassFlag (setMode showVersionMode))
535 , defFlag "-numeric-version" (PassFlag (setMode showNumVersionMode))
536 , defFlag "-info" (PassFlag (setMode showInfoMode))
537 , defFlag "-show-options" (PassFlag (setMode showOptionsMode))
538 , defFlag "-supported-languages" (PassFlag (setMode showSupportedExtensionsMode))
539 , defFlag "-supported-extensions" (PassFlag (setMode showSupportedExtensionsMode))
540 , defFlag "-show-packages" (PassFlag (setMode showPackagesMode))
541 ] ++
542 [ defFlag k' (PassFlag (setMode (printSetting k)))
543 | k <- ["Project version",
544 "Booter version",
545 "Stage",
546 "Build platform",
547 "Host platform",
548 "Target platform",
549 "Have interpreter",
550 "Object splitting supported",
551 "Have native code generator",
552 "Support SMP",
553 "Unregisterised",
554 "Tables next to code",
555 "RTS ways",
556 "Leading underscore",
557 "Debug on",
558 "LibDir",
559 "Global Package DB",
560 "C compiler flags",
561 "Gcc Linker flags",
562 "Ld Linker flags"],
563 let k' = "-print-" ++ map (replaceSpace . toLower) k
564 replaceSpace ' ' = '-'
565 replaceSpace c = c
566 ] ++
567 ------- interfaces ----------------------------------------------------
568 [ defFlag "-show-iface" (HasArg (\f -> setMode (showInterfaceMode f)
569 "--show-iface"))
570
571 ------- primary modes ------------------------------------------------
572 , defFlag "c" (PassFlag (\f -> do setMode (stopBeforeMode StopLn) f
573 addFlag "-no-link" f))
574 , defFlag "M" (PassFlag (setMode doMkDependHSMode))
575 , defFlag "E" (PassFlag (setMode (stopBeforeMode anyHsc)))
576 , defFlag "C" (PassFlag (setMode (stopBeforeMode HCc)))
577 , defFlag "S" (PassFlag (setMode (stopBeforeMode (As False))))
578 , defFlag "-make" (PassFlag (setMode doMakeMode))
579 , defFlag "-interactive" (PassFlag (setMode doInteractiveMode))
580 , defFlag "-abi-hash" (PassFlag (setMode doAbiHashMode))
581 , defFlag "e" (SepArg (\s -> setMode (doEvalMode s) "-e"))
582 ]
583
584 setMode :: Mode -> String -> EwM ModeM ()
585 setMode newMode newFlag = liftEwM $ do
586 (mModeFlag, errs, flags') <- getCmdLineState
587 let (modeFlag', errs') =
588 case mModeFlag of
589 Nothing -> ((newMode, newFlag), errs)
590 Just (oldMode, oldFlag) ->
591 case (oldMode, newMode) of
592 -- -c/--make are allowed together, and mean --make -no-link
593 _ | isStopLnMode oldMode && isDoMakeMode newMode
594 || isStopLnMode newMode && isDoMakeMode oldMode ->
595 ((doMakeMode, "--make"), [])
596
597 -- If we have both --help and --interactive then we
598 -- want showGhciUsage
599 _ | isShowGhcUsageMode oldMode &&
600 isDoInteractiveMode newMode ->
601 ((showGhciUsageMode, oldFlag), [])
602 | isShowGhcUsageMode newMode &&
603 isDoInteractiveMode oldMode ->
604 ((showGhciUsageMode, newFlag), [])
605 -- Otherwise, --help/--version/--numeric-version always win
606 | isDominantFlag oldMode -> ((oldMode, oldFlag), [])
607 | isDominantFlag newMode -> ((newMode, newFlag), [])
608 -- We need to accumulate eval flags like "-e foo -e bar"
609 (Right (Right (DoEval esOld)),
610 Right (Right (DoEval [eNew]))) ->
611 ((Right (Right (DoEval (eNew : esOld))), oldFlag),
612 errs)
613 -- Saying e.g. --interactive --interactive is OK
614 _ | oldFlag == newFlag -> ((oldMode, oldFlag), errs)
615
616 -- --interactive and --show-options are used together
617 (Right (Right DoInteractive), Left (ShowOptions _)) ->
618 ((Left (ShowOptions True),
619 "--interactive --show-options"), errs)
620 (Left (ShowOptions _), (Right (Right DoInteractive))) ->
621 ((Left (ShowOptions True),
622 "--show-options --interactive"), errs)
623 -- Otherwise, complain
624 _ -> let err = flagMismatchErr oldFlag newFlag
625 in ((oldMode, oldFlag), err : errs)
626 putCmdLineState (Just modeFlag', errs', flags')
627 where isDominantFlag f = isShowGhcUsageMode f ||
628 isShowGhciUsageMode f ||
629 isShowVersionMode f ||
630 isShowNumVersionMode f
631
632 flagMismatchErr :: String -> String -> String
633 flagMismatchErr oldFlag newFlag
634 = "cannot use `" ++ oldFlag ++ "' with `" ++ newFlag ++ "'"
635
636 addFlag :: String -> String -> EwM ModeM ()
637 addFlag s flag = liftEwM $ do
638 (m, e, flags') <- getCmdLineState
639 putCmdLineState (m, e, mkGeneralLocated loc s : flags')
640 where loc = "addFlag by " ++ flag ++ " on the commandline"
641
642 -- ----------------------------------------------------------------------------
643 -- Run --make mode
644
645 doMake :: [(String,Maybe Phase)] -> Ghc ()
646 doMake srcs = do
647 let (hs_srcs, non_hs_srcs) = partition haskellish srcs
648
649 haskellish (f,Nothing) =
650 looksLikeModuleName f || isHaskellUserSrcFilename f || '.' `notElem` f
651 haskellish (_,Just phase) =
652 phase `notElem` [ As True, As False, Cc, Cobjc, Cobjcpp, CmmCpp, Cmm
653 , StopLn]
654
655 hsc_env <- GHC.getSession
656
657 -- if we have no haskell sources from which to do a dependency
658 -- analysis, then just do one-shot compilation and/or linking.
659 -- This means that "ghc Foo.o Bar.o -o baz" links the program as
660 -- we expect.
661 if (null hs_srcs)
662 then liftIO (oneShot hsc_env StopLn srcs)
663 else do
664
665 o_files <- mapM (\x -> liftIO $ compileFile hsc_env StopLn x)
666 non_hs_srcs
667 dflags <- GHC.getSessionDynFlags
668 let dflags' = dflags { ldInputs = map (FileOption "") o_files
669 ++ ldInputs dflags }
670 _ <- GHC.setSessionDynFlags dflags'
671
672 targets <- mapM (uncurry GHC.guessTarget) hs_srcs
673 GHC.setTargets targets
674 ok_flag <- GHC.load LoadAllTargets
675
676 when (failed ok_flag) (liftIO $ exitWith (ExitFailure 1))
677 return ()
678
679
680 -- ---------------------------------------------------------------------------
681 -- --show-iface mode
682
683 doShowIface :: DynFlags -> FilePath -> IO ()
684 doShowIface dflags file = do
685 hsc_env <- newHscEnv dflags
686 showIface hsc_env file
687
688 -- ---------------------------------------------------------------------------
689 -- Various banners and verbosity output.
690
691 showBanner :: PostLoadMode -> DynFlags -> IO ()
692 showBanner _postLoadMode dflags = do
693 let verb = verbosity dflags
694
695 #ifdef GHCI
696 -- Show the GHCi banner
697 when (isInteractiveMode _postLoadMode && verb >= 1) $ putStrLn ghciWelcomeMsg
698 #endif
699
700 -- Display details of the configuration in verbose mode
701 when (verb >= 2) $
702 do hPutStr stderr "Glasgow Haskell Compiler, Version "
703 hPutStr stderr cProjectVersion
704 hPutStr stderr ", stage "
705 hPutStr stderr cStage
706 hPutStr stderr " booted by GHC version "
707 hPutStrLn stderr cBooterVersion
708
709 -- We print out a Read-friendly string, but a prettier one than the
710 -- Show instance gives us
711 showInfo :: DynFlags -> IO ()
712 showInfo dflags = do
713 let sq x = " [" ++ x ++ "\n ]"
714 putStrLn $ sq $ intercalate "\n ," $ map show $ compilerInfo dflags
715
716 showSupportedExtensions :: IO ()
717 showSupportedExtensions = mapM_ putStrLn supportedLanguagesAndExtensions
718
719 showVersion :: IO ()
720 showVersion = putStrLn (cProjectName ++ ", version " ++ cProjectVersion)
721
722 showOptions :: Bool -> IO ()
723 showOptions isInteractive = putStr (unlines availableOptions)
724 where
725 availableOptions = concat [
726 flagsForCompletion isInteractive,
727 map ('-':) (concat [
728 getFlagNames mode_flags
729 , (filterUnwantedStatic . getFlagNames $ flagsStatic)
730 , flagsStaticNames
731 ])
732 ]
733 getFlagNames opts = map flagName opts
734 -- this is a hack to get rid of two unwanted entries that get listed
735 -- as static flags. Hopefully this hack will disappear one day together
736 -- with static flags
737 filterUnwantedStatic = filter (`notElem`["f", "fno-"])
738
739 showGhcUsage :: DynFlags -> IO ()
740 showGhcUsage = showUsage False
741
742 showGhciUsage :: DynFlags -> IO ()
743 showGhciUsage = showUsage True
744
745 showUsage :: Bool -> DynFlags -> IO ()
746 showUsage ghci dflags = do
747 let usage_path = if ghci then ghciUsagePath dflags
748 else ghcUsagePath dflags
749 usage <- readFile usage_path
750 dump usage
751 where
752 dump "" = return ()
753 dump ('$':'$':s) = putStr progName >> dump s
754 dump (c:s) = putChar c >> dump s
755
756 dumpFinalStats :: DynFlags -> IO ()
757 dumpFinalStats dflags =
758 when (gopt Opt_D_faststring_stats dflags) $ dumpFastStringStats dflags
759
760 dumpFastStringStats :: DynFlags -> IO ()
761 dumpFastStringStats dflags = do
762 buckets <- getFastStringTable
763 let (entries, longest, has_z) = countFS 0 0 0 buckets
764 msg = text "FastString stats:" $$
765 nest 4 (vcat [text "size: " <+> int (length buckets),
766 text "entries: " <+> int entries,
767 text "longest chain: " <+> int longest,
768 text "has z-encoding: " <+> (has_z `pcntOf` entries)
769 ])
770 -- we usually get more "has z-encoding" than "z-encoded", because
771 -- when we z-encode a string it might hash to the exact same string,
772 -- which will is not counted as "z-encoded". Only strings whose
773 -- Z-encoding is different from the original string are counted in
774 -- the "z-encoded" total.
775 putMsg dflags msg
776 where
777 x `pcntOf` y = int ((x * 100) `quot` y) <> char '%'
778
779 countFS :: Int -> Int -> Int -> [[FastString]] -> (Int, Int, Int)
780 countFS entries longest has_z [] = (entries, longest, has_z)
781 countFS entries longest has_z (b:bs) =
782 let
783 len = length b
784 longest' = max len longest
785 entries' = entries + len
786 has_zs = length (filter hasZEncoding b)
787 in
788 countFS entries' longest' (has_z + has_zs) bs
789
790 showPackages, dumpPackages, dumpPackagesSimple :: DynFlags -> IO ()
791 showPackages dflags = putStrLn (showSDoc dflags (pprPackages dflags))
792 dumpPackages dflags = putMsg dflags (pprPackages dflags)
793 dumpPackagesSimple dflags = putMsg dflags (pprPackagesSimple dflags)
794
795 -- -----------------------------------------------------------------------------
796 -- ABI hash support
797
798 {-
799 ghc --abi-hash Data.Foo System.Bar
800
801 Generates a combined hash of the ABI for modules Data.Foo and
802 System.Bar. The modules must already be compiled, and appropriate -i
803 options may be necessary in order to find the .hi files.
804
805 This is used by Cabal for generating the InstalledPackageId for a
806 package. The InstalledPackageId must change when the visible ABI of
807 the package chagnes, so during registration Cabal calls ghc --abi-hash
808 to get a hash of the package's ABI.
809 -}
810
811 -- | Print ABI hash of input modules.
812 --
813 -- The resulting hash is the MD5 of the GHC version used (Trac #5328,
814 -- see 'hiVersion') and of the existing ABI hash from each module (see
815 -- 'mi_mod_hash').
816 abiHash :: [String] -- ^ List of module names
817 -> Ghc ()
818 abiHash strs = do
819 hsc_env <- getSession
820 let dflags = hsc_dflags hsc_env
821
822 liftIO $ do
823
824 let find_it str = do
825 let modname = mkModuleName str
826 r <- findImportedModule hsc_env modname Nothing
827 case r of
828 Found _ m -> return m
829 _error -> throwGhcException $ CmdLineError $ showSDoc dflags $
830 cannotFindInterface dflags modname r
831
832 mods <- mapM find_it strs
833
834 let get_iface modl = loadUserInterface False (text "abiHash") modl
835 ifaces <- initIfaceCheck hsc_env $ mapM get_iface mods
836
837 bh <- openBinMem (3*1024) -- just less than a block
838 put_ bh hiVersion
839 -- package hashes change when the compiler version changes (for now)
840 -- see #5328
841 mapM_ (put_ bh . mi_mod_hash) ifaces
842 f <- fingerprintBinMem bh
843
844 putStrLn (showPpr dflags f)
845
846 -- -----------------------------------------------------------------------------
847 -- Util
848
849 unknownFlagsErr :: [String] -> a
850 unknownFlagsErr fs = throwGhcException $ UsageError $ concatMap oneError fs
851 where
852 oneError f =
853 "unrecognised flag: " ++ f ++ "\n" ++
854 (case fuzzyMatch f (nub allFlags) of
855 [] -> ""
856 suggs -> "did you mean one of:\n" ++ unlines (map (" " ++) suggs))
857
858 {- Note [-Bsymbolic and hooks]
859 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
860 -Bsymbolic is a flag that prevents the binding of references to global
861 symbols to symbols outside the shared library being compiled (see `man
862 ld`). When dynamically linking, we don't use -Bsymbolic on the RTS
863 package: that is because we want hooks to be overridden by the user,
864 we don't want to constrain them to the RTS package.
865
866 Unfortunately this seems to have broken somehow on OS X: as a result,
867 defaultHooks (in hschooks.c) is not called, which does not initialize
868 the GC stats. As a result, this breaks things like `:set +s` in GHCi
869 (#8754). As a hacky workaround, we instead call 'defaultHooks'
870 directly to initalize the flags in the RTS.
871
872 A byproduct of this, I believe, is that hooks are likely broken on OS
873 X when dynamically linking. But this probably doesn't affect most
874 people since we're linking GHC dynamically, but most things themselves
875 link statically.
876 -}
877
878 foreign import ccall safe "initGCStatistics"
879 initGCStatistics :: IO ()