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