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 )
39 import BasicTypes ( failed )
46 -- Standard Haskell libraries
48 import System.Environment
50 import System.FilePath
55 -----------------------------------------------------------------------------
58 -- time commands when run with -v
60 -- Win32 support: proper signal handling
61 -- reading the package configuration file is too slow
64 -----------------------------------------------------------------------------
65 -- GHC's command-line interface
69 GHC.defaultErrorHandler defaultDynFlags $ do
71 -- 1. extract the -B flag from the args
75 (minusB_args, argv1) = partition ("-B" `isPrefixOf`) argv0
76 mbMinusB | null minusB_args = Nothing
77 | otherwise = Just (drop 2 (last minusB_args))
79 (argv2, staticFlagWarnings) <- parseStaticFlags argv1
81 -- 2. Parse the "mode" flags (--make, --interactive etc.)
82 (cli_mode, argv3, modeFlagWarnings) <- parseModeFlags argv2
84 -- If all we want to do is to show the version number then do it
85 -- now, before we start a GHC session etc.
86 -- If we do it later then bootstrapping gets confused as it tries
87 -- to find out what version of GHC it's using before package.conf
88 -- exists, so starting the session fails.
90 ShowInfo -> do showInfo
92 ShowSupportedLanguages -> do showSupportedLanguages
94 ShowVersion -> do showVersion
96 ShowNumVersion -> do putStrLn cProjectVersion
100 -- start our GHC session
101 session <- GHC.newSession mbMinusB
103 dflags0 <- GHC.getSessionDynFlags session
105 -- set the default GhcMode, HscTarget and GhcLink. The HscTarget
106 -- can be further adjusted on a module by module basis, using only
107 -- the -fvia-C and -fasm flags. If the default HscTarget is not
108 -- HscC or HscAsm, -fvia-C and -fasm have no effect.
109 let dflt_target = hscTarget dflags0
112 DoInteractive -> (CompManager, HscInterpreted, LinkInMemory)
113 DoEval _ -> (CompManager, HscInterpreted, LinkInMemory)
114 DoMake -> (CompManager, dflt_target, LinkBinary)
115 DoMkDependHS -> (MkDepend, dflt_target, LinkBinary)
116 _ -> (OneShot, dflt_target, LinkBinary)
118 let dflags1 = dflags0{ ghcMode = mode,
121 -- leave out hscOutName for now
122 hscOutName = panic "Main.main:hscOutName not set",
123 verbosity = case cli_mode of
128 -- The rest of the arguments are "dynamic"
129 -- Leftover ones are presumably files
130 (dflags2, fileish_args, dynamicFlagWarnings) <- GHC.parseDynamicFlags dflags1 argv3
132 let flagWarnings = staticFlagWarnings
134 ++ dynamicFlagWarnings
135 handleFlagWarnings dflags2 flagWarnings
137 -- make sure we clean up after ourselves
138 GHC.defaultCleanupHandler dflags2 $ do
140 showBanner cli_mode dflags2
142 -- we've finished manipulating the DynFlags, update the session
143 GHC.setSessionDynFlags session dflags2
144 dflags3 <- GHC.getSessionDynFlags session
145 hsc_env <- GHC.sessionHscEnv session
148 -- To simplify the handling of filepaths, we normalise all filepaths right
149 -- away - e.g., for win32 platforms, backslashes are converted
150 -- into forward slashes.
151 normal_fileish_paths = map normalise fileish_args
152 (srcs, objs) = partition_args normal_fileish_paths [] []
154 -- Note: have v_Ld_inputs maintain the order in which 'objs' occurred on
156 mapM_ (consIORef v_Ld_inputs) (reverse objs)
158 ---------------- Display configuration -----------
159 when (verbosity dflags3 >= 4) $
162 when (verbosity dflags3 >= 3) $ do
163 hPutStrLn stderr ("Hsc static flags: " ++ unwords staticFlags)
165 ---------------- Final sanity checking -----------
166 checkOptions cli_mode dflags3 srcs objs
168 ---------------- Do the business -----------
169 let alreadyHandled = panic (show cli_mode ++
170 " should already have been handled")
172 ShowUsage -> showGhcUsage dflags3 cli_mode
173 PrintLibdir -> putStrLn (topDir dflags3)
174 ShowSupportedLanguages -> alreadyHandled
175 ShowVersion -> alreadyHandled
176 ShowNumVersion -> alreadyHandled
177 ShowInterface f -> doShowIface dflags3 f
178 DoMake -> doMake session srcs
179 DoMkDependHS -> doMkDependHS session (map fst srcs)
180 StopBefore p -> oneShot hsc_env p srcs
181 DoInteractive -> interactiveUI session srcs Nothing
182 DoEval exprs -> interactiveUI session srcs $ Just $ reverse exprs
184 dumpFinalStats dflags3
188 interactiveUI :: a -> b -> c -> IO ()
189 interactiveUI _ _ _ =
190 ghcError (CmdLineError "not built for interactive use")
193 -- -----------------------------------------------------------------------------
194 -- Splitting arguments into source files and object files. This is where we
195 -- interpret the -x <suffix> option, and attach a (Maybe Phase) to each source
196 -- file indicating the phase specified by the -x option in force, if any.
198 partition_args :: [String] -> [(String, Maybe Phase)] -> [String]
199 -> ([(String, Maybe Phase)], [String])
200 partition_args [] srcs objs = (reverse srcs, reverse objs)
201 partition_args ("-x":suff:args) srcs objs
202 | "none" <- suff = partition_args args srcs objs
203 | StopLn <- phase = partition_args args srcs (slurp ++ objs)
204 | otherwise = partition_args rest (these_srcs ++ srcs) objs
205 where phase = startPhase suff
206 (slurp,rest) = break (== "-x") args
207 these_srcs = zip slurp (repeat (Just phase))
208 partition_args (arg:args) srcs objs
209 | looks_like_an_input arg = partition_args args ((arg,Nothing):srcs) objs
210 | otherwise = partition_args args srcs (arg:objs)
213 We split out the object files (.o, .dll) and add them
214 to v_Ld_inputs for use by the linker.
216 The following things should be considered compilation manager inputs:
218 - haskell source files (strings ending in .hs, .lhs or other
219 haskellish extension),
221 - module names (not forgetting hierarchical module names),
223 - and finally we consider everything not containing a '.' to be
224 a comp manager input, as shorthand for a .hs or .lhs filename.
226 Everything else is considered to be a linker object, and passed
227 straight through to the linker.
229 looks_like_an_input :: String -> Bool
230 looks_like_an_input m = isSourceFilename m
231 || looksLikeModuleName m
234 -- -----------------------------------------------------------------------------
235 -- Option sanity checks
237 checkOptions :: CmdLineMode -> DynFlags -> [(String,Maybe Phase)] -> [String] -> IO ()
238 -- Final sanity checking before kicking off a compilation (pipeline).
239 checkOptions cli_mode dflags srcs objs = do
240 -- Complain about any unknown flags
241 let unknown_opts = [ f | (f@('-':_), _) <- srcs ]
242 when (notNull unknown_opts) (unknownFlagsErr unknown_opts)
244 when (notNull (filter isRTSWay (wayNames dflags))
245 && isInterpretiveMode cli_mode) $
246 putStrLn ("Warning: -debug, -threaded and -ticky are ignored by GHCi")
248 -- -prof and --interactive are not a good combination
249 when (notNull (filter (not . isRTSWay) (wayNames dflags))
250 && isInterpretiveMode cli_mode) $
251 do ghcError (UsageError
252 "--interactive can't be used with -prof or -unreg.")
254 if (isJust (outputHi dflags) &&
255 (isCompManagerMode cli_mode || srcs `lengthExceeds` 1))
256 then ghcError (UsageError "-ohi can only be used when compiling a single source file")
259 -- -o sanity checking
260 if (srcs `lengthExceeds` 1 && isJust (outputFile dflags)
261 && not (isLinkMode cli_mode))
262 then ghcError (UsageError "can't apply -o to multiple source files")
265 -- Check that there are some input files
266 -- (except in the interactive case)
267 if null srcs && null objs && needsInputsMode cli_mode
268 then ghcError (UsageError "no input files")
271 -- Verify that output files point somewhere sensible.
272 verifyOutputFiles dflags
275 -- Compiler output options
277 -- called to verify that the output files & directories
278 -- point somewhere valid.
280 -- The assumption is that the directory portion of these output
281 -- options will have to exist by the time 'verifyOutputFiles'
284 verifyOutputFiles :: DynFlags -> IO ()
285 verifyOutputFiles dflags = do
286 -- not -odir: we create the directory for -odir if it doesn't exist (#2278).
287 let ofile = outputFile dflags
288 when (isJust ofile) $ do
289 let fn = fromJust ofile
290 flg <- doesDirNameExist fn
291 when (not flg) (nonExistentDir "-o" fn)
292 let ohi = outputHi dflags
293 when (isJust ohi) $ do
294 let hi = fromJust ohi
295 flg <- doesDirNameExist hi
296 when (not flg) (nonExistentDir "-ohi" hi)
298 nonExistentDir flg dir =
299 ghcError (CmdLineError ("error: directory portion of " ++
300 show dir ++ " does not exist (used with " ++
301 show flg ++ " option.)"))
303 -----------------------------------------------------------------------------
304 -- GHC modes of operation
307 = ShowUsage -- ghc -?
308 | PrintLibdir -- ghc --print-libdir
309 | ShowInfo -- ghc --info
310 | ShowSupportedLanguages -- ghc --supported-languages
311 | ShowVersion -- ghc -V/--version
312 | ShowNumVersion -- ghc --numeric-version
313 | ShowInterface String -- ghc --show-iface
314 | DoMkDependHS -- ghc -M
315 | StopBefore Phase -- ghc -E | -C | -S
316 -- StopBefore StopLn is the default
317 | DoMake -- ghc --make
318 | DoInteractive -- ghc --interactive
319 | DoEval [String] -- ghc -e foo -e bar => DoEval ["bar", "foo"]
323 isInteractiveMode :: CmdLineMode -> Bool
324 isInteractiveMode DoInteractive = True
325 isInteractiveMode _ = False
328 -- isInterpretiveMode: byte-code compiler involved
329 isInterpretiveMode :: CmdLineMode -> Bool
330 isInterpretiveMode DoInteractive = True
331 isInterpretiveMode (DoEval _) = True
332 isInterpretiveMode _ = False
334 needsInputsMode :: CmdLineMode -> Bool
335 needsInputsMode DoMkDependHS = True
336 needsInputsMode (StopBefore _) = True
337 needsInputsMode DoMake = True
338 needsInputsMode _ = False
340 -- True if we are going to attempt to link in this mode.
341 -- (we might not actually link, depending on the GhcLink flag)
342 isLinkMode :: CmdLineMode -> Bool
343 isLinkMode (StopBefore StopLn) = True
344 isLinkMode DoMake = True
347 isCompManagerMode :: CmdLineMode -> Bool
348 isCompManagerMode DoMake = True
349 isCompManagerMode DoInteractive = True
350 isCompManagerMode (DoEval _) = True
351 isCompManagerMode _ = False
354 -- -----------------------------------------------------------------------------
355 -- Parsing the mode flag
357 parseModeFlags :: [String] -> IO (CmdLineMode, [String], [String])
358 parseModeFlags args = do
359 let ((leftover, errs, warns), (mode, _, flags')) =
360 runCmdLine (processArgs mode_flags args) (StopBefore StopLn, "", [])
361 when (not (null errs)) $ do
362 ghcError (UsageError (unlines errs))
363 return (mode, flags' ++ leftover, warns)
365 type ModeM = CmdLineP (CmdLineMode, String, [String])
366 -- mode flags sometimes give rise to new DynFlags (eg. -C, see below)
367 -- so we collect the new ones and return them.
369 mode_flags :: [Flag ModeM]
371 [ ------- help / version ----------------------------------------------
372 Flag "?" (PassFlag (setMode ShowUsage))
374 , Flag "-help" (PassFlag (setMode ShowUsage))
376 , Flag "-print-libdir" (PassFlag (setMode PrintLibdir))
378 , Flag "V" (PassFlag (setMode ShowVersion))
380 , Flag "-version" (PassFlag (setMode ShowVersion))
382 , Flag "-numeric-version" (PassFlag (setMode ShowNumVersion))
384 , Flag "-info" (PassFlag (setMode ShowInfo))
386 , Flag "-supported-languages" (PassFlag (setMode ShowSupportedLanguages))
389 ------- interfaces ----------------------------------------------------
390 , Flag "-show-iface" (HasArg (\f -> setMode (ShowInterface f)
394 ------- primary modes ------------------------------------------------
395 , Flag "M" (PassFlag (setMode DoMkDependHS))
397 , Flag "E" (PassFlag (setMode (StopBefore anyHsc)))
399 , Flag "C" (PassFlag (\f -> do setMode (StopBefore HCc) f
402 , Flag "S" (PassFlag (setMode (StopBefore As)))
404 , Flag "-make" (PassFlag (setMode DoMake))
406 , Flag "-interactive" (PassFlag (setMode DoInteractive))
408 , Flag "e" (HasArg (\s -> updateMode (updateDoEval s) "-e"))
411 -- -fno-code says to stop after Hsc but don't generate any code.
412 , Flag "fno-code" (PassFlag (\f -> do setMode (StopBefore HCc) f
414 addFlag "-fforce-recomp"))
418 setMode :: CmdLineMode -> String -> ModeM ()
419 setMode m flag = updateMode (\_ -> m) flag
421 updateDoEval :: String -> CmdLineMode -> CmdLineMode
422 updateDoEval expr (DoEval exprs) = DoEval (expr : exprs)
423 updateDoEval expr _ = DoEval [expr]
425 updateMode :: (CmdLineMode -> CmdLineMode) -> String -> ModeM ()
426 updateMode f flag = do
427 (old_mode, old_flag, flags') <- getCmdLineState
428 if notNull old_flag && flag /= old_flag
429 then ghcError (UsageError
430 ("cannot use `" ++ old_flag ++ "' with `" ++ flag ++ "'"))
431 else putCmdLineState (f old_mode, flag, flags')
433 addFlag :: String -> ModeM ()
435 (m, f, flags') <- getCmdLineState
436 putCmdLineState (m, f, s:flags')
439 -- ----------------------------------------------------------------------------
442 doMake :: Session -> [(String,Maybe Phase)] -> IO ()
443 doMake _ [] = ghcError (UsageError "no input files")
444 doMake sess srcs = do
445 let (hs_srcs, non_hs_srcs) = partition haskellish srcs
447 haskellish (f,Nothing) =
448 looksLikeModuleName f || isHaskellSrcFilename f || '.' `notElem` f
449 haskellish (_,Just phase) =
450 phase `notElem` [As, Cc, CmmCpp, Cmm, StopLn]
452 hsc_env <- GHC.sessionHscEnv sess
453 o_files <- mapM (compileFile hsc_env StopLn) non_hs_srcs
454 mapM_ (consIORef v_Ld_inputs) (reverse o_files)
456 targets <- mapM (uncurry GHC.guessTarget) hs_srcs
457 GHC.setTargets sess targets
458 ok_flag <- GHC.load sess LoadAllTargets
459 when (failed ok_flag) (exitWith (ExitFailure 1))
463 -- ---------------------------------------------------------------------------
466 doShowIface :: DynFlags -> FilePath -> IO ()
467 doShowIface dflags file = do
468 hsc_env <- newHscEnv dflags
469 showIface hsc_env file
471 -- ---------------------------------------------------------------------------
472 -- Various banners and verbosity output.
474 showBanner :: CmdLineMode -> DynFlags -> IO ()
475 showBanner _cli_mode dflags = do
476 let verb = verbosity dflags
479 -- Show the GHCi banner
480 when (isInteractiveMode _cli_mode && verb >= 1) $ putStrLn ghciWelcomeMsg
483 -- Display details of the configuration in verbose mode
485 do hPutStr stderr "Glasgow Haskell Compiler, Version "
486 hPutStr stderr cProjectVersion
487 hPutStr stderr ", for Haskell 98, stage "
488 hPutStr stderr cStage
489 hPutStr stderr " booted by GHC version "
490 hPutStrLn stderr cBooterVersion
492 -- We print out a Read-friendly string, but a prettier one than the
493 -- Show instance gives us
496 let sq x = " [" ++ x ++ "\n ]"
497 putStrLn $ sq $ concat $ intersperse "\n ," $ map show compilerInfo
500 showSupportedLanguages :: IO ()
501 showSupportedLanguages = do mapM_ putStrLn supportedLanguages
506 putStrLn (cProjectName ++ ", version " ++ cProjectVersion)
509 showGhcUsage :: DynFlags -> CmdLineMode -> IO ()
510 showGhcUsage dflags cli_mode = do
512 | DoInteractive <- cli_mode = ghciUsagePath dflags
513 | otherwise = ghcUsagePath dflags
514 usage <- readFile usage_path
519 dump ('$':'$':s) = putStr progName >> dump s
520 dump (c:s) = putChar c >> dump s
522 dumpFinalStats :: DynFlags -> IO ()
523 dumpFinalStats dflags =
524 when (dopt Opt_D_faststring_stats dflags) $ dumpFastStringStats dflags
526 dumpFastStringStats :: DynFlags -> IO ()
527 dumpFastStringStats dflags = do
528 buckets <- getFastStringTable
529 let (entries, longest, is_z, has_z) = countFS 0 0 0 0 buckets
530 msg = text "FastString stats:" $$
531 nest 4 (vcat [text "size: " <+> int (length buckets),
532 text "entries: " <+> int entries,
533 text "longest chain: " <+> int longest,
534 text "z-encoded: " <+> (is_z `pcntOf` entries),
535 text "has z-encoding: " <+> (has_z `pcntOf` entries)
537 -- we usually get more "has z-encoding" than "z-encoded", because
538 -- when we z-encode a string it might hash to the exact same string,
539 -- which will is not counted as "z-encoded". Only strings whose
540 -- Z-encoding is different from the original string are counted in
541 -- the "z-encoded" total.
544 x `pcntOf` y = int ((x * 100) `quot` y) <> char '%'
546 countFS :: Int -> Int -> Int -> Int -> [[FastString]] -> (Int, Int, Int, Int)
547 countFS entries longest is_z has_z [] = (entries, longest, is_z, has_z)
548 countFS entries longest is_z has_z (b:bs) =
551 longest' = max len longest
552 entries' = entries + len
553 is_zs = length (filter isZEncoded b)
554 has_zs = length (filter hasZEncoding b)
556 countFS entries' longest' (is_z + is_zs) (has_z + has_zs) bs
558 -- -----------------------------------------------------------------------------
561 unknownFlagsErr :: [String] -> a
562 unknownFlagsErr fs = ghcError (UsageError ("unrecognised flags: " ++ unwords fs))