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 (m_uber_mode, 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 -- ShowUsage currently has to be handled specially, as it needs to
95 -- actually start up GHC so that it can find the usage.txt files
96 -- in the libdir. It would be nice to embed the text in the
97 -- executable so that we don't have to do that, and things are more
99 Just ShowUsage -> return ()
103 ShowSupportedLanguages -> showSupportedLanguages
104 ShowVersion -> showVersion
105 ShowNumVersion -> putStrLn cProjectVersion
109 -- start our GHC session
110 GHC.runGhc mbMinusB $ do
112 dflags0 <- GHC.getSessionDynFlags
114 -- set the default GhcMode, HscTarget and GhcLink. The HscTarget
115 -- can be further adjusted on a module by module basis, using only
116 -- the -fvia-C and -fasm flags. If the default HscTarget is not
117 -- HscC or HscAsm, -fvia-C and -fasm have no effect.
118 let dflt_target = hscTarget dflags0
121 DoInteractive -> (CompManager, HscInterpreted, LinkInMemory)
122 DoEval _ -> (CompManager, HscInterpreted, LinkInMemory)
123 DoMake -> (CompManager, dflt_target, LinkBinary)
124 DoMkDependHS -> (MkDepend, dflt_target, LinkBinary)
125 _ -> (OneShot, dflt_target, LinkBinary)
127 let dflags1 = dflags0{ ghcMode = mode,
130 -- leave out hscOutName for now
131 hscOutName = panic "Main.main:hscOutName not set",
132 verbosity = case cli_mode of
137 -- turn on -fimplicit-import-qualified for GHCi now, so that it
138 -- can be overriden from the command-line
139 dflags1a | DoInteractive <- cli_mode = imp_qual_enabled
140 | DoEval _ <- cli_mode = imp_qual_enabled
141 | otherwise = dflags1
142 where imp_qual_enabled = dflags1 `dopt_set` Opt_ImplicitImportQualified
144 -- The rest of the arguments are "dynamic"
145 -- Leftover ones are presumably files
146 (dflags2, fileish_args, dynamicFlagWarnings) <- GHC.parseDynamicFlags dflags1a argv3
148 -- As noted earlier, currently we hvae to handle ShowUsage down here
150 Just ShowUsage -> liftIO $ showGhcUsage dflags2 cli_mode
153 let flagWarnings = staticFlagWarnings
155 ++ dynamicFlagWarnings
156 liftIO $ handleFlagWarnings dflags2 flagWarnings
158 -- make sure we clean up after ourselves
159 GHC.defaultCleanupHandler dflags2 $ do
161 liftIO $ showBanner cli_mode dflags2
163 -- we've finished manipulating the DynFlags, update the session
164 GHC.setSessionDynFlags dflags2
165 dflags3 <- GHC.getSessionDynFlags
166 hsc_env <- GHC.getSession
169 -- To simplify the handling of filepaths, we normalise all filepaths right
170 -- away - e.g., for win32 platforms, backslashes are converted
171 -- into forward slashes.
172 normal_fileish_paths = map (normalise . unLoc) fileish_args
173 (srcs, objs) = partition_args normal_fileish_paths [] []
175 -- Note: have v_Ld_inputs maintain the order in which 'objs' occurred on
177 liftIO $ mapM_ (consIORef v_Ld_inputs) (reverse objs)
179 ---------------- Display configuration -----------
180 when (verbosity dflags3 >= 4) $
181 liftIO $ dumpPackages dflags3
183 when (verbosity dflags3 >= 3) $ do
184 liftIO $ hPutStrLn stderr ("Hsc static flags: " ++ unwords staticFlags)
186 ---------------- Final sanity checking -----------
187 liftIO $ checkOptions cli_mode dflags3 srcs objs
189 ---------------- Do the business -----------
190 handleSourceError (\e -> do
191 GHC.printExceptionAndWarnings e
192 liftIO $ exitWith (ExitFailure 1)) $ do
194 PrintLibdir -> liftIO $ putStrLn (topDir dflags3)
195 ShowInterface f -> liftIO $ doShowIface dflags3 f
196 DoMake -> doMake srcs
197 DoMkDependHS -> doMkDependHS (map fst srcs)
198 StopBefore p -> oneShot hsc_env p srcs >> GHC.printWarnings
199 DoInteractive -> interactiveUI srcs Nothing
200 DoEval exprs -> interactiveUI srcs $ Just $ reverse exprs
202 liftIO $ dumpFinalStats dflags3
203 liftIO $ exitWith ExitSuccess
206 interactiveUI :: b -> c -> Ghc ()
208 ghcError (CmdLineError "not built for interactive use")
211 -- -----------------------------------------------------------------------------
212 -- Splitting arguments into source files and object files. This is where we
213 -- interpret the -x <suffix> option, and attach a (Maybe Phase) to each source
214 -- file indicating the phase specified by the -x option in force, if any.
216 partition_args :: [String] -> [(String, Maybe Phase)] -> [String]
217 -> ([(String, Maybe Phase)], [String])
218 partition_args [] srcs objs = (reverse srcs, reverse objs)
219 partition_args ("-x":suff:args) srcs objs
220 | "none" <- suff = partition_args args srcs objs
221 | StopLn <- phase = partition_args args srcs (slurp ++ objs)
222 | otherwise = partition_args rest (these_srcs ++ srcs) objs
223 where phase = startPhase suff
224 (slurp,rest) = break (== "-x") args
225 these_srcs = zip slurp (repeat (Just phase))
226 partition_args (arg:args) srcs objs
227 | looks_like_an_input arg = partition_args args ((arg,Nothing):srcs) objs
228 | otherwise = partition_args args srcs (arg:objs)
231 We split out the object files (.o, .dll) and add them
232 to v_Ld_inputs for use by the linker.
234 The following things should be considered compilation manager inputs:
236 - haskell source files (strings ending in .hs, .lhs or other
237 haskellish extension),
239 - module names (not forgetting hierarchical module names),
241 - and finally we consider everything not containing a '.' to be
242 a comp manager input, as shorthand for a .hs or .lhs filename.
244 Everything else is considered to be a linker object, and passed
245 straight through to the linker.
247 looks_like_an_input :: String -> Bool
248 looks_like_an_input m = isSourceFilename m
249 || looksLikeModuleName m
252 -- -----------------------------------------------------------------------------
253 -- Option sanity checks
255 -- | Ensure sanity of options.
257 -- Throws 'UsageError' or 'CmdLineError' if not.
258 checkOptions :: CmdLineMode -> DynFlags -> [(String,Maybe Phase)] -> [String] -> IO ()
259 -- Final sanity checking before kicking off a compilation (pipeline).
260 checkOptions cli_mode dflags srcs objs = do
261 -- Complain about any unknown flags
262 let unknown_opts = [ f | (f@('-':_), _) <- srcs ]
263 when (notNull unknown_opts) (unknownFlagsErr unknown_opts)
265 when (notNull (filter isRTSWay (wayNames dflags))
266 && isInterpretiveMode cli_mode) $
267 hPutStrLn stderr ("Warning: -debug, -threaded and -ticky are ignored by GHCi")
269 -- -prof and --interactive are not a good combination
270 when (notNull (filter (not . isRTSWay) (wayNames dflags))
271 && isInterpretiveMode cli_mode) $
272 do ghcError (UsageError
273 "--interactive can't be used with -prof or -unreg.")
275 if (isJust (outputHi dflags) &&
276 (isCompManagerMode cli_mode || srcs `lengthExceeds` 1))
277 then ghcError (UsageError "-ohi can only be used when compiling a single source file")
280 -- -o sanity checking
281 if (srcs `lengthExceeds` 1 && isJust (outputFile dflags)
282 && not (isLinkMode cli_mode))
283 then ghcError (UsageError "can't apply -o to multiple source files")
286 let not_linking = not (isLinkMode cli_mode) || isNoLink (ghcLink dflags)
288 when (not_linking && not (null objs)) $
289 hPutStrLn stderr ("Warning: the following files would be used as linker inputs, but linking is not being done: " ++ unwords objs)
291 -- Check that there are some input files
292 -- (except in the interactive case)
293 if null srcs && (null objs || not_linking) && needsInputsMode cli_mode
294 then ghcError (UsageError "no input files")
297 -- Verify that output files point somewhere sensible.
298 verifyOutputFiles dflags
301 -- Compiler output options
303 -- called to verify that the output files & directories
304 -- point somewhere valid.
306 -- The assumption is that the directory portion of these output
307 -- options will have to exist by the time 'verifyOutputFiles'
310 verifyOutputFiles :: DynFlags -> IO ()
311 verifyOutputFiles dflags = do
312 -- not -odir: we create the directory for -odir if it doesn't exist (#2278).
313 let ofile = outputFile dflags
314 when (isJust ofile) $ do
315 let fn = fromJust ofile
316 flg <- doesDirNameExist fn
317 when (not flg) (nonExistentDir "-o" fn)
318 let ohi = outputHi dflags
319 when (isJust ohi) $ do
320 let hi = fromJust ohi
321 flg <- doesDirNameExist hi
322 when (not flg) (nonExistentDir "-ohi" hi)
324 nonExistentDir flg dir =
325 ghcError (CmdLineError ("error: directory portion of " ++
326 show dir ++ " does not exist (used with " ++
327 show flg ++ " option.)"))
329 -----------------------------------------------------------------------------
330 -- GHC modes of operation
333 = ShowUsage -- ghc -?
334 | ShowVersion -- ghc -V/--version
335 | ShowNumVersion -- ghc --numeric-version
336 | ShowSupportedLanguages -- ghc --supported-languages
337 | ShowInfo -- ghc --info
341 = PrintLibdir -- ghc --print-libdir
342 | ShowInterface String -- ghc --show-iface
343 | DoMkDependHS -- ghc -M
344 | StopBefore Phase -- ghc -E | -C | -S
345 -- StopBefore StopLn is the default
346 | DoMake -- ghc --make
347 | DoInteractive -- ghc --interactive
348 | DoEval [String] -- ghc -e foo -e bar => DoEval ["bar", "foo"]
352 isInteractiveMode :: CmdLineMode -> Bool
353 isInteractiveMode DoInteractive = True
354 isInteractiveMode _ = False
357 -- isInterpretiveMode: byte-code compiler involved
358 isInterpretiveMode :: CmdLineMode -> Bool
359 isInterpretiveMode DoInteractive = True
360 isInterpretiveMode (DoEval _) = True
361 isInterpretiveMode _ = False
363 needsInputsMode :: CmdLineMode -> Bool
364 needsInputsMode DoMkDependHS = True
365 needsInputsMode (StopBefore _) = True
366 needsInputsMode DoMake = True
367 needsInputsMode _ = False
369 -- True if we are going to attempt to link in this mode.
370 -- (we might not actually link, depending on the GhcLink flag)
371 isLinkMode :: CmdLineMode -> Bool
372 isLinkMode (StopBefore StopLn) = True
373 isLinkMode DoMake = True
374 isLinkMode DoInteractive = True
375 isLinkMode (DoEval _) = True
378 isCompManagerMode :: CmdLineMode -> Bool
379 isCompManagerMode DoMake = True
380 isCompManagerMode DoInteractive = True
381 isCompManagerMode (DoEval _) = True
382 isCompManagerMode _ = False
385 -- -----------------------------------------------------------------------------
386 -- Parsing the mode flag
388 parseModeFlags :: [Located String]
389 -> IO (Maybe UberMode,
393 parseModeFlags args = do
394 let ((leftover, errs, warns), (mUberMode, mode, _, flags')) =
395 runCmdLine (processArgs mode_flags args)
396 (Nothing, StopBefore StopLn, "", [])
397 when (not (null errs)) $ ghcError $ errorsToGhcException errs
398 return (mUberMode, mode, flags' ++ leftover, warns)
400 type ModeM = CmdLineP (Maybe UberMode, CmdLineMode, String, [Located String])
401 -- mode flags sometimes give rise to new DynFlags (eg. -C, see below)
402 -- so we collect the new ones and return them.
404 mode_flags :: [Flag ModeM]
406 [ ------- help / version ----------------------------------------------
407 Flag "?" (NoArg (setUberMode ShowUsage))
409 , Flag "-help" (NoArg (setUberMode ShowUsage))
411 , Flag "V" (NoArg (setUberMode ShowVersion))
413 , Flag "-version" (NoArg (setUberMode ShowVersion))
415 , Flag "-numeric-version" (NoArg (setUberMode ShowNumVersion))
417 , Flag "-info" (NoArg (setUberMode ShowInfo))
419 , Flag "-supported-languages" (NoArg (setUberMode ShowSupportedLanguages))
421 , Flag "-print-libdir" (PassFlag (setMode PrintLibdir))
424 ------- interfaces ----------------------------------------------------
425 , Flag "-show-iface" (HasArg (\f -> setMode (ShowInterface f)
429 ------- primary modes ------------------------------------------------
430 , Flag "M" (PassFlag (setMode DoMkDependHS))
432 , Flag "E" (PassFlag (setMode (StopBefore anyHsc)))
434 , Flag "C" (PassFlag (\f -> do setMode (StopBefore HCc) f
437 , Flag "S" (PassFlag (setMode (StopBefore As)))
439 , Flag "-make" (PassFlag (setMode DoMake))
441 , Flag "-interactive" (PassFlag (setMode DoInteractive))
443 , Flag "e" (HasArg (\s -> updateMode (updateDoEval s) "-e"))
446 -- -fno-code says to stop after Hsc but don't generate any code.
447 , Flag "fno-code" (PassFlag (\f -> do setMode (StopBefore HCc) f
449 addFlag "-fforce-recomp"))
453 setUberMode :: UberMode -> ModeM ()
455 (_, cmdLineMode, flag, flags') <- getCmdLineState
456 putCmdLineState (Just m, cmdLineMode, flag, flags')
458 setMode :: CmdLineMode -> String -> ModeM ()
459 setMode m flag = updateMode (\_ -> m) flag
461 updateDoEval :: String -> CmdLineMode -> CmdLineMode
462 updateDoEval expr (DoEval exprs) = DoEval (expr : exprs)
463 updateDoEval expr _ = DoEval [expr]
465 updateMode :: (CmdLineMode -> CmdLineMode) -> String -> ModeM ()
466 updateMode f flag = do
467 (m_uber_mode, old_mode, old_flag, flags') <- getCmdLineState
468 if null old_flag || flag == old_flag
469 then putCmdLineState (m_uber_mode, f old_mode, flag, flags')
470 else ghcError (UsageError
471 ("cannot use `" ++ old_flag ++ "' with `" ++ flag ++ "'"))
473 addFlag :: String -> ModeM ()
475 (u, m, f, flags') <- getCmdLineState
476 -- XXX Can we get a useful Loc?
477 putCmdLineState (u, m, f, mkGeneralLocated "addFlag" s : flags')
480 -- ----------------------------------------------------------------------------
483 doMake :: [(String,Maybe Phase)] -> Ghc ()
484 doMake [] = ghcError (UsageError "no input files")
486 let (hs_srcs, non_hs_srcs) = partition haskellish srcs
488 haskellish (f,Nothing) =
489 looksLikeModuleName f || isHaskellSrcFilename f || '.' `notElem` f
490 haskellish (_,Just phase) =
491 phase `notElem` [As, Cc, CmmCpp, Cmm, StopLn]
493 hsc_env <- GHC.getSession
494 o_files <- mapM (\x -> do
495 f <- compileFile hsc_env StopLn x
499 liftIO $ mapM_ (consIORef v_Ld_inputs) (reverse o_files)
501 targets <- mapM (uncurry GHC.guessTarget) hs_srcs
502 GHC.setTargets targets
503 ok_flag <- GHC.load LoadAllTargets
505 when (failed ok_flag) (liftIO $ exitWith (ExitFailure 1))
509 -- ---------------------------------------------------------------------------
512 doShowIface :: DynFlags -> FilePath -> IO ()
513 doShowIface dflags file = do
514 hsc_env <- newHscEnv dflags
515 showIface hsc_env file
517 -- ---------------------------------------------------------------------------
518 -- Various banners and verbosity output.
520 showBanner :: CmdLineMode -> DynFlags -> IO ()
521 showBanner _cli_mode dflags = do
522 let verb = verbosity dflags
525 -- Show the GHCi banner
526 when (isInteractiveMode _cli_mode && verb >= 1) $ putStrLn ghciWelcomeMsg
529 -- Display details of the configuration in verbose mode
531 do hPutStr stderr "Glasgow Haskell Compiler, Version "
532 hPutStr stderr cProjectVersion
533 hPutStr stderr ", for Haskell 98, stage "
534 hPutStr stderr cStage
535 hPutStr stderr " booted by GHC version "
536 hPutStrLn stderr cBooterVersion
538 -- We print out a Read-friendly string, but a prettier one than the
539 -- Show instance gives us
542 let sq x = " [" ++ x ++ "\n ]"
543 putStrLn $ sq $ concat $ intersperse "\n ," $ map show compilerInfo
546 showSupportedLanguages :: IO ()
547 showSupportedLanguages = do mapM_ putStrLn supportedLanguages
552 putStrLn (cProjectName ++ ", version " ++ cProjectVersion)
555 showGhcUsage :: DynFlags -> CmdLineMode -> IO ()
556 showGhcUsage dflags cli_mode = do
558 | DoInteractive <- cli_mode = ghciUsagePath dflags
559 | otherwise = ghcUsagePath dflags
560 usage <- readFile usage_path
565 dump ('$':'$':s) = putStr progName >> dump s
566 dump (c:s) = putChar c >> dump s
568 dumpFinalStats :: DynFlags -> IO ()
569 dumpFinalStats dflags =
570 when (dopt Opt_D_faststring_stats dflags) $ dumpFastStringStats dflags
572 dumpFastStringStats :: DynFlags -> IO ()
573 dumpFastStringStats dflags = do
574 buckets <- getFastStringTable
575 let (entries, longest, is_z, has_z) = countFS 0 0 0 0 buckets
576 msg = text "FastString stats:" $$
577 nest 4 (vcat [text "size: " <+> int (length buckets),
578 text "entries: " <+> int entries,
579 text "longest chain: " <+> int longest,
580 text "z-encoded: " <+> (is_z `pcntOf` entries),
581 text "has z-encoding: " <+> (has_z `pcntOf` entries)
583 -- we usually get more "has z-encoding" than "z-encoded", because
584 -- when we z-encode a string it might hash to the exact same string,
585 -- which will is not counted as "z-encoded". Only strings whose
586 -- Z-encoding is different from the original string are counted in
587 -- the "z-encoded" total.
590 x `pcntOf` y = int ((x * 100) `quot` y) <> char '%'
592 countFS :: Int -> Int -> Int -> Int -> [[FastString]] -> (Int, Int, Int, Int)
593 countFS entries longest is_z has_z [] = (entries, longest, is_z, has_z)
594 countFS entries longest is_z has_z (b:bs) =
597 longest' = max len longest
598 entries' = entries + len
599 is_zs = length (filter isZEncoded b)
600 has_zs = length (filter hasZEncoding b)
602 countFS entries' longest' (is_z + is_zs) (has_z + has_zs) bs
604 -- -----------------------------------------------------------------------------
607 unknownFlagsErr :: [String] -> a
608 unknownFlagsErr fs = ghcError (UsageError ("unrecognised flags: " ++ unwords fs))