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