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 ( 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 )
37 import BasicTypes ( failed )
39 import StaticFlagParser
47 import MonadUtils ( liftIO )
49 -- Standard Haskell libraries
51 import System.Environment
53 import System.FilePath
58 -----------------------------------------------------------------------------
61 -- time commands when run with -v
63 -- Win32 support: proper signal handling
64 -- reading the package configuration file is too slow
67 -----------------------------------------------------------------------------
68 -- GHC's command-line interface
73 GHC.defaultErrorHandler defaultDynFlags $ do
74 -- 1. extract the -B flag from the args
78 (minusB_args, argv1) = partition ("-B" `isPrefixOf`) argv0
79 mbMinusB | null minusB_args = Nothing
80 | otherwise = Just (drop 2 (last minusB_args))
82 let argv1' = map (mkGeneralLocated "on the commandline") argv1
83 (argv2, staticFlagWarnings) <- parseStaticFlags argv1'
85 -- 2. Parse the "mode" flags (--make, --interactive etc.)
86 (cli_mode, argv3, modeFlagWarnings) <- parseModeFlags argv2
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.
94 ShowInfo -> do showInfo
96 ShowSupportedLanguages -> do showSupportedLanguages
98 ShowVersion -> do showVersion
100 ShowNumVersion -> do putStrLn cProjectVersion
104 -- start our GHC session
105 GHC.runGhc mbMinusB $ do
107 dflags0 <- GHC.getSessionDynFlags
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
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)
122 let dflags1 = dflags0{ ghcMode = mode,
125 -- leave out hscOutName for now
126 hscOutName = panic "Main.main:hscOutName not set",
127 verbosity = case cli_mode of
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
139 -- The rest of the arguments are "dynamic"
140 -- Leftover ones are presumably files
141 (dflags2, fileish_args, dynamicFlagWarnings) <- GHC.parseDynamicFlags dflags1a argv3
143 let flagWarnings = staticFlagWarnings
145 ++ dynamicFlagWarnings
146 liftIO $ handleFlagWarnings dflags2 flagWarnings
148 -- make sure we clean up after ourselves
149 GHC.defaultCleanupHandler dflags2 $ do
151 liftIO $ showBanner cli_mode dflags2
153 -- we've finished manipulating the DynFlags, update the session
154 GHC.setSessionDynFlags dflags2
155 dflags3 <- GHC.getSessionDynFlags
156 hsc_env <- GHC.getSession
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 [] []
165 -- Note: have v_Ld_inputs maintain the order in which 'objs' occurred on
167 liftIO $ mapM_ (consIORef v_Ld_inputs) (reverse objs)
169 ---------------- Display configuration -----------
170 when (verbosity dflags3 >= 4) $
171 liftIO $ dumpPackages dflags3
173 when (verbosity dflags3 >= 3) $ do
174 liftIO $ hPutStrLn stderr ("Hsc static flags: " ++ unwords staticFlags)
176 ---------------- Final sanity checking -----------
177 liftIO $ checkOptions cli_mode dflags3 srcs objs
179 ---------------- Do the business -----------
180 let alreadyHandled = panic (show cli_mode ++
181 " should already have been handled")
183 handleSourceError (\e -> do
184 GHC.printExceptionAndWarnings e
185 liftIO $ exitWith (ExitFailure 1)) $
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
199 liftIO $ dumpFinalStats dflags3
200 liftIO $ exitWith ExitSuccess
203 interactiveUI :: b -> c -> Ghc ()
205 ghcError (CmdLineError "not built for interactive use")
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.
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)
228 We split out the object files (.o, .dll) and add them
229 to v_Ld_inputs for use by the linker.
231 The following things should be considered compilation manager inputs:
233 - haskell source files (strings ending in .hs, .lhs or other
234 haskellish extension),
236 - module names (not forgetting hierarchical module names),
238 - and finally we consider everything not containing a '.' to be
239 a comp manager input, as shorthand for a .hs or .lhs filename.
241 Everything else is considered to be a linker object, and passed
242 straight through to the linker.
244 looks_like_an_input :: String -> Bool
245 looks_like_an_input m = isSourceFilename m
246 || looksLikeModuleName m
249 -- -----------------------------------------------------------------------------
250 -- Option sanity checks
252 -- | Ensure sanity of options.
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)
262 when (notNull (filter isRTSWay (wayNames dflags))
263 && isInterpretiveMode cli_mode) $
264 putStrLn ("Warning: -debug, -threaded and -ticky are ignored by GHCi")
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.")
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")
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")
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")
289 -- Verify that output files point somewhere sensible.
290 verifyOutputFiles dflags
293 -- Compiler output options
295 -- called to verify that the output files & directories
296 -- point somewhere valid.
298 -- The assumption is that the directory portion of these output
299 -- options will have to exist by the time 'verifyOutputFiles'
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)
316 nonExistentDir flg dir =
317 ghcError (CmdLineError ("error: directory portion of " ++
318 show dir ++ " does not exist (used with " ++
319 show flg ++ " option.)"))
321 -----------------------------------------------------------------------------
322 -- GHC modes of operation
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"]
341 isInteractiveMode :: CmdLineMode -> Bool
342 isInteractiveMode DoInteractive = True
343 isInteractiveMode _ = False
346 -- isInterpretiveMode: byte-code compiler involved
347 isInterpretiveMode :: CmdLineMode -> Bool
348 isInterpretiveMode DoInteractive = True
349 isInterpretiveMode (DoEval _) = True
350 isInterpretiveMode _ = False
352 needsInputsMode :: CmdLineMode -> Bool
353 needsInputsMode DoMkDependHS = True
354 needsInputsMode (StopBefore _) = True
355 needsInputsMode DoMake = True
356 needsInputsMode _ = False
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
365 isCompManagerMode :: CmdLineMode -> Bool
366 isCompManagerMode DoMake = True
367 isCompManagerMode DoInteractive = True
368 isCompManagerMode (DoEval _) = True
369 isCompManagerMode _ = False
372 -- -----------------------------------------------------------------------------
373 -- Parsing the mode flag
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)
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.
387 mode_flags :: [Flag ModeM]
389 [ ------- help / version ----------------------------------------------
390 Flag "?" (PassFlag (setMode ShowUsage))
392 , Flag "-help" (PassFlag (setMode ShowUsage))
394 , Flag "-print-libdir" (PassFlag (setMode PrintLibdir))
396 , Flag "V" (PassFlag (setMode ShowVersion))
398 , Flag "-version" (PassFlag (setMode ShowVersion))
400 , Flag "-numeric-version" (PassFlag (setMode ShowNumVersion))
402 , Flag "-info" (PassFlag (setMode ShowInfo))
404 , Flag "-supported-languages" (PassFlag (setMode ShowSupportedLanguages))
407 ------- interfaces ----------------------------------------------------
408 , Flag "-show-iface" (HasArg (\f -> setMode (ShowInterface f)
412 ------- primary modes ------------------------------------------------
413 , Flag "M" (PassFlag (setMode DoMkDependHS))
415 , Flag "E" (PassFlag (setMode (StopBefore anyHsc)))
417 , Flag "C" (PassFlag (\f -> do setMode (StopBefore HCc) f
420 , Flag "S" (PassFlag (setMode (StopBefore As)))
422 , Flag "-make" (PassFlag (setMode DoMake))
424 , Flag "-interactive" (PassFlag (setMode DoInteractive))
426 , Flag "e" (HasArg (\s -> updateMode (updateDoEval s) "-e"))
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
432 addFlag "-fforce-recomp"))
436 setMode :: CmdLineMode -> String -> ModeM ()
437 setMode m flag = updateMode (\_ -> m) flag
439 updateDoEval :: String -> CmdLineMode -> CmdLineMode
440 updateDoEval expr (DoEval exprs) = DoEval (expr : exprs)
441 updateDoEval expr _ = DoEval [expr]
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')
451 addFlag :: String -> ModeM ()
453 (m, f, flags') <- getCmdLineState
454 -- XXX Can we get a useful Loc?
455 putCmdLineState (m, f, mkGeneralLocated "addFlag" s : flags')
458 -- ----------------------------------------------------------------------------
461 doMake :: [(String,Maybe Phase)] -> Ghc ()
462 doMake [] = ghcError (UsageError "no input files")
464 let (hs_srcs, non_hs_srcs) = partition haskellish srcs
466 haskellish (f,Nothing) =
467 looksLikeModuleName f || isHaskellSrcFilename f || '.' `notElem` f
468 haskellish (_,Just phase) =
469 phase `notElem` [As, Cc, CmmCpp, Cmm, StopLn]
471 hsc_env <- GHC.getSession
472 o_files <- mapM (\x -> do
473 f <- compileFile hsc_env StopLn x
477 liftIO $ mapM_ (consIORef v_Ld_inputs) (reverse o_files)
479 targets <- mapM (uncurry GHC.guessTarget) hs_srcs
480 GHC.setTargets targets
481 ok_flag <- GHC.load LoadAllTargets
483 when (failed ok_flag) (liftIO $ exitWith (ExitFailure 1))
487 -- ---------------------------------------------------------------------------
490 doShowIface :: DynFlags -> FilePath -> IO ()
491 doShowIface dflags file = do
492 hsc_env <- newHscEnv dflags
493 showIface hsc_env file
495 -- ---------------------------------------------------------------------------
496 -- Various banners and verbosity output.
498 showBanner :: CmdLineMode -> DynFlags -> IO ()
499 showBanner _cli_mode dflags = do
500 let verb = verbosity dflags
503 -- Show the GHCi banner
504 when (isInteractiveMode _cli_mode && verb >= 1) $ putStrLn ghciWelcomeMsg
507 -- Display details of the configuration in verbose mode
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
516 -- We print out a Read-friendly string, but a prettier one than the
517 -- Show instance gives us
520 let sq x = " [" ++ x ++ "\n ]"
521 putStrLn $ sq $ concat $ intersperse "\n ," $ map show compilerInfo
524 showSupportedLanguages :: IO ()
525 showSupportedLanguages = do mapM_ putStrLn supportedLanguages
530 putStrLn (cProjectName ++ ", version " ++ cProjectVersion)
533 showGhcUsage :: DynFlags -> CmdLineMode -> IO ()
534 showGhcUsage dflags cli_mode = do
536 | DoInteractive <- cli_mode = ghciUsagePath dflags
537 | otherwise = ghcUsagePath dflags
538 usage <- readFile usage_path
543 dump ('$':'$':s) = putStr progName >> dump s
544 dump (c:s) = putChar c >> dump s
546 dumpFinalStats :: DynFlags -> IO ()
547 dumpFinalStats dflags =
548 when (dopt Opt_D_faststring_stats dflags) $ dumpFastStringStats dflags
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)
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.
568 x `pcntOf` y = int ((x * 100) `quot` y) <> char '%'
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) =
575 longest' = max len longest
576 entries' = entries + len
577 is_zs = length (filter isZEncoded b)
578 has_zs = length (filter hasZEncoding b)
580 countFS entries' longest' (is_z + is_zs) (has_z + has_zs) bs
582 -- -----------------------------------------------------------------------------
585 unknownFlagsErr :: [String] -> a
586 unknownFlagsErr fs = ghcError (UsageError ("unrecognised flags: " ++ unwords fs))