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