Separate language option handling into 2 phases
[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 = do
80    hSetBuffering stdout NoBuffering
81    GHC.defaultErrorHandler defaultDynFlags $ do
82     -- 1. extract the -B flag from the args
83     argv0 <- getArgs
84
85     let (minusB_args, argv1) = partition ("-B" `isPrefixOf`) argv0
86         mbMinusB | null minusB_args = Nothing
87                  | otherwise = Just (drop 2 (last minusB_args))
88
89     let argv1' = map (mkGeneralLocated "on the commandline") argv1
90     (argv2, staticFlagWarnings) <- parseStaticFlags argv1'
91
92     -- 2. Parse the "mode" flags (--make, --interactive etc.)
93     (mode, argv3, modeFlagWarnings) <- parseModeFlags argv2
94
95     let flagWarnings = staticFlagWarnings ++ modeFlagWarnings
96
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.
100
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.
105     case mode of
106         Left preStartupMode ->
107             do case preStartupMode of
108                    ShowSupportedLanguages  -> showSupportedLanguages
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
115
116             dflags <- GHC.getSessionDynFlags
117
118             case postStartupMode of
119                 Left preLoadMode ->
120                     liftIO $ do
121                         case preLoadMode 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
128
129 main' :: PostLoadMode -> DynFlags -> [Located String] -> [Located String]
130       -> Ghc ()
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
137       (mode, lang, link)
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)
145
146   let dflags1 = dflags0{ ghcMode   = mode,
147                          hscTarget = lang,
148                          ghcLink   = link,
149                          -- leave out hscOutName for now
150                          hscOutName = panic "Main.main:hscOutName not set",
151                          verbosity = case postLoadMode of
152                                          DoEval _ -> 0
153                                          _other   -> 1
154                         }
155
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
162
163         -- The rest of the arguments are "dynamic"
164         -- Leftover ones are presumably files
165   (dflags2, fileish_args, dynamicFlagWarnings) <- GHC.parseDynamicFlags dflags1a args
166
167   let flagWarnings' = flagWarnings ++ dynamicFlagWarnings
168
169   handleSourceError (\e -> do
170        GHC.printExceptionAndWarnings e
171        liftIO $ exitWith (ExitFailure 1)) $
172     handleFlagWarnings dflags2 flagWarnings'
173
174         -- make sure we clean up after ourselves
175   GHC.defaultCleanupHandler dflags2 $ do
176
177   liftIO $ showBanner postLoadMode dflags2
178
179   -- we've finished manipulating the DynFlags, update the session
180   _ <- GHC.setSessionDynFlags dflags2
181   dflags3 <- GHC.getSessionDynFlags
182   hsc_env <- GHC.getSession
183
184   let
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 [] []
190
191   -- Note: have v_Ld_inputs maintain the order in which 'objs' occurred on 
192   --       the command-line.
193   liftIO $ mapM_ (consIORef v_Ld_inputs) (reverse objs)
194
195         ---------------- Display configuration -----------
196   when (verbosity dflags3 >= 4) $
197         liftIO $ dumpPackages dflags3
198
199   when (verbosity dflags3 >= 3) $ do
200         liftIO $ hPutStrLn stderr ("Hsc static flags: " ++ unwords staticFlags)
201
202         ---------------- Final sanity checking -----------
203   liftIO $ checkOptions postLoadMode dflags3 srcs objs
204
205   ---------------- Do the business -----------
206   handleSourceError (\e -> do
207        GHC.printExceptionAndWarnings e
208        liftIO $ exitWith (ExitFailure 1)) $ do
209     case postLoadMode of
210        ShowInterface f        -> liftIO $ doShowIface dflags3 f
211        DoMake                 -> doMake srcs
212        DoMkDependHS           -> do doMkDependHS (map fst srcs)
213                                     GHC.printWarnings
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
218
219   liftIO $ dumpFinalStats dflags3
220
221 #ifndef GHCI
222 interactiveUI :: b -> c -> Ghc ()
223 interactiveUI _ _ =
224   ghcError (CmdLineError "not built for interactive use")
225 #endif
226
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.
231
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)
245
246     {-
247       We split out the object files (.o, .dll) and add them
248       to v_Ld_inputs for use by the linker.
249
250       The following things should be considered compilation manager inputs:
251
252        - haskell source files (strings ending in .hs, .lhs or other 
253          haskellish extension),
254
255        - module names (not forgetting hierarchical module names),
256
257        - and finally we consider everything not containing a '.' to be
258          a comp manager input, as shorthand for a .hs or .lhs filename.
259
260       Everything else is considered to be a linker object, and passed
261       straight through to the linker.
262     -}
263 looks_like_an_input :: String -> Bool
264 looks_like_an_input m =  isSourceFilename m 
265                       || looksLikeModuleName m
266                       || '.' `notElem` m
267
268 -- -----------------------------------------------------------------------------
269 -- Option sanity checks
270
271 -- | Ensure sanity of options.
272 --
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)
280
281    when (notNull (filter isRTSWay (wayNames dflags))
282          && isInterpretiveMode mode) $
283         hPutStrLn stderr ("Warning: -debug, -threaded and -ticky are ignored by GHCi")
284
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.")
290         -- -ohi sanity check
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")
294         else do
295
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")
300         else do
301
302    let not_linking = not (isLinkMode mode) || isNoLink (ghcLink dflags)
303
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)
306
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")
311         else do
312
313      -- Verify that output files point somewhere sensible.
314    verifyOutputFiles dflags
315
316
317 -- Compiler output options
318
319 -- called to verify that the output files & directories
320 -- point somewhere valid. 
321 --
322 -- The assumption is that the directory portion of these output
323 -- options will have to exist by the time 'verifyOutputFiles'
324 -- is invoked.
325 -- 
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)
339  where
340    nonExistentDir flg dir = 
341      ghcError (CmdLineError ("error: directory portion of " ++ 
342                              show dir ++ " does not exist (used with " ++ 
343                              show flg ++ " option.)"))
344
345 -----------------------------------------------------------------------------
346 -- GHC modes of operation
347
348 type Mode = Either PreStartupMode PostStartupMode
349 type PostStartupMode = Either PreLoadMode PostLoadMode
350
351 data PreStartupMode
352   = ShowVersion             -- ghc -V/--version
353   | ShowNumVersion          -- ghc --numeric-version
354   | ShowSupportedLanguages  -- ghc --supported-languages
355   | Print String            -- ghc --print-foo
356
357 showVersionMode, showNumVersionMode, showSupportedLanguagesMode :: Mode
358 showVersionMode            = mkPreStartupMode ShowVersion
359 showNumVersionMode         = mkPreStartupMode ShowNumVersion
360 showSupportedLanguagesMode = mkPreStartupMode ShowSupportedLanguages
361
362 printMode :: String -> Mode
363 printMode str              = mkPreStartupMode (Print str)
364
365 mkPreStartupMode :: PreStartupMode -> Mode
366 mkPreStartupMode = Left
367
368 isShowVersionMode :: Mode -> Bool
369 isShowVersionMode (Left ShowVersion) = True
370 isShowVersionMode _ = False
371
372 isShowNumVersionMode :: Mode -> Bool
373 isShowNumVersionMode (Left ShowNumVersion) = True
374 isShowNumVersionMode _ = False
375
376 data PreLoadMode
377   = ShowGhcUsage                           -- ghc -?
378   | ShowGhciUsage                          -- ghci -?
379   | ShowInfo                               -- ghc --info
380   | PrintWithDynFlags (DynFlags -> String) -- ghc --print-foo
381
382 showGhcUsageMode, showGhciUsageMode, showInfoMode :: Mode
383 showGhcUsageMode = mkPreLoadMode ShowGhcUsage
384 showGhciUsageMode = mkPreLoadMode ShowGhciUsage
385 showInfoMode = mkPreLoadMode ShowInfo
386
387 printWithDynFlagsMode :: (DynFlags -> String) -> Mode
388 printWithDynFlagsMode f = mkPreLoadMode (PrintWithDynFlags f)
389
390 mkPreLoadMode :: PreLoadMode -> Mode
391 mkPreLoadMode = Right . Left
392
393 isShowGhcUsageMode :: Mode -> Bool
394 isShowGhcUsageMode (Right (Left ShowGhcUsage)) = True
395 isShowGhcUsageMode _ = False
396
397 isShowGhciUsageMode :: Mode -> Bool
398 isShowGhciUsageMode (Right (Left ShowGhciUsage)) = True
399 isShowGhciUsageMode _ = False
400
401 data PostLoadMode
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
410
411 doMkDependHSMode, doMakeMode, doInteractiveMode, doAbiHashMode :: Mode
412 doMkDependHSMode = mkPostLoadMode DoMkDependHS
413 doMakeMode = mkPostLoadMode DoMake
414 doInteractiveMode = mkPostLoadMode DoInteractive
415 doAbiHashMode = mkPostLoadMode DoAbiHash
416
417 showInterfaceMode :: FilePath -> Mode
418 showInterfaceMode fp = mkPostLoadMode (ShowInterface fp)
419
420 stopBeforeMode :: Phase -> Mode
421 stopBeforeMode phase = mkPostLoadMode (StopBefore phase)
422
423 doEvalMode :: String -> Mode
424 doEvalMode str = mkPostLoadMode (DoEval [str])
425
426 mkPostLoadMode :: PostLoadMode -> Mode
427 mkPostLoadMode = Right . Right
428
429 isDoInteractiveMode :: Mode -> Bool
430 isDoInteractiveMode (Right (Right DoInteractive)) = True
431 isDoInteractiveMode _ = False
432
433 isStopLnMode :: Mode -> Bool
434 isStopLnMode (Right (Right (StopBefore StopLn))) = True
435 isStopLnMode _ = False
436
437 isDoMakeMode :: Mode -> Bool
438 isDoMakeMode (Right (Right DoMake)) = True
439 isDoMakeMode _ = False
440
441 #ifdef GHCI
442 isInteractiveMode :: PostLoadMode -> Bool
443 isInteractiveMode DoInteractive = True
444 isInteractiveMode _             = False
445 #endif
446
447 -- isInterpretiveMode: byte-code compiler involved
448 isInterpretiveMode :: PostLoadMode -> Bool
449 isInterpretiveMode DoInteractive = True
450 isInterpretiveMode (DoEval _)    = True
451 isInterpretiveMode _             = False
452
453 needsInputsMode :: PostLoadMode -> Bool
454 needsInputsMode DoMkDependHS    = True
455 needsInputsMode (StopBefore _)  = True
456 needsInputsMode DoMake          = True
457 needsInputsMode _               = False
458
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
466 isLinkMode _                   = False
467
468 isCompManagerMode :: PostLoadMode -> Bool
469 isCompManagerMode DoMake        = True
470 isCompManagerMode DoInteractive = True
471 isCompManagerMode (DoEval _)    = True
472 isCompManagerMode _             = False
473
474 -- -----------------------------------------------------------------------------
475 -- Parsing the mode flag
476
477 parseModeFlags :: [Located String]
478                -> IO (Mode,
479                       [Located String],
480                       [Located String])
481 parseModeFlags args = do
482   let ((leftover, errs1, warns), (mModeFlag, errs2, flags')) =
483           runCmdLine (processArgs mode_flags args)
484                      (Nothing, [], [])
485       mode = case mModeFlag of
486              Nothing     -> doMakeMode
487              Just (m, _) -> m
488       errs = errs1 ++ map (mkGeneralLocated "on the commandline") errs2
489   when (not (null errs)) $ ghcError $ errorsToGhcException errs
490   return (mode, flags' ++ leftover, warns)
491
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.
495
496 mode_flags :: [Flag ModeM]
497 mode_flags =
498   [  ------- help / version ----------------------------------------------
499     Flag "?"                    (PassFlag (setMode showGhcUsageMode))
500          Supported
501   , Flag "-help"                (PassFlag (setMode showGhcUsageMode))
502          Supported
503   , Flag "V"                    (PassFlag (setMode showVersionMode))
504          Supported
505   , Flag "-version"             (PassFlag (setMode showVersionMode))
506          Supported
507   , Flag "-numeric-version"     (PassFlag (setMode showNumVersionMode))
508          Supported
509   , Flag "-info"                (PassFlag (setMode showInfoMode))
510          Supported
511   , Flag "-supported-languages" (PassFlag (setMode showSupportedLanguagesMode))
512          Supported
513   ] ++
514   [ Flag k'                     (PassFlag (setMode mode))
515          Supported
516   | (k, v) <- compilerInfo,
517     let k' = "-print-" ++ map (replaceSpace . toLower) k
518         replaceSpace ' ' = '-'
519         replaceSpace c   = c
520         mode = case v of
521                String str -> printMode str
522                FromDynFlags f -> printWithDynFlagsMode f
523   ] ++
524       ------- interfaces ----------------------------------------------------
525   [ Flag "-show-iface"  (HasArg (\f -> setMode (showInterfaceMode f)
526                                                "--show-iface"))
527          Supported
528
529       ------- primary modes ------------------------------------------------
530   , Flag "c"            (PassFlag (\f -> do setMode (stopBeforeMode StopLn) f
531                                             addFlag "-no-link" f))
532          Supported
533   , Flag "M"            (PassFlag (setMode doMkDependHSMode))
534          Supported
535   , Flag "E"            (PassFlag (setMode (stopBeforeMode anyHsc)))
536          Supported
537   , Flag "C"            (PassFlag (\f -> do setMode (stopBeforeMode HCc) f
538                                             addFlag "-fvia-C" f))
539          Supported
540   , Flag "S"            (PassFlag (setMode (stopBeforeMode As)))
541          Supported
542   , Flag "-make"        (PassFlag (setMode doMakeMode))
543          Supported
544   , Flag "-interactive" (PassFlag (setMode doInteractiveMode))
545          Supported
546   , Flag "-abi-hash"    (PassFlag (setMode doAbiHashMode))
547          Supported
548   , Flag "e"            (SepArg   (\s -> setMode (doEvalMode s) "-e"))
549          Supported
550   ]
551
552 setMode :: Mode -> String -> ModeM ()
553 setMode newMode newFlag = do
554     (mModeFlag, errs, flags') <- getCmdLineState
555     let (modeFlag', errs') =
556             case mModeFlag of
557             Nothing -> ((newMode, newFlag), errs)
558             Just (oldMode, oldFlag) ->
559                 case (oldMode, newMode) of
560                     -- -c/--make are allowed together, and mean --make -no-link
561                     _ |  isStopLnMode oldMode && isDoMakeMode newMode
562                       || isStopLnMode newMode && isDoMakeMode oldMode ->
563                       ((doMakeMode, "--make"), [])
564
565                     -- If we have both --help and --interactive then we
566                     -- want showGhciUsage
567                     _ | isShowGhcUsageMode oldMode &&
568                         isDoInteractiveMode newMode ->
569                             ((showGhciUsageMode, oldFlag), [])
570                       | isShowGhcUsageMode newMode &&
571                         isDoInteractiveMode oldMode ->
572                             ((showGhciUsageMode, newFlag), [])
573                     -- Otherwise, --help/--version/--numeric-version always win
574                       | isDominantFlag oldMode -> ((oldMode, oldFlag), [])
575                       | isDominantFlag newMode -> ((newMode, newFlag), [])
576                     -- We need to accumulate eval flags like "-e foo -e bar"
577                     (Right (Right (DoEval esOld)),
578                      Right (Right (DoEval [eNew]))) ->
579                         ((Right (Right (DoEval (eNew : esOld))), oldFlag),
580                          errs)
581                     -- Saying e.g. --interactive --interactive is OK
582                     _ | oldFlag == newFlag -> ((oldMode, oldFlag), errs)
583                     -- Otherwise, complain
584                     _ -> let err = flagMismatchErr oldFlag newFlag
585                          in ((oldMode, oldFlag), err : errs)
586     putCmdLineState (Just modeFlag', errs', flags')
587   where isDominantFlag f = isShowGhcUsageMode   f ||
588                            isShowGhciUsageMode  f ||
589                            isShowVersionMode    f ||
590                            isShowNumVersionMode f
591
592 flagMismatchErr :: String -> String -> String
593 flagMismatchErr oldFlag newFlag
594     = "cannot use `" ++ oldFlag ++  "' with `" ++ newFlag ++ "'"
595
596 addFlag :: String -> String -> ModeM ()
597 addFlag s flag = do
598   (m, e, flags') <- getCmdLineState
599   putCmdLineState (m, e, mkGeneralLocated loc s : flags')
600     where loc = "addFlag by " ++ flag ++ " on the commandline"
601
602 -- ----------------------------------------------------------------------------
603 -- Run --make mode
604
605 doMake :: [(String,Maybe Phase)] -> Ghc ()
606 doMake srcs  = do
607     let (hs_srcs, non_hs_srcs) = partition haskellish srcs
608
609         haskellish (f,Nothing) = 
610           looksLikeModuleName f || isHaskellSrcFilename f || '.' `notElem` f
611         haskellish (_,Just phase) = 
612           phase `notElem` [As, Cc, CmmCpp, Cmm, StopLn]
613
614     hsc_env <- GHC.getSession
615
616     -- if we have no haskell sources from which to do a dependency
617     -- analysis, then just do one-shot compilation and/or linking.
618     -- This means that "ghc Foo.o Bar.o -o baz" links the program as
619     -- we expect.
620     if (null hs_srcs)
621        then oneShot hsc_env StopLn srcs >> GHC.printWarnings
622        else do
623
624     o_files <- mapM (\x -> do
625                         f <- compileFile hsc_env StopLn x
626                         GHC.printWarnings
627                         return f)
628                  non_hs_srcs
629     liftIO $ mapM_ (consIORef v_Ld_inputs) (reverse o_files)
630
631     targets <- mapM (uncurry GHC.guessTarget) hs_srcs
632     GHC.setTargets targets
633     ok_flag <- GHC.load LoadAllTargets
634
635     when (failed ok_flag) (liftIO $ exitWith (ExitFailure 1))
636     return ()
637
638
639 -- ---------------------------------------------------------------------------
640 -- --show-iface mode
641
642 doShowIface :: DynFlags -> FilePath -> IO ()
643 doShowIface dflags file = do
644   hsc_env <- newHscEnv defaultCallbacks dflags
645   showIface hsc_env file
646
647 -- ---------------------------------------------------------------------------
648 -- Various banners and verbosity output.
649
650 showBanner :: PostLoadMode -> DynFlags -> IO ()
651 showBanner _postLoadMode dflags = do
652    let verb = verbosity dflags
653
654 #ifdef GHCI
655    -- Show the GHCi banner
656    when (isInteractiveMode _postLoadMode && verb >= 1) $ putStrLn ghciWelcomeMsg
657 #endif
658
659    -- Display details of the configuration in verbose mode
660    when (verb >= 2) $
661     do hPutStr stderr "Glasgow Haskell Compiler, Version "
662        hPutStr stderr cProjectVersion
663        hPutStr stderr ", for Haskell 98, stage "
664        hPutStr stderr cStage
665        hPutStr stderr " booted by GHC version "
666        hPutStrLn stderr cBooterVersion
667
668 -- We print out a Read-friendly string, but a prettier one than the
669 -- Show instance gives us
670 showInfo :: DynFlags -> IO ()
671 showInfo dflags = do
672         let sq x = " [" ++ x ++ "\n ]"
673         putStrLn $ sq $ concat $ intersperse "\n ," $ map (show . flatten) compilerInfo
674     where flatten (k, String v)       = (k, v)
675           flatten (k, FromDynFlags f) = (k, f dflags)
676
677 showSupportedLanguages :: IO ()
678 showSupportedLanguages = mapM_ putStrLn supportedLanguages
679
680 showVersion :: IO ()
681 showVersion = putStrLn (cProjectName ++ ", version " ++ cProjectVersion)
682
683 showGhcUsage :: DynFlags -> IO ()
684 showGhcUsage = showUsage False
685
686 showGhciUsage :: DynFlags -> IO ()
687 showGhciUsage = showUsage True
688
689 showUsage :: Bool -> DynFlags -> IO ()
690 showUsage ghci dflags = do
691   let usage_path = if ghci then ghciUsagePath dflags
692                            else ghcUsagePath dflags
693   usage <- readFile usage_path
694   dump usage
695   where
696      dump ""          = return ()
697      dump ('$':'$':s) = putStr progName >> dump s
698      dump (c:s)       = putChar c >> dump s
699
700 dumpFinalStats :: DynFlags -> IO ()
701 dumpFinalStats dflags = 
702   when (dopt Opt_D_faststring_stats dflags) $ dumpFastStringStats dflags
703
704 dumpFastStringStats :: DynFlags -> IO ()
705 dumpFastStringStats dflags = do
706   buckets <- getFastStringTable
707   let (entries, longest, is_z, has_z) = countFS 0 0 0 0 buckets
708       msg = text "FastString stats:" $$
709             nest 4 (vcat [text "size:           " <+> int (length buckets),
710                           text "entries:        " <+> int entries,
711                           text "longest chain:  " <+> int longest,
712                           text "z-encoded:      " <+> (is_z `pcntOf` entries),
713                           text "has z-encoding: " <+> (has_z `pcntOf` entries)
714                          ])
715         -- we usually get more "has z-encoding" than "z-encoded", because
716         -- when we z-encode a string it might hash to the exact same string,
717         -- which will is not counted as "z-encoded".  Only strings whose
718         -- Z-encoding is different from the original string are counted in
719         -- the "z-encoded" total.
720   putMsg dflags msg
721   where
722    x `pcntOf` y = int ((x * 100) `quot` y) <> char '%'
723
724 countFS :: Int -> Int -> Int -> Int -> [[FastString]] -> (Int, Int, Int, Int)
725 countFS entries longest is_z has_z [] = (entries, longest, is_z, has_z)
726 countFS entries longest is_z has_z (b:bs) = 
727   let
728         len = length b
729         longest' = max len longest
730         entries' = entries + len
731         is_zs = length (filter isZEncoded b)
732         has_zs = length (filter hasZEncoding b)
733   in
734         countFS entries' longest' (is_z + is_zs) (has_z + has_zs) bs
735
736 -- -----------------------------------------------------------------------------
737 -- ABI hash support
738
739 {-
740         ghc --abi-hash Data.Foo System.Bar
741
742 Generates a combined hash of the ABI for modules Data.Foo and
743 System.Bar.  The modules must already be compiled, and appropriate -i
744 options may be necessary in order to find the .hi files.
745
746 This is used by Cabal for generating the InstalledPackageId for a
747 package.  The InstalledPackageId must change when the visible ABI of
748 the package chagnes, so during registration Cabal calls ghc --abi-hash
749 to get a hash of the package's ABI.
750 -}
751
752 abiHash :: [(String, Maybe Phase)] -> Ghc ()
753 abiHash strs = do
754   hsc_env <- getSession
755   let dflags = hsc_dflags hsc_env
756
757   liftIO $ do
758
759   let find_it str = do
760          let modname = mkModuleName str
761          r <- findImportedModule hsc_env modname Nothing
762          case r of
763            Found _ m -> return m
764            _error    -> ghcError $ CmdLineError $ showSDoc $
765                           cannotFindInterface dflags modname r
766
767   mods <- mapM find_it (map fst strs)
768
769   let get_iface modl = loadUserInterface False (text "abiHash") modl
770   ifaces <- initIfaceCheck hsc_env $ mapM get_iface mods
771
772   bh <- openBinMem (3*1024) -- just less than a block
773   mapM_ (put_ bh . mi_mod_hash) ifaces
774   f <- fingerprintBinMem bh
775
776   putStrLn (showSDoc (ppr f))
777
778 -- -----------------------------------------------------------------------------
779 -- Util
780
781 unknownFlagsErr :: [String] -> a
782 unknownFlagsErr fs = ghcError (UsageError ("unrecognised flags: " ++ unwords fs))