Rename "language" varibles etc to "extension", and add --supported-extensions
[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                    ShowSupportedExtensions -> showSupportedExtensions
109                    ShowVersion             -> showVersion
110                    ShowNumVersion          -> putStrLn cProjectVersion
111                    Print str               -> putStrLn str
112         Right postStartupMode ->
113             -- start our GHC session
114             GHC.runGhc mbMinusB $ do
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   | ShowSupportedExtensions -- ghc --supported-extensions
355   | Print String            -- ghc --print-foo
356
357 showVersionMode, showNumVersionMode, showSupportedExtensionsMode :: Mode
358 showVersionMode             = mkPreStartupMode ShowVersion
359 showNumVersionMode          = mkPreStartupMode ShowNumVersion
360 showSupportedExtensionsMode = mkPreStartupMode ShowSupportedExtensions
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 showSupportedExtensionsMode))
512          Supported
513   , Flag "-supported-extensions" (PassFlag (setMode showSupportedExtensionsMode))
514          Supported
515   ] ++
516   [ Flag k'                     (PassFlag (setMode mode))
517          Supported
518   | (k, v) <- compilerInfo,
519     let k' = "-print-" ++ map (replaceSpace . toLower) k
520         replaceSpace ' ' = '-'
521         replaceSpace c   = c
522         mode = case v of
523                String str -> printMode str
524                FromDynFlags f -> printWithDynFlagsMode f
525   ] ++
526       ------- interfaces ----------------------------------------------------
527   [ Flag "-show-iface"  (HasArg (\f -> setMode (showInterfaceMode f)
528                                                "--show-iface"))
529          Supported
530
531       ------- primary modes ------------------------------------------------
532   , Flag "c"            (PassFlag (\f -> do setMode (stopBeforeMode StopLn) f
533                                             addFlag "-no-link" f))
534          Supported
535   , Flag "M"            (PassFlag (setMode doMkDependHSMode))
536          Supported
537   , Flag "E"            (PassFlag (setMode (stopBeforeMode anyHsc)))
538          Supported
539   , Flag "C"            (PassFlag (\f -> do setMode (stopBeforeMode HCc) f
540                                             addFlag "-fvia-C" f))
541          Supported
542   , Flag "S"            (PassFlag (setMode (stopBeforeMode As)))
543          Supported
544   , Flag "-make"        (PassFlag (setMode doMakeMode))
545          Supported
546   , Flag "-interactive" (PassFlag (setMode doInteractiveMode))
547          Supported
548   , Flag "-abi-hash"    (PassFlag (setMode doAbiHashMode))
549          Supported
550   , Flag "e"            (SepArg   (\s -> setMode (doEvalMode s) "-e"))
551          Supported
552   ]
553
554 setMode :: Mode -> String -> ModeM ()
555 setMode newMode newFlag = do
556     (mModeFlag, errs, flags') <- getCmdLineState
557     let (modeFlag', errs') =
558             case mModeFlag of
559             Nothing -> ((newMode, newFlag), errs)
560             Just (oldMode, oldFlag) ->
561                 case (oldMode, newMode) of
562                     -- -c/--make are allowed together, and mean --make -no-link
563                     _ |  isStopLnMode oldMode && isDoMakeMode newMode
564                       || isStopLnMode newMode && isDoMakeMode oldMode ->
565                       ((doMakeMode, "--make"), [])
566
567                     -- If we have both --help and --interactive then we
568                     -- want showGhciUsage
569                     _ | isShowGhcUsageMode oldMode &&
570                         isDoInteractiveMode newMode ->
571                             ((showGhciUsageMode, oldFlag), [])
572                       | isShowGhcUsageMode newMode &&
573                         isDoInteractiveMode oldMode ->
574                             ((showGhciUsageMode, newFlag), [])
575                     -- Otherwise, --help/--version/--numeric-version always win
576                       | isDominantFlag oldMode -> ((oldMode, oldFlag), [])
577                       | isDominantFlag newMode -> ((newMode, newFlag), [])
578                     -- We need to accumulate eval flags like "-e foo -e bar"
579                     (Right (Right (DoEval esOld)),
580                      Right (Right (DoEval [eNew]))) ->
581                         ((Right (Right (DoEval (eNew : esOld))), oldFlag),
582                          errs)
583                     -- Saying e.g. --interactive --interactive is OK
584                     _ | oldFlag == newFlag -> ((oldMode, oldFlag), errs)
585                     -- Otherwise, complain
586                     _ -> let err = flagMismatchErr oldFlag newFlag
587                          in ((oldMode, oldFlag), err : errs)
588     putCmdLineState (Just modeFlag', errs', flags')
589   where isDominantFlag f = isShowGhcUsageMode   f ||
590                            isShowGhciUsageMode  f ||
591                            isShowVersionMode    f ||
592                            isShowNumVersionMode f
593
594 flagMismatchErr :: String -> String -> String
595 flagMismatchErr oldFlag newFlag
596     = "cannot use `" ++ oldFlag ++  "' with `" ++ newFlag ++ "'"
597
598 addFlag :: String -> String -> ModeM ()
599 addFlag s flag = do
600   (m, e, flags') <- getCmdLineState
601   putCmdLineState (m, e, mkGeneralLocated loc s : flags')
602     where loc = "addFlag by " ++ flag ++ " on the commandline"
603
604 -- ----------------------------------------------------------------------------
605 -- Run --make mode
606
607 doMake :: [(String,Maybe Phase)] -> Ghc ()
608 doMake srcs  = do
609     let (hs_srcs, non_hs_srcs) = partition haskellish srcs
610
611         haskellish (f,Nothing) = 
612           looksLikeModuleName f || isHaskellSrcFilename f || '.' `notElem` f
613         haskellish (_,Just phase) = 
614           phase `notElem` [As, Cc, CmmCpp, Cmm, StopLn]
615
616     hsc_env <- GHC.getSession
617
618     -- if we have no haskell sources from which to do a dependency
619     -- analysis, then just do one-shot compilation and/or linking.
620     -- This means that "ghc Foo.o Bar.o -o baz" links the program as
621     -- we expect.
622     if (null hs_srcs)
623        then oneShot hsc_env StopLn srcs >> GHC.printWarnings
624        else do
625
626     o_files <- mapM (\x -> do
627                         f <- compileFile hsc_env StopLn x
628                         GHC.printWarnings
629                         return f)
630                  non_hs_srcs
631     liftIO $ mapM_ (consIORef v_Ld_inputs) (reverse o_files)
632
633     targets <- mapM (uncurry GHC.guessTarget) hs_srcs
634     GHC.setTargets targets
635     ok_flag <- GHC.load LoadAllTargets
636
637     when (failed ok_flag) (liftIO $ exitWith (ExitFailure 1))
638     return ()
639
640
641 -- ---------------------------------------------------------------------------
642 -- --show-iface mode
643
644 doShowIface :: DynFlags -> FilePath -> IO ()
645 doShowIface dflags file = do
646   hsc_env <- newHscEnv defaultCallbacks dflags
647   showIface hsc_env file
648
649 -- ---------------------------------------------------------------------------
650 -- Various banners and verbosity output.
651
652 showBanner :: PostLoadMode -> DynFlags -> IO ()
653 showBanner _postLoadMode dflags = do
654    let verb = verbosity dflags
655
656 #ifdef GHCI
657    -- Show the GHCi banner
658    when (isInteractiveMode _postLoadMode && verb >= 1) $ putStrLn ghciWelcomeMsg
659 #endif
660
661    -- Display details of the configuration in verbose mode
662    when (verb >= 2) $
663     do hPutStr stderr "Glasgow Haskell Compiler, Version "
664        hPutStr stderr cProjectVersion
665        hPutStr stderr ", for Haskell 98, stage "
666        hPutStr stderr cStage
667        hPutStr stderr " booted by GHC version "
668        hPutStrLn stderr cBooterVersion
669
670 -- We print out a Read-friendly string, but a prettier one than the
671 -- Show instance gives us
672 showInfo :: DynFlags -> IO ()
673 showInfo dflags = do
674         let sq x = " [" ++ x ++ "\n ]"
675         putStrLn $ sq $ concat $ intersperse "\n ," $ map (show . flatten) compilerInfo
676     where flatten (k, String v)       = (k, v)
677           flatten (k, FromDynFlags f) = (k, f dflags)
678
679 showSupportedExtensions :: IO ()
680 showSupportedExtensions = mapM_ putStrLn supportedExtensions
681
682 showVersion :: IO ()
683 showVersion = putStrLn (cProjectName ++ ", version " ++ cProjectVersion)
684
685 showGhcUsage :: DynFlags -> IO ()
686 showGhcUsage = showUsage False
687
688 showGhciUsage :: DynFlags -> IO ()
689 showGhciUsage = showUsage True
690
691 showUsage :: Bool -> DynFlags -> IO ()
692 showUsage ghci dflags = do
693   let usage_path = if ghci then ghciUsagePath dflags
694                            else ghcUsagePath dflags
695   usage <- readFile usage_path
696   dump usage
697   where
698      dump ""          = return ()
699      dump ('$':'$':s) = putStr progName >> dump s
700      dump (c:s)       = putChar c >> dump s
701
702 dumpFinalStats :: DynFlags -> IO ()
703 dumpFinalStats dflags = 
704   when (dopt Opt_D_faststring_stats dflags) $ dumpFastStringStats dflags
705
706 dumpFastStringStats :: DynFlags -> IO ()
707 dumpFastStringStats dflags = do
708   buckets <- getFastStringTable
709   let (entries, longest, is_z, has_z) = countFS 0 0 0 0 buckets
710       msg = text "FastString stats:" $$
711             nest 4 (vcat [text "size:           " <+> int (length buckets),
712                           text "entries:        " <+> int entries,
713                           text "longest chain:  " <+> int longest,
714                           text "z-encoded:      " <+> (is_z `pcntOf` entries),
715                           text "has z-encoding: " <+> (has_z `pcntOf` entries)
716                          ])
717         -- we usually get more "has z-encoding" than "z-encoded", because
718         -- when we z-encode a string it might hash to the exact same string,
719         -- which will is not counted as "z-encoded".  Only strings whose
720         -- Z-encoding is different from the original string are counted in
721         -- the "z-encoded" total.
722   putMsg dflags msg
723   where
724    x `pcntOf` y = int ((x * 100) `quot` y) <> char '%'
725
726 countFS :: Int -> Int -> Int -> Int -> [[FastString]] -> (Int, Int, Int, Int)
727 countFS entries longest is_z has_z [] = (entries, longest, is_z, has_z)
728 countFS entries longest is_z has_z (b:bs) = 
729   let
730         len = length b
731         longest' = max len longest
732         entries' = entries + len
733         is_zs = length (filter isZEncoded b)
734         has_zs = length (filter hasZEncoding b)
735   in
736         countFS entries' longest' (is_z + is_zs) (has_z + has_zs) bs
737
738 -- -----------------------------------------------------------------------------
739 -- ABI hash support
740
741 {-
742         ghc --abi-hash Data.Foo System.Bar
743
744 Generates a combined hash of the ABI for modules Data.Foo and
745 System.Bar.  The modules must already be compiled, and appropriate -i
746 options may be necessary in order to find the .hi files.
747
748 This is used by Cabal for generating the InstalledPackageId for a
749 package.  The InstalledPackageId must change when the visible ABI of
750 the package chagnes, so during registration Cabal calls ghc --abi-hash
751 to get a hash of the package's ABI.
752 -}
753
754 abiHash :: [(String, Maybe Phase)] -> Ghc ()
755 abiHash strs = do
756   hsc_env <- getSession
757   let dflags = hsc_dflags hsc_env
758
759   liftIO $ do
760
761   let find_it str = do
762          let modname = mkModuleName str
763          r <- findImportedModule hsc_env modname Nothing
764          case r of
765            Found _ m -> return m
766            _error    -> ghcError $ CmdLineError $ showSDoc $
767                           cannotFindInterface dflags modname r
768
769   mods <- mapM find_it (map fst strs)
770
771   let get_iface modl = loadUserInterface False (text "abiHash") modl
772   ifaces <- initIfaceCheck hsc_env $ mapM get_iface mods
773
774   bh <- openBinMem (3*1024) -- just less than a block
775   mapM_ (put_ bh . mi_mod_hash) ifaces
776   f <- fingerprintBinMem bh
777
778   putStrLn (showSDoc (ppr f))
779
780 -- -----------------------------------------------------------------------------
781 -- Util
782
783 unknownFlagsErr :: [String] -> a
784 unknownFlagsErr fs = ghcError (UsageError ("unrecognised flags: " ++ unwords fs))