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
47 import Control.Exception ( throwDyn )
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 -- The rest of the arguments are "dynamic"
130 -- Leftover ones are presumably files
131 (dflags2, fileish_args, dynamicFlagWarnings) <- GHC.parseDynamicFlags dflags1 argv3
133 let flagWarnings = staticFlagWarnings
135 ++ dynamicFlagWarnings
136 handleFlagWarnings dflags2 flagWarnings
138 -- make sure we clean up after ourselves
139 GHC.defaultCleanupHandler dflags2 $ do
141 showBanner cli_mode dflags2
143 -- we've finished manipulating the DynFlags, update the session
144 GHC.setSessionDynFlags session dflags2
145 dflags3 <- GHC.getSessionDynFlags session
146 hsc_env <- GHC.sessionHscEnv session
149 -- To simplify the handling of filepaths, we normalise all filepaths right
150 -- away - e.g., for win32 platforms, backslashes are converted
151 -- into forward slashes.
152 normal_fileish_paths = map normalise fileish_args
153 (srcs, objs) = partition_args normal_fileish_paths [] []
155 -- Note: have v_Ld_inputs maintain the order in which 'objs' occurred on
157 mapM_ (consIORef v_Ld_inputs) (reverse objs)
159 ---------------- Display configuration -----------
160 when (verbosity dflags3 >= 4) $
163 when (verbosity dflags3 >= 3) $ do
164 hPutStrLn stderr ("Hsc static flags: " ++ unwords staticFlags)
166 ---------------- Final sanity checking -----------
167 checkOptions cli_mode dflags3 srcs objs
169 ---------------- Do the business -----------
170 let alreadyHandled = panic (show cli_mode ++
171 " should already have been handled")
173 ShowUsage -> showGhcUsage dflags3 cli_mode
174 PrintLibdir -> putStrLn (topDir dflags3)
175 ShowSupportedLanguages -> alreadyHandled
176 ShowVersion -> alreadyHandled
177 ShowNumVersion -> alreadyHandled
178 ShowInterface f -> doShowIface dflags3 f
179 DoMake -> doMake session srcs
180 DoMkDependHS -> doMkDependHS session (map fst srcs)
181 StopBefore p -> oneShot hsc_env p srcs
182 DoInteractive -> interactiveUI session srcs Nothing
183 DoEval exprs -> interactiveUI session srcs $ Just $ reverse exprs
185 dumpFinalStats dflags3
189 interactiveUI :: a -> b -> c -> IO ()
190 interactiveUI _ _ _ =
191 throwDyn (CmdLineError "not built for interactive use")
194 -- -----------------------------------------------------------------------------
195 -- Splitting arguments into source files and object files. This is where we
196 -- interpret the -x <suffix> option, and attach a (Maybe Phase) to each source
197 -- file indicating the phase specified by the -x option in force, if any.
199 partition_args :: [String] -> [(String, Maybe Phase)] -> [String]
200 -> ([(String, Maybe Phase)], [String])
201 partition_args [] srcs objs = (reverse srcs, reverse objs)
202 partition_args ("-x":suff:args) srcs objs
203 | "none" <- suff = partition_args args srcs objs
204 | StopLn <- phase = partition_args args srcs (slurp ++ objs)
205 | otherwise = partition_args rest (these_srcs ++ srcs) objs
206 where phase = startPhase suff
207 (slurp,rest) = break (== "-x") args
208 these_srcs = zip slurp (repeat (Just phase))
209 partition_args (arg:args) srcs objs
210 | looks_like_an_input arg = partition_args args ((arg,Nothing):srcs) objs
211 | otherwise = partition_args args srcs (arg:objs)
214 We split out the object files (.o, .dll) and add them
215 to v_Ld_inputs for use by the linker.
217 The following things should be considered compilation manager inputs:
219 - haskell source files (strings ending in .hs, .lhs or other
220 haskellish extension),
222 - module names (not forgetting hierarchical module names),
224 - and finally we consider everything not containing a '.' to be
225 a comp manager input, as shorthand for a .hs or .lhs filename.
227 Everything else is considered to be a linker object, and passed
228 straight through to the linker.
230 looks_like_an_input :: String -> Bool
231 looks_like_an_input m = isSourceFilename m
232 || looksLikeModuleName m
235 -- -----------------------------------------------------------------------------
236 -- Option sanity checks
238 checkOptions :: CmdLineMode -> DynFlags -> [(String,Maybe Phase)] -> [String] -> IO ()
239 -- Final sanity checking before kicking off a compilation (pipeline).
240 checkOptions cli_mode dflags srcs objs = do
241 -- Complain about any unknown flags
242 let unknown_opts = [ f | (f@('-':_), _) <- srcs ]
243 when (notNull unknown_opts) (unknownFlagsErr unknown_opts)
245 when (notNull (filter isRTSWay (wayNames dflags))
246 && isInterpretiveMode cli_mode) $
247 putStrLn ("Warning: -debug, -threaded and -ticky are ignored by GHCi")
249 -- -prof and --interactive are not a good combination
250 when (notNull (filter (not . isRTSWay) (wayNames dflags))
251 && isInterpretiveMode cli_mode) $
252 do throwDyn (UsageError
253 "--interactive can't be used with -prof or -unreg.")
255 if (isJust (outputHi dflags) &&
256 (isCompManagerMode cli_mode || srcs `lengthExceeds` 1))
257 then throwDyn (UsageError "-ohi can only be used when compiling a single source file")
260 -- -o sanity checking
261 if (srcs `lengthExceeds` 1 && isJust (outputFile dflags)
262 && not (isLinkMode cli_mode))
263 then throwDyn (UsageError "can't apply -o to multiple source files")
266 -- Check that there are some input files
267 -- (except in the interactive case)
268 if null srcs && null objs && needsInputsMode cli_mode
269 then throwDyn (UsageError "no input files")
272 -- Verify that output files point somewhere sensible.
273 verifyOutputFiles dflags
276 -- Compiler output options
278 -- called to verify that the output files & directories
279 -- point somewhere valid.
281 -- The assumption is that the directory portion of these output
282 -- options will have to exist by the time 'verifyOutputFiles'
285 verifyOutputFiles :: DynFlags -> IO ()
286 verifyOutputFiles dflags = do
287 -- not -odir: we create the directory for -odir if it doesn't exist (#2278).
288 let ofile = outputFile dflags
289 when (isJust ofile) $ do
290 let fn = fromJust ofile
291 flg <- doesDirNameExist fn
292 when (not flg) (nonExistentDir "-o" fn)
293 let ohi = outputHi dflags
294 when (isJust ohi) $ do
295 let hi = fromJust ohi
296 flg <- doesDirNameExist hi
297 when (not flg) (nonExistentDir "-ohi" hi)
299 nonExistentDir flg dir =
300 throwDyn (CmdLineError ("error: directory portion of " ++
301 show dir ++ " does not exist (used with " ++
302 show flg ++ " option.)"))
304 -----------------------------------------------------------------------------
305 -- GHC modes of operation
308 = ShowUsage -- ghc -?
309 | PrintLibdir -- ghc --print-libdir
310 | ShowInfo -- ghc --info
311 | ShowSupportedLanguages -- ghc --supported-languages
312 | ShowVersion -- ghc -V/--version
313 | ShowNumVersion -- ghc --numeric-version
314 | ShowInterface String -- ghc --show-iface
315 | DoMkDependHS -- ghc -M
316 | StopBefore Phase -- ghc -E | -C | -S
317 -- StopBefore StopLn is the default
318 | DoMake -- ghc --make
319 | DoInteractive -- ghc --interactive
320 | DoEval [String] -- ghc -e foo -e bar => DoEval ["bar", "foo"]
324 isInteractiveMode :: CmdLineMode -> Bool
325 isInteractiveMode DoInteractive = True
326 isInteractiveMode _ = False
329 -- isInterpretiveMode: byte-code compiler involved
330 isInterpretiveMode :: CmdLineMode -> Bool
331 isInterpretiveMode DoInteractive = True
332 isInterpretiveMode (DoEval _) = True
333 isInterpretiveMode _ = False
335 needsInputsMode :: CmdLineMode -> Bool
336 needsInputsMode DoMkDependHS = True
337 needsInputsMode (StopBefore _) = True
338 needsInputsMode DoMake = True
339 needsInputsMode _ = False
341 -- True if we are going to attempt to link in this mode.
342 -- (we might not actually link, depending on the GhcLink flag)
343 isLinkMode :: CmdLineMode -> Bool
344 isLinkMode (StopBefore StopLn) = True
345 isLinkMode DoMake = True
348 isCompManagerMode :: CmdLineMode -> Bool
349 isCompManagerMode DoMake = True
350 isCompManagerMode DoInteractive = True
351 isCompManagerMode (DoEval _) = True
352 isCompManagerMode _ = False
355 -- -----------------------------------------------------------------------------
356 -- Parsing the mode flag
358 parseModeFlags :: [String] -> IO (CmdLineMode, [String], [String])
359 parseModeFlags args = do
360 let ((leftover, errs, warns), (mode, _, flags')) =
361 runCmdLine (processArgs mode_flags args) (StopBefore StopLn, "", [])
362 when (not (null errs)) $ do
363 throwDyn (UsageError (unlines errs))
364 return (mode, flags' ++ leftover, warns)
366 type ModeM = CmdLineP (CmdLineMode, String, [String])
367 -- mode flags sometimes give rise to new DynFlags (eg. -C, see below)
368 -- so we collect the new ones and return them.
370 mode_flags :: [Flag ModeM]
372 [ ------- help / version ----------------------------------------------
373 Flag "?" (PassFlag (setMode ShowUsage))
375 , Flag "-help" (PassFlag (setMode ShowUsage))
377 , Flag "-print-libdir" (PassFlag (setMode PrintLibdir))
379 , Flag "V" (PassFlag (setMode ShowVersion))
381 , Flag "-version" (PassFlag (setMode ShowVersion))
383 , Flag "-numeric-version" (PassFlag (setMode ShowNumVersion))
385 , Flag "-info" (PassFlag (setMode ShowInfo))
387 , Flag "-supported-languages" (PassFlag (setMode ShowSupportedLanguages))
390 ------- interfaces ----------------------------------------------------
391 , Flag "-show-iface" (HasArg (\f -> setMode (ShowInterface f)
395 ------- primary modes ------------------------------------------------
396 , Flag "M" (PassFlag (setMode DoMkDependHS))
398 , Flag "E" (PassFlag (setMode (StopBefore anyHsc)))
400 , Flag "C" (PassFlag (\f -> do setMode (StopBefore HCc) f
403 , Flag "S" (PassFlag (setMode (StopBefore As)))
405 , Flag "-make" (PassFlag (setMode DoMake))
407 , Flag "-interactive" (PassFlag (setMode DoInteractive))
409 , Flag "e" (HasArg (\s -> updateMode (updateDoEval s) "-e"))
412 -- -fno-code says to stop after Hsc but don't generate any code.
413 , Flag "fno-code" (PassFlag (\f -> do setMode (StopBefore HCc) f
415 addFlag "-fforce-recomp"))
419 setMode :: CmdLineMode -> String -> ModeM ()
420 setMode m flag = updateMode (\_ -> m) flag
422 updateDoEval :: String -> CmdLineMode -> CmdLineMode
423 updateDoEval expr (DoEval exprs) = DoEval (expr : exprs)
424 updateDoEval expr _ = DoEval [expr]
426 updateMode :: (CmdLineMode -> CmdLineMode) -> String -> ModeM ()
427 updateMode f flag = do
428 (old_mode, old_flag, flags') <- getCmdLineState
429 if notNull old_flag && flag /= old_flag
430 then throwDyn (UsageError
431 ("cannot use `" ++ old_flag ++ "' with `" ++ flag ++ "'"))
432 else putCmdLineState (f old_mode, flag, flags')
434 addFlag :: String -> ModeM ()
436 (m, f, flags') <- getCmdLineState
437 putCmdLineState (m, f, s:flags')
440 -- ----------------------------------------------------------------------------
443 doMake :: Session -> [(String,Maybe Phase)] -> IO ()
444 doMake _ [] = throwDyn (UsageError "no input files")
445 doMake sess srcs = do
446 let (hs_srcs, non_hs_srcs) = partition haskellish srcs
448 haskellish (f,Nothing) =
449 looksLikeModuleName f || isHaskellSrcFilename f || '.' `notElem` f
450 haskellish (_,Just phase) =
451 phase `notElem` [As, Cc, CmmCpp, Cmm, StopLn]
453 hsc_env <- GHC.sessionHscEnv sess
454 o_files <- mapM (compileFile hsc_env StopLn) non_hs_srcs
455 mapM_ (consIORef v_Ld_inputs) (reverse o_files)
457 targets <- mapM (uncurry GHC.guessTarget) hs_srcs
458 GHC.setTargets sess targets
459 ok_flag <- GHC.load sess LoadAllTargets
460 when (failed ok_flag) (exitWith (ExitFailure 1))
464 -- ---------------------------------------------------------------------------
467 doShowIface :: DynFlags -> FilePath -> IO ()
468 doShowIface dflags file = do
469 hsc_env <- newHscEnv dflags
470 showIface hsc_env file
472 -- ---------------------------------------------------------------------------
473 -- Various banners and verbosity output.
475 showBanner :: CmdLineMode -> DynFlags -> IO ()
476 showBanner _cli_mode dflags = do
477 let verb = verbosity dflags
480 -- Show the GHCi banner
481 when (isInteractiveMode _cli_mode && verb >= 1) $ putStrLn ghciWelcomeMsg
484 -- Display details of the configuration in verbose mode
486 do hPutStr stderr "Glasgow Haskell Compiler, Version "
487 hPutStr stderr cProjectVersion
488 hPutStr stderr ", for Haskell 98, stage "
489 hPutStr stderr cStage
490 hPutStr stderr " booted by GHC version "
491 hPutStrLn stderr cBooterVersion
493 -- We print out a Read-friendly string, but a prettier one than the
494 -- Show instance gives us
497 let sq x = " [" ++ x ++ "\n ]"
498 putStrLn $ sq $ concat $ intersperse "\n ," $ map show compilerInfo
501 showSupportedLanguages :: IO ()
502 showSupportedLanguages = do mapM_ putStrLn supportedLanguages
507 putStrLn (cProjectName ++ ", version " ++ cProjectVersion)
510 showGhcUsage :: DynFlags -> CmdLineMode -> IO ()
511 showGhcUsage dflags cli_mode = do
513 | DoInteractive <- cli_mode = ghciUsagePath dflags
514 | otherwise = ghcUsagePath dflags
515 usage <- readFile usage_path
520 dump ('$':'$':s) = putStr progName >> dump s
521 dump (c:s) = putChar c >> dump s
523 dumpFinalStats :: DynFlags -> IO ()
524 dumpFinalStats dflags =
525 when (dopt Opt_D_faststring_stats dflags) $ dumpFastStringStats dflags
527 dumpFastStringStats :: DynFlags -> IO ()
528 dumpFastStringStats dflags = do
529 buckets <- getFastStringTable
530 let (entries, longest, is_z, has_z) = countFS 0 0 0 0 buckets
531 msg = text "FastString stats:" $$
532 nest 4 (vcat [text "size: " <+> int (length buckets),
533 text "entries: " <+> int entries,
534 text "longest chain: " <+> int longest,
535 text "z-encoded: " <+> (is_z `pcntOf` entries),
536 text "has z-encoding: " <+> (has_z `pcntOf` entries)
538 -- we usually get more "has z-encoding" than "z-encoded", because
539 -- when we z-encode a string it might hash to the exact same string,
540 -- which will is not counted as "z-encoded". Only strings whose
541 -- Z-encoding is different from the original string are counted in
542 -- the "z-encoded" total.
545 x `pcntOf` y = int ((x * 100) `quot` y) <> char '%'
547 countFS :: Int -> Int -> Int -> Int -> [[FastString]] -> (Int, Int, Int, Int)
548 countFS entries longest is_z has_z [] = (entries, longest, is_z, has_z)
549 countFS entries longest is_z has_z (b:bs) =
552 longest' = max len longest
553 entries' = entries + len
554 is_zs = length (filter isZEncoded b)
555 has_zs = length (filter hasZEncoding b)
557 countFS entries' longest' (is_z + is_zs) (has_z + has_zs) bs
559 -- -----------------------------------------------------------------------------
562 unknownFlagsErr :: [String] -> a
563 unknownFlagsErr fs = throwDyn (UsageError ("unrecognised flags: " ++ unwords fs))