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 hPutStrLn stderr ("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 let not_linking = not (isLinkMode cli_mode) || isNoLink (ghcLink dflags)
285 when (not_linking && not (null objs)) $
286 hPutStrLn stderr ("Warning: the following files would be used as linker inputs, but linking is not being done: " ++ unwords objs)
288 -- Check that there are some input files
289 -- (except in the interactive case)
290 if null srcs && (null objs || not_linking) && needsInputsMode cli_mode
291 then ghcError (UsageError "no input files")
294 -- Verify that output files point somewhere sensible.
295 verifyOutputFiles dflags
298 -- Compiler output options
300 -- called to verify that the output files & directories
301 -- point somewhere valid.
303 -- The assumption is that the directory portion of these output
304 -- options will have to exist by the time 'verifyOutputFiles'
307 verifyOutputFiles :: DynFlags -> IO ()
308 verifyOutputFiles dflags = do
309 -- not -odir: we create the directory for -odir if it doesn't exist (#2278).
310 let ofile = outputFile dflags
311 when (isJust ofile) $ do
312 let fn = fromJust ofile
313 flg <- doesDirNameExist fn
314 when (not flg) (nonExistentDir "-o" fn)
315 let ohi = outputHi dflags
316 when (isJust ohi) $ do
317 let hi = fromJust ohi
318 flg <- doesDirNameExist hi
319 when (not flg) (nonExistentDir "-ohi" hi)
321 nonExistentDir flg dir =
322 ghcError (CmdLineError ("error: directory portion of " ++
323 show dir ++ " does not exist (used with " ++
324 show flg ++ " option.)"))
326 -----------------------------------------------------------------------------
327 -- GHC modes of operation
330 = ShowUsage -- ghc -?
331 | PrintLibdir -- ghc --print-libdir
332 | ShowInfo -- ghc --info
333 | ShowSupportedLanguages -- ghc --supported-languages
334 | ShowVersion -- ghc -V/--version
335 | ShowNumVersion -- ghc --numeric-version
336 | ShowInterface String -- ghc --show-iface
337 | DoMkDependHS -- ghc -M
338 | StopBefore Phase -- ghc -E | -C | -S
339 -- StopBefore StopLn is the default
340 | DoMake -- ghc --make
341 | DoInteractive -- ghc --interactive
342 | DoEval [String] -- ghc -e foo -e bar => DoEval ["bar", "foo"]
346 isInteractiveMode :: CmdLineMode -> Bool
347 isInteractiveMode DoInteractive = True
348 isInteractiveMode _ = False
351 -- isInterpretiveMode: byte-code compiler involved
352 isInterpretiveMode :: CmdLineMode -> Bool
353 isInterpretiveMode DoInteractive = True
354 isInterpretiveMode (DoEval _) = True
355 isInterpretiveMode _ = False
357 needsInputsMode :: CmdLineMode -> Bool
358 needsInputsMode DoMkDependHS = True
359 needsInputsMode (StopBefore _) = True
360 needsInputsMode DoMake = True
361 needsInputsMode _ = False
363 -- True if we are going to attempt to link in this mode.
364 -- (we might not actually link, depending on the GhcLink flag)
365 isLinkMode :: CmdLineMode -> Bool
366 isLinkMode (StopBefore StopLn) = True
367 isLinkMode DoMake = True
368 isLinkMode DoInteractive = True
369 isLinkMode (DoEval _) = True
372 isCompManagerMode :: CmdLineMode -> Bool
373 isCompManagerMode DoMake = True
374 isCompManagerMode DoInteractive = True
375 isCompManagerMode (DoEval _) = True
376 isCompManagerMode _ = False
379 -- -----------------------------------------------------------------------------
380 -- Parsing the mode flag
382 parseModeFlags :: [Located String]
383 -> IO (CmdLineMode, [Located String], [Located String])
384 parseModeFlags args = do
385 let ((leftover, errs, warns), (mode, _, flags')) =
386 runCmdLine (processArgs mode_flags args) (StopBefore StopLn, "", [])
387 when (not (null errs)) $ ghcError $ errorsToGhcException errs
388 return (mode, flags' ++ leftover, warns)
390 type ModeM = CmdLineP (CmdLineMode, String, [Located String])
391 -- mode flags sometimes give rise to new DynFlags (eg. -C, see below)
392 -- so we collect the new ones and return them.
394 mode_flags :: [Flag ModeM]
396 [ ------- help / version ----------------------------------------------
397 Flag "?" (PassFlag (setMode ShowUsage))
399 , Flag "-help" (PassFlag (setMode ShowUsage))
401 , Flag "-print-libdir" (PassFlag (setMode PrintLibdir))
403 , Flag "V" (PassFlag (setMode ShowVersion))
405 , Flag "-version" (PassFlag (setMode ShowVersion))
407 , Flag "-numeric-version" (PassFlag (setMode ShowNumVersion))
409 , Flag "-info" (PassFlag (setMode ShowInfo))
411 , Flag "-supported-languages" (PassFlag (setMode ShowSupportedLanguages))
414 ------- interfaces ----------------------------------------------------
415 , Flag "-show-iface" (HasArg (\f -> setMode (ShowInterface f)
419 ------- primary modes ------------------------------------------------
420 , Flag "M" (PassFlag (setMode DoMkDependHS))
422 , Flag "E" (PassFlag (setMode (StopBefore anyHsc)))
424 , Flag "C" (PassFlag (\f -> do setMode (StopBefore HCc) f
427 , Flag "S" (PassFlag (setMode (StopBefore As)))
429 , Flag "-make" (PassFlag (setMode DoMake))
431 , Flag "-interactive" (PassFlag (setMode DoInteractive))
433 , Flag "e" (HasArg (\s -> updateMode (updateDoEval s) "-e"))
436 -- -fno-code says to stop after Hsc but don't generate any code.
437 , Flag "fno-code" (PassFlag (\f -> do setMode (StopBefore HCc) f
439 addFlag "-fforce-recomp"))
443 setMode :: CmdLineMode -> String -> ModeM ()
444 setMode m flag = updateMode (\_ -> m) flag
446 updateDoEval :: String -> CmdLineMode -> CmdLineMode
447 updateDoEval expr (DoEval exprs) = DoEval (expr : exprs)
448 updateDoEval expr _ = DoEval [expr]
450 updateMode :: (CmdLineMode -> CmdLineMode) -> String -> ModeM ()
451 updateMode f flag = do
452 (old_mode, old_flag, flags') <- getCmdLineState
453 if notNull old_flag && flag /= old_flag
454 then ghcError (UsageError
455 ("cannot use `" ++ old_flag ++ "' with `" ++ flag ++ "'"))
456 else putCmdLineState (f old_mode, flag, flags')
458 addFlag :: String -> ModeM ()
460 (m, f, flags') <- getCmdLineState
461 -- XXX Can we get a useful Loc?
462 putCmdLineState (m, f, mkGeneralLocated "addFlag" s : flags')
465 -- ----------------------------------------------------------------------------
468 doMake :: [(String,Maybe Phase)] -> Ghc ()
469 doMake [] = ghcError (UsageError "no input files")
471 let (hs_srcs, non_hs_srcs) = partition haskellish srcs
473 haskellish (f,Nothing) =
474 looksLikeModuleName f || isHaskellSrcFilename f || '.' `notElem` f
475 haskellish (_,Just phase) =
476 phase `notElem` [As, Cc, CmmCpp, Cmm, StopLn]
478 hsc_env <- GHC.getSession
479 o_files <- mapM (\x -> do
480 f <- compileFile hsc_env StopLn x
484 liftIO $ mapM_ (consIORef v_Ld_inputs) (reverse o_files)
486 targets <- mapM (uncurry GHC.guessTarget) hs_srcs
487 GHC.setTargets targets
488 ok_flag <- GHC.load LoadAllTargets
490 when (failed ok_flag) (liftIO $ exitWith (ExitFailure 1))
494 -- ---------------------------------------------------------------------------
497 doShowIface :: DynFlags -> FilePath -> IO ()
498 doShowIface dflags file = do
499 hsc_env <- newHscEnv dflags
500 showIface hsc_env file
502 -- ---------------------------------------------------------------------------
503 -- Various banners and verbosity output.
505 showBanner :: CmdLineMode -> DynFlags -> IO ()
506 showBanner _cli_mode dflags = do
507 let verb = verbosity dflags
510 -- Show the GHCi banner
511 when (isInteractiveMode _cli_mode && verb >= 1) $ putStrLn ghciWelcomeMsg
514 -- Display details of the configuration in verbose mode
516 do hPutStr stderr "Glasgow Haskell Compiler, Version "
517 hPutStr stderr cProjectVersion
518 hPutStr stderr ", for Haskell 98, stage "
519 hPutStr stderr cStage
520 hPutStr stderr " booted by GHC version "
521 hPutStrLn stderr cBooterVersion
523 -- We print out a Read-friendly string, but a prettier one than the
524 -- Show instance gives us
527 let sq x = " [" ++ x ++ "\n ]"
528 putStrLn $ sq $ concat $ intersperse "\n ," $ map show compilerInfo
531 showSupportedLanguages :: IO ()
532 showSupportedLanguages = do mapM_ putStrLn supportedLanguages
537 putStrLn (cProjectName ++ ", version " ++ cProjectVersion)
540 showGhcUsage :: DynFlags -> CmdLineMode -> IO ()
541 showGhcUsage dflags cli_mode = do
543 | DoInteractive <- cli_mode = ghciUsagePath dflags
544 | otherwise = ghcUsagePath dflags
545 usage <- readFile usage_path
550 dump ('$':'$':s) = putStr progName >> dump s
551 dump (c:s) = putChar c >> dump s
553 dumpFinalStats :: DynFlags -> IO ()
554 dumpFinalStats dflags =
555 when (dopt Opt_D_faststring_stats dflags) $ dumpFastStringStats dflags
557 dumpFastStringStats :: DynFlags -> IO ()
558 dumpFastStringStats dflags = do
559 buckets <- getFastStringTable
560 let (entries, longest, is_z, has_z) = countFS 0 0 0 0 buckets
561 msg = text "FastString stats:" $$
562 nest 4 (vcat [text "size: " <+> int (length buckets),
563 text "entries: " <+> int entries,
564 text "longest chain: " <+> int longest,
565 text "z-encoded: " <+> (is_z `pcntOf` entries),
566 text "has z-encoding: " <+> (has_z `pcntOf` entries)
568 -- we usually get more "has z-encoding" than "z-encoded", because
569 -- when we z-encode a string it might hash to the exact same string,
570 -- which will is not counted as "z-encoded". Only strings whose
571 -- Z-encoding is different from the original string are counted in
572 -- the "z-encoded" total.
575 x `pcntOf` y = int ((x * 100) `quot` y) <> char '%'
577 countFS :: Int -> Int -> Int -> Int -> [[FastString]] -> (Int, Int, Int, Int)
578 countFS entries longest is_z has_z [] = (entries, longest, is_z, has_z)
579 countFS entries longest is_z has_z (b:bs) =
582 longest' = max len longest
583 entries' = entries + len
584 is_zs = length (filter isZEncoded b)
585 has_zs = length (filter hasZEncoding b)
587 countFS entries' longest' (is_z + is_zs) (has_z + has_zs) bs
589 -- -----------------------------------------------------------------------------
592 unknownFlagsErr :: [String] -> a
593 unknownFlagsErr fs = ghcError (UsageError ("unrecognised flags: " ++ unwords fs))