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