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