1 {-# OPTIONS -fno-warn-incomplete-patterns -optc-DNON_POSIX_SOURCE #-}
3 -----------------------------------------------------------------------------
7 -- (c) The University of Glasgow 2005
9 -----------------------------------------------------------------------------
11 module Main (main) where
13 #include "HsVersions.h"
15 -- The official GHC API
17 import GHC ( Session, DynFlags(..), HscTarget(..),
18 GhcMode(..), GhcLink(..),
19 LoadHowMuch(..), dopt, DynFlag(..) )
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 )
28 import InteractiveUI ( interactiveUI, ghciWelcomeMsg )
31 -- Various other random stuff that we need
34 import Packages ( dumpPackages )
35 import DriverPhases ( Phase(..), isSourceFilename, anyHsc,
36 startPhase, isHaskellSrcFilename )
38 import StaticFlagParser
40 import BasicTypes ( failed )
47 -- Standard Haskell libraries
49 import System.Environment
51 import System.FilePath
56 -----------------------------------------------------------------------------
59 -- time commands when run with -v
61 -- Win32 support: proper signal handling
62 -- reading the package configuration file is too slow
65 -----------------------------------------------------------------------------
66 -- GHC's command-line interface
70 GHC.defaultErrorHandler defaultDynFlags $ do
72 -- 1. extract the -B flag from the args
76 (minusB_args, argv1) = partition ("-B" `isPrefixOf`) argv0
77 mbMinusB | null minusB_args = Nothing
78 | otherwise = Just (drop 2 (last minusB_args))
80 (argv2, staticFlagWarnings) <- parseStaticFlags argv1
82 -- 2. Parse the "mode" flags (--make, --interactive etc.)
83 (cli_mode, argv3, modeFlagWarnings) <- parseModeFlags argv2
85 -- If all we want to do is to show the version number then do it
86 -- now, before we start a GHC session etc.
87 -- If we do it later then bootstrapping gets confused as it tries
88 -- to find out what version of GHC it's using before package.conf
89 -- exists, so starting the session fails.
91 ShowInfo -> do showInfo
93 ShowSupportedLanguages -> do showSupportedLanguages
95 ShowVersion -> do showVersion
97 ShowNumVersion -> do putStrLn cProjectVersion
101 -- start our GHC session
102 session <- GHC.newSession mbMinusB
104 dflags0 <- GHC.getSessionDynFlags session
106 -- set the default GhcMode, HscTarget and GhcLink. The HscTarget
107 -- can be further adjusted on a module by module basis, using only
108 -- the -fvia-C and -fasm flags. If the default HscTarget is not
109 -- HscC or HscAsm, -fvia-C and -fasm have no effect.
110 let dflt_target = hscTarget dflags0
113 DoInteractive -> (CompManager, HscInterpreted, LinkInMemory)
114 DoEval _ -> (CompManager, HscInterpreted, LinkInMemory)
115 DoMake -> (CompManager, dflt_target, LinkBinary)
116 DoMkDependHS -> (MkDepend, dflt_target, LinkBinary)
117 _ -> (OneShot, dflt_target, LinkBinary)
119 let dflags1 = dflags0{ ghcMode = mode,
122 -- leave out hscOutName for now
123 hscOutName = panic "Main.main:hscOutName not set",
124 verbosity = case cli_mode of
129 -- turn on -fimplicit-import-qualified for GHCi now, so that it
130 -- can be overriden from the command-line
131 dflags1a | DoInteractive <- cli_mode = imp_qual_enabled
132 | DoEval _ <- cli_mode = imp_qual_enabled
133 | otherwise = dflags1
134 where imp_qual_enabled = dflags1 `dopt_set` Opt_ImplicitImportQualified
136 -- The rest of the arguments are "dynamic"
137 -- Leftover ones are presumably files
138 (dflags2, fileish_args, dynamicFlagWarnings) <- GHC.parseDynamicFlags dflags1a argv3
140 let flagWarnings = staticFlagWarnings
142 ++ dynamicFlagWarnings
143 handleFlagWarnings dflags2 flagWarnings
145 -- make sure we clean up after ourselves
146 GHC.defaultCleanupHandler dflags2 $ do
148 showBanner cli_mode dflags2
150 -- we've finished manipulating the DynFlags, update the session
151 GHC.setSessionDynFlags session dflags2
152 dflags3 <- GHC.getSessionDynFlags session
153 hsc_env <- GHC.sessionHscEnv session
156 -- To simplify the handling of filepaths, we normalise all filepaths right
157 -- away - e.g., for win32 platforms, backslashes are converted
158 -- into forward slashes.
159 normal_fileish_paths = map normalise fileish_args
160 (srcs, objs) = partition_args normal_fileish_paths [] []
162 -- Note: have v_Ld_inputs maintain the order in which 'objs' occurred on
164 mapM_ (consIORef v_Ld_inputs) (reverse objs)
166 ---------------- Display configuration -----------
167 when (verbosity dflags3 >= 4) $
170 when (verbosity dflags3 >= 3) $ do
171 hPutStrLn stderr ("Hsc static flags: " ++ unwords staticFlags)
173 ---------------- Final sanity checking -----------
174 checkOptions cli_mode dflags3 srcs objs
176 ---------------- Do the business -----------
177 let alreadyHandled = panic (show cli_mode ++
178 " should already have been handled")
180 ShowUsage -> showGhcUsage dflags3 cli_mode
181 PrintLibdir -> putStrLn (topDir dflags3)
182 ShowSupportedLanguages -> alreadyHandled
183 ShowVersion -> alreadyHandled
184 ShowNumVersion -> alreadyHandled
185 ShowInterface f -> doShowIface dflags3 f
186 DoMake -> doMake session srcs
187 DoMkDependHS -> doMkDependHS session (map fst srcs)
188 StopBefore p -> oneShot hsc_env p srcs
189 DoInteractive -> interactiveUI session srcs Nothing
190 DoEval exprs -> interactiveUI session srcs $ Just $ reverse exprs
192 dumpFinalStats dflags3
196 interactiveUI :: a -> b -> c -> IO ()
197 interactiveUI _ _ _ =
198 ghcError (CmdLineError "not built for interactive use")
201 -- -----------------------------------------------------------------------------
202 -- Splitting arguments into source files and object files. This is where we
203 -- interpret the -x <suffix> option, and attach a (Maybe Phase) to each source
204 -- file indicating the phase specified by the -x option in force, if any.
206 partition_args :: [String] -> [(String, Maybe Phase)] -> [String]
207 -> ([(String, Maybe Phase)], [String])
208 partition_args [] srcs objs = (reverse srcs, reverse objs)
209 partition_args ("-x":suff:args) srcs objs
210 | "none" <- suff = partition_args args srcs objs
211 | StopLn <- phase = partition_args args srcs (slurp ++ objs)
212 | otherwise = partition_args rest (these_srcs ++ srcs) objs
213 where phase = startPhase suff
214 (slurp,rest) = break (== "-x") args
215 these_srcs = zip slurp (repeat (Just phase))
216 partition_args (arg:args) srcs objs
217 | looks_like_an_input arg = partition_args args ((arg,Nothing):srcs) objs
218 | otherwise = partition_args args srcs (arg:objs)
221 We split out the object files (.o, .dll) and add them
222 to v_Ld_inputs for use by the linker.
224 The following things should be considered compilation manager inputs:
226 - haskell source files (strings ending in .hs, .lhs or other
227 haskellish extension),
229 - module names (not forgetting hierarchical module names),
231 - and finally we consider everything not containing a '.' to be
232 a comp manager input, as shorthand for a .hs or .lhs filename.
234 Everything else is considered to be a linker object, and passed
235 straight through to the linker.
237 looks_like_an_input :: String -> Bool
238 looks_like_an_input m = isSourceFilename m
239 || looksLikeModuleName m
242 -- -----------------------------------------------------------------------------
243 -- Option sanity checks
245 checkOptions :: CmdLineMode -> DynFlags -> [(String,Maybe Phase)] -> [String] -> IO ()
246 -- Final sanity checking before kicking off a compilation (pipeline).
247 checkOptions cli_mode dflags srcs objs = do
248 -- Complain about any unknown flags
249 let unknown_opts = [ f | (f@('-':_), _) <- srcs ]
250 when (notNull unknown_opts) (unknownFlagsErr unknown_opts)
252 when (notNull (filter isRTSWay (wayNames dflags))
253 && isInterpretiveMode cli_mode) $
254 putStrLn ("Warning: -debug, -threaded and -ticky are ignored by GHCi")
256 -- -prof and --interactive are not a good combination
257 when (notNull (filter (not . isRTSWay) (wayNames dflags))
258 && isInterpretiveMode cli_mode) $
259 do ghcError (UsageError
260 "--interactive can't be used with -prof or -unreg.")
262 if (isJust (outputHi dflags) &&
263 (isCompManagerMode cli_mode || srcs `lengthExceeds` 1))
264 then ghcError (UsageError "-ohi can only be used when compiling a single source file")
267 -- -o sanity checking
268 if (srcs `lengthExceeds` 1 && isJust (outputFile dflags)
269 && not (isLinkMode cli_mode))
270 then ghcError (UsageError "can't apply -o to multiple source files")
273 -- Check that there are some input files
274 -- (except in the interactive case)
275 if null srcs && null objs && needsInputsMode cli_mode
276 then ghcError (UsageError "no input files")
279 -- Verify that output files point somewhere sensible.
280 verifyOutputFiles dflags
283 -- Compiler output options
285 -- called to verify that the output files & directories
286 -- point somewhere valid.
288 -- The assumption is that the directory portion of these output
289 -- options will have to exist by the time 'verifyOutputFiles'
292 verifyOutputFiles :: DynFlags -> IO ()
293 verifyOutputFiles dflags = do
294 -- not -odir: we create the directory for -odir if it doesn't exist (#2278).
295 let ofile = outputFile dflags
296 when (isJust ofile) $ do
297 let fn = fromJust ofile
298 flg <- doesDirNameExist fn
299 when (not flg) (nonExistentDir "-o" fn)
300 let ohi = outputHi dflags
301 when (isJust ohi) $ do
302 let hi = fromJust ohi
303 flg <- doesDirNameExist hi
304 when (not flg) (nonExistentDir "-ohi" hi)
306 nonExistentDir flg dir =
307 ghcError (CmdLineError ("error: directory portion of " ++
308 show dir ++ " does not exist (used with " ++
309 show flg ++ " option.)"))
311 -----------------------------------------------------------------------------
312 -- GHC modes of operation
315 = ShowUsage -- ghc -?
316 | PrintLibdir -- ghc --print-libdir
317 | ShowInfo -- ghc --info
318 | ShowSupportedLanguages -- ghc --supported-languages
319 | ShowVersion -- ghc -V/--version
320 | ShowNumVersion -- ghc --numeric-version
321 | ShowInterface String -- ghc --show-iface
322 | DoMkDependHS -- ghc -M
323 | StopBefore Phase -- ghc -E | -C | -S
324 -- StopBefore StopLn is the default
325 | DoMake -- ghc --make
326 | DoInteractive -- ghc --interactive
327 | DoEval [String] -- ghc -e foo -e bar => DoEval ["bar", "foo"]
331 isInteractiveMode :: CmdLineMode -> Bool
332 isInteractiveMode DoInteractive = True
333 isInteractiveMode _ = False
336 -- isInterpretiveMode: byte-code compiler involved
337 isInterpretiveMode :: CmdLineMode -> Bool
338 isInterpretiveMode DoInteractive = True
339 isInterpretiveMode (DoEval _) = True
340 isInterpretiveMode _ = False
342 needsInputsMode :: CmdLineMode -> Bool
343 needsInputsMode DoMkDependHS = True
344 needsInputsMode (StopBefore _) = True
345 needsInputsMode DoMake = True
346 needsInputsMode _ = False
348 -- True if we are going to attempt to link in this mode.
349 -- (we might not actually link, depending on the GhcLink flag)
350 isLinkMode :: CmdLineMode -> Bool
351 isLinkMode (StopBefore StopLn) = True
352 isLinkMode DoMake = True
355 isCompManagerMode :: CmdLineMode -> Bool
356 isCompManagerMode DoMake = True
357 isCompManagerMode DoInteractive = True
358 isCompManagerMode (DoEval _) = True
359 isCompManagerMode _ = False
362 -- -----------------------------------------------------------------------------
363 -- Parsing the mode flag
365 parseModeFlags :: [String] -> IO (CmdLineMode, [String], [String])
366 parseModeFlags args = do
367 let ((leftover, errs, warns), (mode, _, flags')) =
368 runCmdLine (processArgs mode_flags args) (StopBefore StopLn, "", [])
369 when (not (null errs)) $ do
370 ghcError (UsageError (unlines errs))
371 return (mode, flags' ++ leftover, warns)
373 type ModeM = CmdLineP (CmdLineMode, String, [String])
374 -- mode flags sometimes give rise to new DynFlags (eg. -C, see below)
375 -- so we collect the new ones and return them.
377 mode_flags :: [Flag ModeM]
379 [ ------- help / version ----------------------------------------------
380 Flag "?" (PassFlag (setMode ShowUsage))
382 , Flag "-help" (PassFlag (setMode ShowUsage))
384 , Flag "-print-libdir" (PassFlag (setMode PrintLibdir))
386 , Flag "V" (PassFlag (setMode ShowVersion))
388 , Flag "-version" (PassFlag (setMode ShowVersion))
390 , Flag "-numeric-version" (PassFlag (setMode ShowNumVersion))
392 , Flag "-info" (PassFlag (setMode ShowInfo))
394 , Flag "-supported-languages" (PassFlag (setMode ShowSupportedLanguages))
397 ------- interfaces ----------------------------------------------------
398 , Flag "-show-iface" (HasArg (\f -> setMode (ShowInterface f)
402 ------- primary modes ------------------------------------------------
403 , Flag "M" (PassFlag (setMode DoMkDependHS))
405 , Flag "E" (PassFlag (setMode (StopBefore anyHsc)))
407 , Flag "C" (PassFlag (\f -> do setMode (StopBefore HCc) f
410 , Flag "S" (PassFlag (setMode (StopBefore As)))
412 , Flag "-make" (PassFlag (setMode DoMake))
414 , Flag "-interactive" (PassFlag (setMode DoInteractive))
416 , Flag "e" (HasArg (\s -> updateMode (updateDoEval s) "-e"))
419 -- -fno-code says to stop after Hsc but don't generate any code.
420 , Flag "fno-code" (PassFlag (\f -> do setMode (StopBefore HCc) f
422 addFlag "-fforce-recomp"))
426 setMode :: CmdLineMode -> String -> ModeM ()
427 setMode m flag = updateMode (\_ -> m) flag
429 updateDoEval :: String -> CmdLineMode -> CmdLineMode
430 updateDoEval expr (DoEval exprs) = DoEval (expr : exprs)
431 updateDoEval expr _ = DoEval [expr]
433 updateMode :: (CmdLineMode -> CmdLineMode) -> String -> ModeM ()
434 updateMode f flag = do
435 (old_mode, old_flag, flags') <- getCmdLineState
436 if notNull old_flag && flag /= old_flag
437 then ghcError (UsageError
438 ("cannot use `" ++ old_flag ++ "' with `" ++ flag ++ "'"))
439 else putCmdLineState (f old_mode, flag, flags')
441 addFlag :: String -> ModeM ()
443 (m, f, flags') <- getCmdLineState
444 putCmdLineState (m, f, s:flags')
447 -- ----------------------------------------------------------------------------
450 doMake :: Session -> [(String,Maybe Phase)] -> IO ()
451 doMake _ [] = ghcError (UsageError "no input files")
452 doMake sess srcs = do
453 let (hs_srcs, non_hs_srcs) = partition haskellish srcs
455 haskellish (f,Nothing) =
456 looksLikeModuleName f || isHaskellSrcFilename f || '.' `notElem` f
457 haskellish (_,Just phase) =
458 phase `notElem` [As, Cc, CmmCpp, Cmm, StopLn]
460 hsc_env <- GHC.sessionHscEnv sess
461 o_files <- mapM (compileFile hsc_env StopLn) non_hs_srcs
462 mapM_ (consIORef v_Ld_inputs) (reverse o_files)
464 targets <- mapM (uncurry GHC.guessTarget) hs_srcs
465 GHC.setTargets sess targets
466 ok_flag <- GHC.load sess LoadAllTargets
467 when (failed ok_flag) (exitWith (ExitFailure 1))
471 -- ---------------------------------------------------------------------------
474 doShowIface :: DynFlags -> FilePath -> IO ()
475 doShowIface dflags file = do
476 hsc_env <- newHscEnv dflags
477 showIface hsc_env file
479 -- ---------------------------------------------------------------------------
480 -- Various banners and verbosity output.
482 showBanner :: CmdLineMode -> DynFlags -> IO ()
483 showBanner _cli_mode dflags = do
484 let verb = verbosity dflags
487 -- Show the GHCi banner
488 when (isInteractiveMode _cli_mode && verb >= 1) $ putStrLn ghciWelcomeMsg
491 -- Display details of the configuration in verbose mode
493 do hPutStr stderr "Glasgow Haskell Compiler, Version "
494 hPutStr stderr cProjectVersion
495 hPutStr stderr ", for Haskell 98, stage "
496 hPutStr stderr cStage
497 hPutStr stderr " booted by GHC version "
498 hPutStrLn stderr cBooterVersion
500 -- We print out a Read-friendly string, but a prettier one than the
501 -- Show instance gives us
504 let sq x = " [" ++ x ++ "\n ]"
505 putStrLn $ sq $ concat $ intersperse "\n ," $ map show compilerInfo
508 showSupportedLanguages :: IO ()
509 showSupportedLanguages = do mapM_ putStrLn supportedLanguages
514 putStrLn (cProjectName ++ ", version " ++ cProjectVersion)
517 showGhcUsage :: DynFlags -> CmdLineMode -> IO ()
518 showGhcUsage dflags cli_mode = do
520 | DoInteractive <- cli_mode = ghciUsagePath dflags
521 | otherwise = ghcUsagePath dflags
522 usage <- readFile usage_path
527 dump ('$':'$':s) = putStr progName >> dump s
528 dump (c:s) = putChar c >> dump s
530 dumpFinalStats :: DynFlags -> IO ()
531 dumpFinalStats dflags =
532 when (dopt Opt_D_faststring_stats dflags) $ dumpFastStringStats dflags
534 dumpFastStringStats :: DynFlags -> IO ()
535 dumpFastStringStats dflags = do
536 buckets <- getFastStringTable
537 let (entries, longest, is_z, has_z) = countFS 0 0 0 0 buckets
538 msg = text "FastString stats:" $$
539 nest 4 (vcat [text "size: " <+> int (length buckets),
540 text "entries: " <+> int entries,
541 text "longest chain: " <+> int longest,
542 text "z-encoded: " <+> (is_z `pcntOf` entries),
543 text "has z-encoding: " <+> (has_z `pcntOf` entries)
545 -- we usually get more "has z-encoding" than "z-encoded", because
546 -- when we z-encode a string it might hash to the exact same string,
547 -- which will is not counted as "z-encoded". Only strings whose
548 -- Z-encoding is different from the original string are counted in
549 -- the "z-encoded" total.
552 x `pcntOf` y = int ((x * 100) `quot` y) <> char '%'
554 countFS :: Int -> Int -> Int -> Int -> [[FastString]] -> (Int, Int, Int, Int)
555 countFS entries longest is_z has_z [] = (entries, longest, is_z, has_z)
556 countFS entries longest is_z has_z (b:bs) =
559 longest' = max len longest
560 entries' = entries + len
561 is_zs = length (filter isZEncoded b)
562 has_zs = length (filter hasZEncoding b)
564 countFS entries' longest' (is_z + is_zs) (has_z + has_zs) bs
566 -- -----------------------------------------------------------------------------
569 unknownFlagsErr :: [String] -> a
570 unknownFlagsErr fs = ghcError (UsageError ("unrecognised flags: " ++ unwords fs))