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