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