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 -- turn on -fimplicit-import-qualified for GHCi now, so that it
129 -- can be overriden from the command-line
130 dflags1a | DoInteractive <- cli_mode = imp_qual_enabled
131 | DoEval _ <- cli_mode = imp_qual_enabled
132 | otherwise = dflags1
133 where imp_qual_enabled = dflags1 `dopt_set` Opt_ImplicitImportQualified
135 -- The rest of the arguments are "dynamic"
136 -- Leftover ones are presumably files
137 (dflags2, fileish_args, dynamicFlagWarnings) <- GHC.parseDynamicFlags dflags1a argv3
139 let flagWarnings = staticFlagWarnings
141 ++ dynamicFlagWarnings
142 handleFlagWarnings dflags2 flagWarnings
144 -- make sure we clean up after ourselves
145 GHC.defaultCleanupHandler dflags2 $ do
147 showBanner cli_mode dflags2
149 -- we've finished manipulating the DynFlags, update the session
150 GHC.setSessionDynFlags session dflags2
151 dflags3 <- GHC.getSessionDynFlags session
152 hsc_env <- GHC.sessionHscEnv session
155 -- To simplify the handling of filepaths, we normalise all filepaths right
156 -- away - e.g., for win32 platforms, backslashes are converted
157 -- into forward slashes.
158 normal_fileish_paths = map normalise fileish_args
159 (srcs, objs) = partition_args normal_fileish_paths [] []
161 -- Note: have v_Ld_inputs maintain the order in which 'objs' occurred on
163 mapM_ (consIORef v_Ld_inputs) (reverse objs)
165 ---------------- Display configuration -----------
166 when (verbosity dflags3 >= 4) $
169 when (verbosity dflags3 >= 3) $ do
170 hPutStrLn stderr ("Hsc static flags: " ++ unwords staticFlags)
172 ---------------- Final sanity checking -----------
173 checkOptions cli_mode dflags3 srcs objs
175 ---------------- Do the business -----------
176 let alreadyHandled = panic (show cli_mode ++
177 " should already have been handled")
179 ShowUsage -> showGhcUsage dflags3 cli_mode
180 PrintLibdir -> putStrLn (topDir dflags3)
181 ShowSupportedLanguages -> alreadyHandled
182 ShowVersion -> alreadyHandled
183 ShowNumVersion -> alreadyHandled
184 ShowInterface f -> doShowIface dflags3 f
185 DoMake -> doMake session srcs
186 DoMkDependHS -> doMkDependHS session (map fst srcs)
187 StopBefore p -> oneShot hsc_env p srcs
188 DoInteractive -> interactiveUI session srcs Nothing
189 DoEval exprs -> interactiveUI session srcs $ Just $ reverse exprs
191 dumpFinalStats dflags3
195 interactiveUI :: a -> b -> c -> IO ()
196 interactiveUI _ _ _ =
197 ghcError (CmdLineError "not built for interactive use")
200 -- -----------------------------------------------------------------------------
201 -- Splitting arguments into source files and object files. This is where we
202 -- interpret the -x <suffix> option, and attach a (Maybe Phase) to each source
203 -- file indicating the phase specified by the -x option in force, if any.
205 partition_args :: [String] -> [(String, Maybe Phase)] -> [String]
206 -> ([(String, Maybe Phase)], [String])
207 partition_args [] srcs objs = (reverse srcs, reverse objs)
208 partition_args ("-x":suff:args) srcs objs
209 | "none" <- suff = partition_args args srcs objs
210 | StopLn <- phase = partition_args args srcs (slurp ++ objs)
211 | otherwise = partition_args rest (these_srcs ++ srcs) objs
212 where phase = startPhase suff
213 (slurp,rest) = break (== "-x") args
214 these_srcs = zip slurp (repeat (Just phase))
215 partition_args (arg:args) srcs objs
216 | looks_like_an_input arg = partition_args args ((arg,Nothing):srcs) objs
217 | otherwise = partition_args args srcs (arg:objs)
220 We split out the object files (.o, .dll) and add them
221 to v_Ld_inputs for use by the linker.
223 The following things should be considered compilation manager inputs:
225 - haskell source files (strings ending in .hs, .lhs or other
226 haskellish extension),
228 - module names (not forgetting hierarchical module names),
230 - and finally we consider everything not containing a '.' to be
231 a comp manager input, as shorthand for a .hs or .lhs filename.
233 Everything else is considered to be a linker object, and passed
234 straight through to the linker.
236 looks_like_an_input :: String -> Bool
237 looks_like_an_input m = isSourceFilename m
238 || looksLikeModuleName m
241 -- -----------------------------------------------------------------------------
242 -- Option sanity checks
244 checkOptions :: CmdLineMode -> DynFlags -> [(String,Maybe Phase)] -> [String] -> IO ()
245 -- Final sanity checking before kicking off a compilation (pipeline).
246 checkOptions cli_mode dflags srcs objs = do
247 -- Complain about any unknown flags
248 let unknown_opts = [ f | (f@('-':_), _) <- srcs ]
249 when (notNull unknown_opts) (unknownFlagsErr unknown_opts)
251 when (notNull (filter isRTSWay (wayNames dflags))
252 && isInterpretiveMode cli_mode) $
253 putStrLn ("Warning: -debug, -threaded and -ticky are ignored by GHCi")
255 -- -prof and --interactive are not a good combination
256 when (notNull (filter (not . isRTSWay) (wayNames dflags))
257 && isInterpretiveMode cli_mode) $
258 do ghcError (UsageError
259 "--interactive can't be used with -prof or -unreg.")
261 if (isJust (outputHi dflags) &&
262 (isCompManagerMode cli_mode || srcs `lengthExceeds` 1))
263 then ghcError (UsageError "-ohi can only be used when compiling a single source file")
266 -- -o sanity checking
267 if (srcs `lengthExceeds` 1 && isJust (outputFile dflags)
268 && not (isLinkMode cli_mode))
269 then ghcError (UsageError "can't apply -o to multiple source files")
272 -- Check that there are some input files
273 -- (except in the interactive case)
274 if null srcs && null objs && needsInputsMode cli_mode
275 then ghcError (UsageError "no input files")
278 -- Verify that output files point somewhere sensible.
279 verifyOutputFiles dflags
282 -- Compiler output options
284 -- called to verify that the output files & directories
285 -- point somewhere valid.
287 -- The assumption is that the directory portion of these output
288 -- options will have to exist by the time 'verifyOutputFiles'
291 verifyOutputFiles :: DynFlags -> IO ()
292 verifyOutputFiles dflags = do
293 -- not -odir: we create the directory for -odir if it doesn't exist (#2278).
294 let ofile = outputFile dflags
295 when (isJust ofile) $ do
296 let fn = fromJust ofile
297 flg <- doesDirNameExist fn
298 when (not flg) (nonExistentDir "-o" fn)
299 let ohi = outputHi dflags
300 when (isJust ohi) $ do
301 let hi = fromJust ohi
302 flg <- doesDirNameExist hi
303 when (not flg) (nonExistentDir "-ohi" hi)
305 nonExistentDir flg dir =
306 ghcError (CmdLineError ("error: directory portion of " ++
307 show dir ++ " does not exist (used with " ++
308 show flg ++ " option.)"))
310 -----------------------------------------------------------------------------
311 -- GHC modes of operation
314 = ShowUsage -- ghc -?
315 | PrintLibdir -- ghc --print-libdir
316 | ShowInfo -- ghc --info
317 | ShowSupportedLanguages -- ghc --supported-languages
318 | ShowVersion -- ghc -V/--version
319 | ShowNumVersion -- ghc --numeric-version
320 | ShowInterface String -- ghc --show-iface
321 | DoMkDependHS -- ghc -M
322 | StopBefore Phase -- ghc -E | -C | -S
323 -- StopBefore StopLn is the default
324 | DoMake -- ghc --make
325 | DoInteractive -- ghc --interactive
326 | DoEval [String] -- ghc -e foo -e bar => DoEval ["bar", "foo"]
330 isInteractiveMode :: CmdLineMode -> Bool
331 isInteractiveMode DoInteractive = True
332 isInteractiveMode _ = False
335 -- isInterpretiveMode: byte-code compiler involved
336 isInterpretiveMode :: CmdLineMode -> Bool
337 isInterpretiveMode DoInteractive = True
338 isInterpretiveMode (DoEval _) = True
339 isInterpretiveMode _ = False
341 needsInputsMode :: CmdLineMode -> Bool
342 needsInputsMode DoMkDependHS = True
343 needsInputsMode (StopBefore _) = True
344 needsInputsMode DoMake = True
345 needsInputsMode _ = False
347 -- True if we are going to attempt to link in this mode.
348 -- (we might not actually link, depending on the GhcLink flag)
349 isLinkMode :: CmdLineMode -> Bool
350 isLinkMode (StopBefore StopLn) = True
351 isLinkMode DoMake = True
354 isCompManagerMode :: CmdLineMode -> Bool
355 isCompManagerMode DoMake = True
356 isCompManagerMode DoInteractive = True
357 isCompManagerMode (DoEval _) = True
358 isCompManagerMode _ = False
361 -- -----------------------------------------------------------------------------
362 -- Parsing the mode flag
364 parseModeFlags :: [String] -> IO (CmdLineMode, [String], [String])
365 parseModeFlags args = do
366 let ((leftover, errs, warns), (mode, _, flags')) =
367 runCmdLine (processArgs mode_flags args) (StopBefore StopLn, "", [])
368 when (not (null errs)) $ do
369 ghcError (UsageError (unlines errs))
370 return (mode, flags' ++ leftover, warns)
372 type ModeM = CmdLineP (CmdLineMode, String, [String])
373 -- mode flags sometimes give rise to new DynFlags (eg. -C, see below)
374 -- so we collect the new ones and return them.
376 mode_flags :: [Flag ModeM]
378 [ ------- help / version ----------------------------------------------
379 Flag "?" (PassFlag (setMode ShowUsage))
381 , Flag "-help" (PassFlag (setMode ShowUsage))
383 , Flag "-print-libdir" (PassFlag (setMode PrintLibdir))
385 , Flag "V" (PassFlag (setMode ShowVersion))
387 , Flag "-version" (PassFlag (setMode ShowVersion))
389 , Flag "-numeric-version" (PassFlag (setMode ShowNumVersion))
391 , Flag "-info" (PassFlag (setMode ShowInfo))
393 , Flag "-supported-languages" (PassFlag (setMode ShowSupportedLanguages))
396 ------- interfaces ----------------------------------------------------
397 , Flag "-show-iface" (HasArg (\f -> setMode (ShowInterface f)
401 ------- primary modes ------------------------------------------------
402 , Flag "M" (PassFlag (setMode DoMkDependHS))
404 , Flag "E" (PassFlag (setMode (StopBefore anyHsc)))
406 , Flag "C" (PassFlag (\f -> do setMode (StopBefore HCc) f
409 , Flag "S" (PassFlag (setMode (StopBefore As)))
411 , Flag "-make" (PassFlag (setMode DoMake))
413 , Flag "-interactive" (PassFlag (setMode DoInteractive))
415 , Flag "e" (HasArg (\s -> updateMode (updateDoEval s) "-e"))
418 -- -fno-code says to stop after Hsc but don't generate any code.
419 , Flag "fno-code" (PassFlag (\f -> do setMode (StopBefore HCc) f
421 addFlag "-fforce-recomp"))
425 setMode :: CmdLineMode -> String -> ModeM ()
426 setMode m flag = updateMode (\_ -> m) flag
428 updateDoEval :: String -> CmdLineMode -> CmdLineMode
429 updateDoEval expr (DoEval exprs) = DoEval (expr : exprs)
430 updateDoEval expr _ = DoEval [expr]
432 updateMode :: (CmdLineMode -> CmdLineMode) -> String -> ModeM ()
433 updateMode f flag = do
434 (old_mode, old_flag, flags') <- getCmdLineState
435 if notNull old_flag && flag /= old_flag
436 then ghcError (UsageError
437 ("cannot use `" ++ old_flag ++ "' with `" ++ flag ++ "'"))
438 else putCmdLineState (f old_mode, flag, flags')
440 addFlag :: String -> ModeM ()
442 (m, f, flags') <- getCmdLineState
443 putCmdLineState (m, f, s:flags')
446 -- ----------------------------------------------------------------------------
449 doMake :: Session -> [(String,Maybe Phase)] -> IO ()
450 doMake _ [] = ghcError (UsageError "no input files")
451 doMake sess srcs = do
452 let (hs_srcs, non_hs_srcs) = partition haskellish srcs
454 haskellish (f,Nothing) =
455 looksLikeModuleName f || isHaskellSrcFilename f || '.' `notElem` f
456 haskellish (_,Just phase) =
457 phase `notElem` [As, Cc, CmmCpp, Cmm, StopLn]
459 hsc_env <- GHC.sessionHscEnv sess
460 o_files <- mapM (compileFile hsc_env StopLn) non_hs_srcs
461 mapM_ (consIORef v_Ld_inputs) (reverse o_files)
463 targets <- mapM (uncurry GHC.guessTarget) hs_srcs
464 GHC.setTargets sess targets
465 ok_flag <- GHC.load sess LoadAllTargets
466 when (failed ok_flag) (exitWith (ExitFailure 1))
470 -- ---------------------------------------------------------------------------
473 doShowIface :: DynFlags -> FilePath -> IO ()
474 doShowIface dflags file = do
475 hsc_env <- newHscEnv dflags
476 showIface hsc_env file
478 -- ---------------------------------------------------------------------------
479 -- Various banners and verbosity output.
481 showBanner :: CmdLineMode -> DynFlags -> IO ()
482 showBanner _cli_mode dflags = do
483 let verb = verbosity dflags
486 -- Show the GHCi banner
487 when (isInteractiveMode _cli_mode && verb >= 1) $ putStrLn ghciWelcomeMsg
490 -- Display details of the configuration in verbose mode
492 do hPutStr stderr "Glasgow Haskell Compiler, Version "
493 hPutStr stderr cProjectVersion
494 hPutStr stderr ", for Haskell 98, stage "
495 hPutStr stderr cStage
496 hPutStr stderr " booted by GHC version "
497 hPutStrLn stderr cBooterVersion
499 -- We print out a Read-friendly string, but a prettier one than the
500 -- Show instance gives us
503 let sq x = " [" ++ x ++ "\n ]"
504 putStrLn $ sq $ concat $ intersperse "\n ," $ map show compilerInfo
507 showSupportedLanguages :: IO ()
508 showSupportedLanguages = do mapM_ putStrLn supportedLanguages
513 putStrLn (cProjectName ++ ", version " ++ cProjectVersion)
516 showGhcUsage :: DynFlags -> CmdLineMode -> IO ()
517 showGhcUsage dflags cli_mode = do
519 | DoInteractive <- cli_mode = ghciUsagePath dflags
520 | otherwise = ghcUsagePath dflags
521 usage <- readFile usage_path
526 dump ('$':'$':s) = putStr progName >> dump s
527 dump (c:s) = putChar c >> dump s
529 dumpFinalStats :: DynFlags -> IO ()
530 dumpFinalStats dflags =
531 when (dopt Opt_D_faststring_stats dflags) $ dumpFastStringStats dflags
533 dumpFastStringStats :: DynFlags -> IO ()
534 dumpFastStringStats dflags = do
535 buckets <- getFastStringTable
536 let (entries, longest, is_z, has_z) = countFS 0 0 0 0 buckets
537 msg = text "FastString stats:" $$
538 nest 4 (vcat [text "size: " <+> int (length buckets),
539 text "entries: " <+> int entries,
540 text "longest chain: " <+> int longest,
541 text "z-encoded: " <+> (is_z `pcntOf` entries),
542 text "has z-encoding: " <+> (has_z `pcntOf` entries)
544 -- we usually get more "has z-encoding" than "z-encoded", because
545 -- when we z-encode a string it might hash to the exact same string,
546 -- which will is not counted as "z-encoded". Only strings whose
547 -- Z-encoding is different from the original string are counted in
548 -- the "z-encoded" total.
551 x `pcntOf` y = int ((x * 100) `quot` y) <> char '%'
553 countFS :: Int -> Int -> Int -> Int -> [[FastString]] -> (Int, Int, Int, Int)
554 countFS entries longest is_z has_z [] = (entries, longest, is_z, has_z)
555 countFS entries longest is_z has_z (b:bs) =
558 longest' = max len longest
559 entries' = entries + len
560 is_zs = length (filter isZEncoded b)
561 has_zs = length (filter hasZEncoding b)
563 countFS entries' longest' (is_z + is_zs) (has_z + has_zs) bs
565 -- -----------------------------------------------------------------------------
568 unknownFlagsErr :: [String] -> a
569 unknownFlagsErr fs = ghcError (UsageError ("unrecognised flags: " ++ unwords fs))