Separate the static flag parser from the static global variables
[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 #include "HsVersions.h"
14
15 -- The official GHC API
16 import qualified GHC
17 import GHC              ( Session, DynFlags(..), HscTarget(..), 
18                           GhcMode(..), GhcLink(..),
19                           LoadHowMuch(..), dopt, DynFlag(..) )
20 import CmdLineParser
21
22 -- Implementations of the various modes (--show-iface, mkdependHS. etc.)
23 import LoadIface        ( showIface )
24 import HscMain          ( newHscEnv )
25 import DriverPipeline   ( oneShot, compileFile )
26 import DriverMkDepend   ( doMkDependHS )
27 #ifdef GHCI
28 import InteractiveUI    ( interactiveUI, ghciWelcomeMsg )
29 #endif
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 StaticFlags
38 import StaticFlagParser
39 import DynFlags
40 import BasicTypes       ( failed )
41 import ErrUtils
42 import FastString
43 import Outputable
44 import Util
45 import Panic
46
47 -- Standard Haskell libraries
48 import System.IO
49 import System.Environment
50 import System.Exit
51 import System.FilePath
52 import Control.Monad
53 import Data.List
54 import Data.Maybe
55
56 -----------------------------------------------------------------------------
57 -- ToDo:
58
59 -- time commands when run with -v
60 -- user ways
61 -- Win32 support: proper signal handling
62 -- reading the package configuration file is too slow
63 -- -K<size>
64
65 -----------------------------------------------------------------------------
66 -- GHC's command-line interface
67
68 main :: IO ()
69 main =
70   GHC.defaultErrorHandler defaultDynFlags $ do
71   
72   -- 1. extract the -B flag from the args
73   argv0 <- getArgs
74
75   let
76         (minusB_args, argv1) = partition ("-B" `isPrefixOf`) argv0
77         mbMinusB | null minusB_args = Nothing
78                  | otherwise = Just (drop 2 (last minusB_args))
79
80   (argv2, staticFlagWarnings) <- parseStaticFlags argv1
81
82   -- 2. Parse the "mode" flags (--make, --interactive etc.)
83   (cli_mode, argv3, modeFlagWarnings) <- parseModeFlags argv2
84
85   -- If all we want to do is to show the version number then do it
86   -- now, before we start a GHC session etc.
87   -- If we do it later then bootstrapping gets confused as it tries
88   -- to find out what version of GHC it's using before package.conf
89   -- exists, so starting the session fails.
90   case cli_mode of
91     ShowInfo                -> do showInfo
92                                   exitWith ExitSuccess
93     ShowSupportedLanguages  -> do showSupportedLanguages
94                                   exitWith ExitSuccess
95     ShowVersion             -> do showVersion
96                                   exitWith ExitSuccess
97     ShowNumVersion          -> do putStrLn cProjectVersion
98                                   exitWith ExitSuccess
99     _                       -> return ()
100
101   -- start our GHC session
102   session <- GHC.newSession mbMinusB
103
104   dflags0 <- GHC.getSessionDynFlags session
105
106   -- set the default GhcMode, HscTarget and GhcLink.  The HscTarget
107   -- can be further adjusted on a module by module basis, using only
108   -- the -fvia-C and -fasm flags.  If the default HscTarget is not
109   -- HscC or HscAsm, -fvia-C and -fasm have no effect.
110   let dflt_target = hscTarget dflags0
111       (mode, lang, link)
112          = case cli_mode of
113                 DoInteractive   -> (CompManager, HscInterpreted, LinkInMemory)
114                 DoEval _        -> (CompManager, HscInterpreted, LinkInMemory)
115                 DoMake          -> (CompManager, dflt_target,    LinkBinary)
116                 DoMkDependHS    -> (MkDepend,    dflt_target,    LinkBinary)
117                 _               -> (OneShot,     dflt_target,    LinkBinary)
118
119   let dflags1 = dflags0{ ghcMode   = mode,
120                          hscTarget = lang,
121                          ghcLink   = link,
122                          -- leave out hscOutName for now
123                          hscOutName = panic "Main.main:hscOutName not set",
124                          verbosity = case cli_mode of
125                                          DoEval _ -> 0
126                                          _other   -> 1
127                         }
128
129       -- turn on -fimplicit-import-qualified for GHCi now, so that it
130       -- can be overriden from the command-line
131       dflags1a | DoInteractive <- cli_mode = imp_qual_enabled
132                | DoEval _      <- cli_mode = imp_qual_enabled
133                | otherwise                 = dflags1
134         where imp_qual_enabled = dflags1 `dopt_set` Opt_ImplicitImportQualified
135
136         -- The rest of the arguments are "dynamic"
137         -- Leftover ones are presumably files
138   (dflags2, fileish_args, dynamicFlagWarnings) <- GHC.parseDynamicFlags dflags1a argv3
139
140   let flagWarnings = staticFlagWarnings
141                   ++ modeFlagWarnings
142                   ++ dynamicFlagWarnings
143   handleFlagWarnings dflags2 flagWarnings
144
145         -- make sure we clean up after ourselves
146   GHC.defaultCleanupHandler dflags2 $ do
147
148   showBanner cli_mode dflags2
149
150   -- we've finished manipulating the DynFlags, update the session
151   GHC.setSessionDynFlags session dflags2
152   dflags3 <- GHC.getSessionDynFlags session
153   hsc_env <- GHC.sessionHscEnv      session
154
155   let
156      -- To simplify the handling of filepaths, we normalise all filepaths right 
157      -- away - e.g., for win32 platforms, backslashes are converted
158      -- into forward slashes.
159     normal_fileish_paths = map normalise fileish_args
160     (srcs, objs)         = partition_args normal_fileish_paths [] []
161
162   -- Note: have v_Ld_inputs maintain the order in which 'objs' occurred on 
163   --       the command-line.
164   mapM_ (consIORef v_Ld_inputs) (reverse objs)
165
166         ---------------- Display configuration -----------
167   when (verbosity dflags3 >= 4) $
168         dumpPackages dflags3
169
170   when (verbosity dflags3 >= 3) $ do
171         hPutStrLn stderr ("Hsc static flags: " ++ unwords staticFlags)
172
173         ---------------- Final sanity checking -----------
174   checkOptions cli_mode dflags3 srcs objs
175
176   ---------------- Do the business -----------
177   let alreadyHandled = panic (show cli_mode ++
178                               " should already have been handled")
179   case cli_mode of
180     ShowUsage              -> showGhcUsage dflags3 cli_mode
181     PrintLibdir            -> putStrLn (topDir dflags3)
182     ShowSupportedLanguages -> alreadyHandled
183     ShowVersion            -> alreadyHandled
184     ShowNumVersion         -> alreadyHandled
185     ShowInterface f        -> doShowIface dflags3 f
186     DoMake                 -> doMake session srcs
187     DoMkDependHS           -> doMkDependHS session (map fst srcs)
188     StopBefore p           -> oneShot hsc_env p srcs
189     DoInteractive          -> interactiveUI session srcs Nothing
190     DoEval exprs           -> interactiveUI session srcs $ Just $ reverse exprs
191
192   dumpFinalStats dflags3
193   exitWith ExitSuccess
194
195 #ifndef GHCI
196 interactiveUI :: a -> b -> c -> IO ()
197 interactiveUI _ _ _ = 
198   ghcError (CmdLineError "not built for interactive use")
199 #endif
200
201 -- -----------------------------------------------------------------------------
202 -- Splitting arguments into source files and object files.  This is where we
203 -- interpret the -x <suffix> option, and attach a (Maybe Phase) to each source
204 -- file indicating the phase specified by the -x option in force, if any.
205
206 partition_args :: [String] -> [(String, Maybe Phase)] -> [String]
207                -> ([(String, Maybe Phase)], [String])
208 partition_args [] srcs objs = (reverse srcs, reverse objs)
209 partition_args ("-x":suff:args) srcs objs
210   | "none" <- suff      = partition_args args srcs objs
211   | StopLn <- phase     = partition_args args srcs (slurp ++ objs)
212   | otherwise           = partition_args rest (these_srcs ++ srcs) objs
213         where phase = startPhase suff
214               (slurp,rest) = break (== "-x") args 
215               these_srcs = zip slurp (repeat (Just phase))
216 partition_args (arg:args) srcs objs
217   | looks_like_an_input arg = partition_args args ((arg,Nothing):srcs) objs
218   | otherwise               = partition_args args srcs (arg:objs)
219
220     {-
221       We split out the object files (.o, .dll) and add them
222       to v_Ld_inputs for use by the linker.
223
224       The following things should be considered compilation manager inputs:
225
226        - haskell source files (strings ending in .hs, .lhs or other 
227          haskellish extension),
228
229        - module names (not forgetting hierarchical module names),
230
231        - and finally we consider everything not containing a '.' to be
232          a comp manager input, as shorthand for a .hs or .lhs filename.
233
234       Everything else is considered to be a linker object, and passed
235       straight through to the linker.
236     -}
237 looks_like_an_input :: String -> Bool
238 looks_like_an_input m =  isSourceFilename m 
239                       || looksLikeModuleName m
240                       || '.' `notElem` m
241
242 -- -----------------------------------------------------------------------------
243 -- Option sanity checks
244
245 checkOptions :: CmdLineMode -> DynFlags -> [(String,Maybe Phase)] -> [String] -> IO ()
246      -- Final sanity checking before kicking off a compilation (pipeline).
247 checkOptions cli_mode dflags srcs objs = do
248      -- Complain about any unknown flags
249    let unknown_opts = [ f | (f@('-':_), _) <- srcs ]
250    when (notNull unknown_opts) (unknownFlagsErr unknown_opts)
251
252    when (notNull (filter isRTSWay (wayNames dflags))
253          && isInterpretiveMode cli_mode) $
254         putStrLn ("Warning: -debug, -threaded and -ticky are ignored by GHCi")
255
256         -- -prof and --interactive are not a good combination
257    when (notNull (filter (not . isRTSWay) (wayNames dflags))
258          && isInterpretiveMode cli_mode) $
259       do ghcError (UsageError 
260                    "--interactive can't be used with -prof or -unreg.")
261         -- -ohi sanity check
262    if (isJust (outputHi dflags) && 
263       (isCompManagerMode cli_mode || srcs `lengthExceeds` 1))
264         then ghcError (UsageError "-ohi can only be used when compiling a single source file")
265         else do
266
267         -- -o sanity checking
268    if (srcs `lengthExceeds` 1 && isJust (outputFile dflags)
269          && not (isLinkMode cli_mode))
270         then ghcError (UsageError "can't apply -o to multiple source files")
271         else do
272
273         -- Check that there are some input files
274         -- (except in the interactive case)
275    if null srcs && null objs && needsInputsMode cli_mode
276         then ghcError (UsageError "no input files")
277         else do
278
279      -- Verify that output files point somewhere sensible.
280    verifyOutputFiles dflags
281
282
283 -- Compiler output options
284
285 -- called to verify that the output files & directories
286 -- point somewhere valid. 
287 --
288 -- The assumption is that the directory portion of these output
289 -- options will have to exist by the time 'verifyOutputFiles'
290 -- is invoked.
291 -- 
292 verifyOutputFiles :: DynFlags -> IO ()
293 verifyOutputFiles dflags = do
294   -- not -odir: we create the directory for -odir if it doesn't exist (#2278).
295   let ofile = outputFile dflags
296   when (isJust ofile) $ do
297      let fn = fromJust ofile
298      flg <- doesDirNameExist fn
299      when (not flg) (nonExistentDir "-o" fn)
300   let ohi = outputHi dflags
301   when (isJust ohi) $ do
302      let hi = fromJust ohi
303      flg <- doesDirNameExist hi
304      when (not flg) (nonExistentDir "-ohi" hi)
305  where
306    nonExistentDir flg dir = 
307      ghcError (CmdLineError ("error: directory portion of " ++ 
308                              show dir ++ " does not exist (used with " ++ 
309                              show flg ++ " option.)"))
310
311 -----------------------------------------------------------------------------
312 -- GHC modes of operation
313
314 data CmdLineMode
315   = ShowUsage               -- ghc -?
316   | PrintLibdir             -- ghc --print-libdir
317   | ShowInfo                -- ghc --info
318   | ShowSupportedLanguages  -- ghc --supported-languages
319   | ShowVersion             -- ghc -V/--version
320   | ShowNumVersion          -- ghc --numeric-version
321   | ShowInterface String    -- ghc --show-iface
322   | DoMkDependHS            -- ghc -M
323   | StopBefore Phase        -- ghc -E | -C | -S
324                             -- StopBefore StopLn is the default
325   | DoMake                  -- ghc --make
326   | DoInteractive           -- ghc --interactive
327   | DoEval [String]         -- ghc -e foo -e bar => DoEval ["bar", "foo"]
328   deriving (Show)
329
330 #ifdef GHCI
331 isInteractiveMode :: CmdLineMode -> Bool
332 isInteractiveMode DoInteractive = True
333 isInteractiveMode _             = False
334 #endif
335
336 -- isInterpretiveMode: byte-code compiler involved
337 isInterpretiveMode :: CmdLineMode -> Bool
338 isInterpretiveMode DoInteractive = True
339 isInterpretiveMode (DoEval _)    = True
340 isInterpretiveMode _             = False
341
342 needsInputsMode :: CmdLineMode -> Bool
343 needsInputsMode DoMkDependHS    = True
344 needsInputsMode (StopBefore _)  = True
345 needsInputsMode DoMake          = True
346 needsInputsMode _               = False
347
348 -- True if we are going to attempt to link in this mode.
349 -- (we might not actually link, depending on the GhcLink flag)
350 isLinkMode :: CmdLineMode -> Bool
351 isLinkMode (StopBefore StopLn) = True
352 isLinkMode DoMake              = True
353 isLinkMode _                   = False
354
355 isCompManagerMode :: CmdLineMode -> Bool
356 isCompManagerMode DoMake        = True
357 isCompManagerMode DoInteractive = True
358 isCompManagerMode (DoEval _)    = True
359 isCompManagerMode _             = False
360
361
362 -- -----------------------------------------------------------------------------
363 -- Parsing the mode flag
364
365 parseModeFlags :: [String] -> IO (CmdLineMode, [String], [String])
366 parseModeFlags args = do
367   let ((leftover, errs, warns), (mode, _, flags')) =
368          runCmdLine (processArgs mode_flags args) (StopBefore StopLn, "", []) 
369   when (not (null errs)) $ do
370     ghcError (UsageError (unlines errs))
371   return (mode, flags' ++ leftover, warns)
372
373 type ModeM = CmdLineP (CmdLineMode, String, [String])
374   -- mode flags sometimes give rise to new DynFlags (eg. -C, see below)
375   -- so we collect the new ones and return them.
376
377 mode_flags :: [Flag ModeM]
378 mode_flags =
379   [  ------- help / version ----------------------------------------------
380     Flag "?"                    (PassFlag (setMode ShowUsage))
381          Supported
382   , Flag "-help"                (PassFlag (setMode ShowUsage))
383          Supported
384   , Flag "-print-libdir"        (PassFlag (setMode PrintLibdir))
385          Supported
386   , Flag "V"                    (PassFlag (setMode ShowVersion))
387          Supported
388   , Flag "-version"             (PassFlag (setMode ShowVersion))
389          Supported
390   , Flag "-numeric-version"     (PassFlag (setMode ShowNumVersion))
391          Supported
392   , Flag "-info"                (PassFlag (setMode ShowInfo))
393          Supported
394   , Flag "-supported-languages" (PassFlag (setMode ShowSupportedLanguages))
395          Supported
396
397       ------- interfaces ----------------------------------------------------
398   , Flag "-show-iface"  (HasArg (\f -> setMode (ShowInterface f)
399                                                "--show-iface"))
400          Supported
401
402       ------- primary modes ------------------------------------------------
403   , Flag "M"            (PassFlag (setMode DoMkDependHS))
404          Supported
405   , Flag "E"            (PassFlag (setMode (StopBefore anyHsc)))
406          Supported
407   , Flag "C"            (PassFlag (\f -> do setMode (StopBefore HCc) f
408                                             addFlag "-fvia-C"))
409          Supported
410   , Flag "S"            (PassFlag (setMode (StopBefore As)))
411          Supported
412   , Flag "-make"        (PassFlag (setMode DoMake))
413          Supported
414   , Flag "-interactive" (PassFlag (setMode DoInteractive))
415          Supported
416   , Flag "e"            (HasArg   (\s -> updateMode (updateDoEval s) "-e"))
417          Supported
418
419        -- -fno-code says to stop after Hsc but don't generate any code.
420   , Flag "fno-code"     (PassFlag (\f -> do setMode (StopBefore HCc) f
421                                             addFlag "-fno-code"
422                                             addFlag "-fforce-recomp"))
423          Supported
424   ]
425
426 setMode :: CmdLineMode -> String -> ModeM ()
427 setMode m flag = updateMode (\_ -> m) flag
428
429 updateDoEval :: String -> CmdLineMode -> CmdLineMode
430 updateDoEval expr (DoEval exprs) = DoEval (expr : exprs)
431 updateDoEval expr _              = DoEval [expr]
432
433 updateMode :: (CmdLineMode -> CmdLineMode) -> String -> ModeM ()
434 updateMode f flag = do
435   (old_mode, old_flag, flags') <- getCmdLineState
436   if notNull old_flag && flag /= old_flag
437       then ghcError (UsageError
438                ("cannot use `" ++ old_flag ++ "' with `" ++ flag ++ "'"))
439       else putCmdLineState (f old_mode, flag, flags')
440
441 addFlag :: String -> ModeM ()
442 addFlag s = do
443   (m, f, flags') <- getCmdLineState
444   putCmdLineState (m, f, s:flags')
445
446
447 -- ----------------------------------------------------------------------------
448 -- Run --make mode
449
450 doMake :: Session -> [(String,Maybe Phase)] -> IO ()
451 doMake _    []    = ghcError (UsageError "no input files")
452 doMake sess srcs  = do 
453     let (hs_srcs, non_hs_srcs) = partition haskellish srcs
454
455         haskellish (f,Nothing) = 
456           looksLikeModuleName f || isHaskellSrcFilename f || '.' `notElem` f
457         haskellish (_,Just phase) = 
458           phase `notElem` [As, Cc, CmmCpp, Cmm, StopLn]
459
460     hsc_env <- GHC.sessionHscEnv sess
461     o_files <- mapM (compileFile hsc_env StopLn) non_hs_srcs
462     mapM_ (consIORef v_Ld_inputs) (reverse o_files)
463
464     targets <- mapM (uncurry GHC.guessTarget) hs_srcs
465     GHC.setTargets sess targets
466     ok_flag <- GHC.load sess LoadAllTargets
467     when (failed ok_flag) (exitWith (ExitFailure 1))
468     return ()
469
470
471 -- ---------------------------------------------------------------------------
472 -- --show-iface mode
473
474 doShowIface :: DynFlags -> FilePath -> IO ()
475 doShowIface dflags file = do
476   hsc_env <- newHscEnv dflags
477   showIface hsc_env file
478
479 -- ---------------------------------------------------------------------------
480 -- Various banners and verbosity output.
481
482 showBanner :: CmdLineMode -> DynFlags -> IO ()
483 showBanner _cli_mode dflags = do
484    let verb = verbosity dflags
485
486 #ifdef GHCI
487    -- Show the GHCi banner
488    when (isInteractiveMode _cli_mode && verb >= 1) $ putStrLn ghciWelcomeMsg
489 #endif
490
491    -- Display details of the configuration in verbose mode
492    when (verb >= 2) $
493     do hPutStr stderr "Glasgow Haskell Compiler, Version "
494        hPutStr stderr cProjectVersion
495        hPutStr stderr ", for Haskell 98, stage "
496        hPutStr stderr cStage
497        hPutStr stderr " booted by GHC version "
498        hPutStrLn stderr cBooterVersion
499
500 -- We print out a Read-friendly string, but a prettier one than the
501 -- Show instance gives us
502 showInfo :: IO ()
503 showInfo = do
504     let sq x = " [" ++ x ++ "\n ]"
505     putStrLn $ sq $ concat $ intersperse "\n ," $ map show compilerInfo
506     exitWith ExitSuccess
507
508 showSupportedLanguages :: IO ()
509 showSupportedLanguages = do mapM_ putStrLn supportedLanguages
510                             exitWith ExitSuccess
511
512 showVersion :: IO ()
513 showVersion = do
514   putStrLn (cProjectName ++ ", version " ++ cProjectVersion)
515   exitWith ExitSuccess
516
517 showGhcUsage :: DynFlags -> CmdLineMode -> IO ()
518 showGhcUsage dflags cli_mode = do 
519   let usage_path 
520         | DoInteractive <- cli_mode = ghciUsagePath dflags
521         | otherwise                 = ghcUsagePath dflags
522   usage <- readFile usage_path
523   dump usage
524   exitWith ExitSuccess
525   where
526      dump ""          = return ()
527      dump ('$':'$':s) = putStr progName >> dump s
528      dump (c:s)       = putChar c >> dump s
529
530 dumpFinalStats :: DynFlags -> IO ()
531 dumpFinalStats dflags = 
532   when (dopt Opt_D_faststring_stats dflags) $ dumpFastStringStats dflags
533
534 dumpFastStringStats :: DynFlags -> IO ()
535 dumpFastStringStats dflags = do
536   buckets <- getFastStringTable
537   let (entries, longest, is_z, has_z) = countFS 0 0 0 0 buckets
538       msg = text "FastString stats:" $$
539             nest 4 (vcat [text "size:           " <+> int (length buckets),
540                           text "entries:        " <+> int entries,
541                           text "longest chain:  " <+> int longest,
542                           text "z-encoded:      " <+> (is_z `pcntOf` entries),
543                           text "has z-encoding: " <+> (has_z `pcntOf` entries)
544                          ])
545         -- we usually get more "has z-encoding" than "z-encoded", because
546         -- when we z-encode a string it might hash to the exact same string,
547         -- which will is not counted as "z-encoded".  Only strings whose
548         -- Z-encoding is different from the original string are counted in
549         -- the "z-encoded" total.
550   putMsg dflags msg
551   where
552    x `pcntOf` y = int ((x * 100) `quot` y) <> char '%'
553
554 countFS :: Int -> Int -> Int -> Int -> [[FastString]] -> (Int, Int, Int, Int)
555 countFS entries longest is_z has_z [] = (entries, longest, is_z, has_z)
556 countFS entries longest is_z has_z (b:bs) = 
557   let
558         len = length b
559         longest' = max len longest
560         entries' = entries + len
561         is_zs = length (filter isZEncoded b)
562         has_zs = length (filter hasZEncoding b)
563   in
564         countFS entries' longest' (is_z + is_zs) (has_z + has_zs) bs
565
566 -- -----------------------------------------------------------------------------
567 -- Util
568
569 unknownFlagsErr :: [String] -> a
570 unknownFlagsErr fs = ghcError (UsageError ("unrecognised flags: " ++ unwords fs))