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 )
38 import StaticFlagParser
40 import BasicTypes ( failed )
48 -- Standard Haskell libraries
50 import System.Environment
52 import System.FilePath
57 -----------------------------------------------------------------------------
60 -- time commands when run with -v
62 -- Win32 support: proper signal handling
63 -- reading the package configuration file is too slow
66 -----------------------------------------------------------------------------
67 -- GHC's command-line interface
71 GHC.defaultErrorHandler defaultDynFlags $ do
73 -- 1. extract the -B flag from the args
77 (minusB_args, argv1) = partition ("-B" `isPrefixOf`) argv0
78 mbMinusB | null minusB_args = Nothing
79 | otherwise = Just (drop 2 (last minusB_args))
81 let argv1' = map (mkGeneralLocated "on the commandline") argv1
82 (argv2, staticFlagWarnings) <- parseStaticFlags argv1'
84 -- 2. Parse the "mode" flags (--make, --interactive etc.)
85 (cli_mode, argv3, modeFlagWarnings) <- parseModeFlags argv2
87 -- If all we want to do is to show the version number then do it
88 -- now, before we start a GHC session etc.
89 -- If we do it later then bootstrapping gets confused as it tries
90 -- to find out what version of GHC it's using before package.conf
91 -- exists, so starting the session fails.
93 ShowInfo -> do showInfo
95 ShowSupportedLanguages -> do showSupportedLanguages
97 ShowVersion -> do showVersion
99 ShowNumVersion -> do putStrLn cProjectVersion
103 -- start our GHC session
104 session <- GHC.newSession mbMinusB
106 dflags0 <- GHC.getSessionDynFlags session
108 -- set the default GhcMode, HscTarget and GhcLink. The HscTarget
109 -- can be further adjusted on a module by module basis, using only
110 -- the -fvia-C and -fasm flags. If the default HscTarget is not
111 -- HscC or HscAsm, -fvia-C and -fasm have no effect.
112 let dflt_target = hscTarget dflags0
115 DoInteractive -> (CompManager, HscInterpreted, LinkInMemory)
116 DoEval _ -> (CompManager, HscInterpreted, LinkInMemory)
117 DoMake -> (CompManager, dflt_target, LinkBinary)
118 DoMkDependHS -> (MkDepend, dflt_target, LinkBinary)
119 _ -> (OneShot, dflt_target, LinkBinary)
121 let dflags1 = dflags0{ ghcMode = mode,
124 -- leave out hscOutName for now
125 hscOutName = panic "Main.main:hscOutName not set",
126 verbosity = case cli_mode of
131 -- turn on -fimplicit-import-qualified for GHCi now, so that it
132 -- can be overriden from the command-line
133 dflags1a | DoInteractive <- cli_mode = imp_qual_enabled
134 | DoEval _ <- cli_mode = imp_qual_enabled
135 | otherwise = dflags1
136 where imp_qual_enabled = dflags1 `dopt_set` Opt_ImplicitImportQualified
138 -- The rest of the arguments are "dynamic"
139 -- Leftover ones are presumably files
140 (dflags2, fileish_args, dynamicFlagWarnings) <- GHC.parseDynamicFlags dflags1a argv3
142 let flagWarnings = staticFlagWarnings
144 ++ dynamicFlagWarnings
145 handleFlagWarnings dflags2 flagWarnings
147 -- make sure we clean up after ourselves
148 GHC.defaultCleanupHandler dflags2 $ do
150 showBanner cli_mode dflags2
152 -- we've finished manipulating the DynFlags, update the session
153 GHC.setSessionDynFlags session dflags2
154 dflags3 <- GHC.getSessionDynFlags session
155 hsc_env <- GHC.sessionHscEnv session
158 -- To simplify the handling of filepaths, we normalise all filepaths right
159 -- away - e.g., for win32 platforms, backslashes are converted
160 -- into forward slashes.
161 normal_fileish_paths = map (normalise . unLoc) fileish_args
162 (srcs, objs) = partition_args normal_fileish_paths [] []
164 -- Note: have v_Ld_inputs maintain the order in which 'objs' occurred on
166 mapM_ (consIORef v_Ld_inputs) (reverse objs)
168 ---------------- Display configuration -----------
169 when (verbosity dflags3 >= 4) $
172 when (verbosity dflags3 >= 3) $ do
173 hPutStrLn stderr ("Hsc static flags: " ++ unwords staticFlags)
175 ---------------- Final sanity checking -----------
176 checkOptions cli_mode dflags3 srcs objs
178 ---------------- Do the business -----------
179 let alreadyHandled = panic (show cli_mode ++
180 " should already have been handled")
182 ShowUsage -> showGhcUsage dflags3 cli_mode
183 PrintLibdir -> putStrLn (topDir dflags3)
184 ShowSupportedLanguages -> alreadyHandled
185 ShowVersion -> alreadyHandled
186 ShowNumVersion -> alreadyHandled
187 ShowInterface f -> doShowIface dflags3 f
188 DoMake -> doMake session srcs
189 DoMkDependHS -> doMkDependHS session (map fst srcs)
190 StopBefore p -> oneShot hsc_env p srcs
191 DoInteractive -> interactiveUI session srcs Nothing
192 DoEval exprs -> interactiveUI session srcs $ Just $ reverse exprs
194 dumpFinalStats dflags3
198 interactiveUI :: a -> b -> c -> IO ()
199 interactiveUI _ _ _ =
200 ghcError (CmdLineError "not built for interactive use")
203 -- -----------------------------------------------------------------------------
204 -- Splitting arguments into source files and object files. This is where we
205 -- interpret the -x <suffix> option, and attach a (Maybe Phase) to each source
206 -- file indicating the phase specified by the -x option in force, if any.
208 partition_args :: [String] -> [(String, Maybe Phase)] -> [String]
209 -> ([(String, Maybe Phase)], [String])
210 partition_args [] srcs objs = (reverse srcs, reverse objs)
211 partition_args ("-x":suff:args) srcs objs
212 | "none" <- suff = partition_args args srcs objs
213 | StopLn <- phase = partition_args args srcs (slurp ++ objs)
214 | otherwise = partition_args rest (these_srcs ++ srcs) objs
215 where phase = startPhase suff
216 (slurp,rest) = break (== "-x") args
217 these_srcs = zip slurp (repeat (Just phase))
218 partition_args (arg:args) srcs objs
219 | looks_like_an_input arg = partition_args args ((arg,Nothing):srcs) objs
220 | otherwise = partition_args args srcs (arg:objs)
223 We split out the object files (.o, .dll) and add them
224 to v_Ld_inputs for use by the linker.
226 The following things should be considered compilation manager inputs:
228 - haskell source files (strings ending in .hs, .lhs or other
229 haskellish extension),
231 - module names (not forgetting hierarchical module names),
233 - and finally we consider everything not containing a '.' to be
234 a comp manager input, as shorthand for a .hs or .lhs filename.
236 Everything else is considered to be a linker object, and passed
237 straight through to the linker.
239 looks_like_an_input :: String -> Bool
240 looks_like_an_input m = isSourceFilename m
241 || looksLikeModuleName m
244 -- -----------------------------------------------------------------------------
245 -- Option sanity checks
247 checkOptions :: CmdLineMode -> DynFlags -> [(String,Maybe Phase)] -> [String] -> IO ()
248 -- Final sanity checking before kicking off a compilation (pipeline).
249 checkOptions cli_mode dflags srcs objs = do
250 -- Complain about any unknown flags
251 let unknown_opts = [ f | (f@('-':_), _) <- srcs ]
252 when (notNull unknown_opts) (unknownFlagsErr unknown_opts)
254 when (notNull (filter isRTSWay (wayNames dflags))
255 && isInterpretiveMode cli_mode) $
256 putStrLn ("Warning: -debug, -threaded and -ticky are ignored by GHCi")
258 -- -prof and --interactive are not a good combination
259 when (notNull (filter (not . isRTSWay) (wayNames dflags))
260 && isInterpretiveMode cli_mode) $
261 do ghcError (UsageError
262 "--interactive can't be used with -prof or -unreg.")
264 if (isJust (outputHi dflags) &&
265 (isCompManagerMode cli_mode || srcs `lengthExceeds` 1))
266 then ghcError (UsageError "-ohi can only be used when compiling a single source file")
269 -- -o sanity checking
270 if (srcs `lengthExceeds` 1 && isJust (outputFile dflags)
271 && not (isLinkMode cli_mode))
272 then ghcError (UsageError "can't apply -o to multiple source files")
275 -- Check that there are some input files
276 -- (except in the interactive case)
277 if null srcs && null objs && needsInputsMode cli_mode
278 then ghcError (UsageError "no input files")
281 -- Verify that output files point somewhere sensible.
282 verifyOutputFiles dflags
285 -- Compiler output options
287 -- called to verify that the output files & directories
288 -- point somewhere valid.
290 -- The assumption is that the directory portion of these output
291 -- options will have to exist by the time 'verifyOutputFiles'
294 verifyOutputFiles :: DynFlags -> IO ()
295 verifyOutputFiles dflags = do
296 -- not -odir: we create the directory for -odir if it doesn't exist (#2278).
297 let ofile = outputFile dflags
298 when (isJust ofile) $ do
299 let fn = fromJust ofile
300 flg <- doesDirNameExist fn
301 when (not flg) (nonExistentDir "-o" fn)
302 let ohi = outputHi dflags
303 when (isJust ohi) $ do
304 let hi = fromJust ohi
305 flg <- doesDirNameExist hi
306 when (not flg) (nonExistentDir "-ohi" hi)
308 nonExistentDir flg dir =
309 ghcError (CmdLineError ("error: directory portion of " ++
310 show dir ++ " does not exist (used with " ++
311 show flg ++ " option.)"))
313 -----------------------------------------------------------------------------
314 -- GHC modes of operation
317 = ShowUsage -- ghc -?
318 | PrintLibdir -- ghc --print-libdir
319 | ShowInfo -- ghc --info
320 | ShowSupportedLanguages -- ghc --supported-languages
321 | ShowVersion -- ghc -V/--version
322 | ShowNumVersion -- ghc --numeric-version
323 | ShowInterface String -- ghc --show-iface
324 | DoMkDependHS -- ghc -M
325 | StopBefore Phase -- ghc -E | -C | -S
326 -- StopBefore StopLn is the default
327 | DoMake -- ghc --make
328 | DoInteractive -- ghc --interactive
329 | DoEval [String] -- ghc -e foo -e bar => DoEval ["bar", "foo"]
333 isInteractiveMode :: CmdLineMode -> Bool
334 isInteractiveMode DoInteractive = True
335 isInteractiveMode _ = False
338 -- isInterpretiveMode: byte-code compiler involved
339 isInterpretiveMode :: CmdLineMode -> Bool
340 isInterpretiveMode DoInteractive = True
341 isInterpretiveMode (DoEval _) = True
342 isInterpretiveMode _ = False
344 needsInputsMode :: CmdLineMode -> Bool
345 needsInputsMode DoMkDependHS = True
346 needsInputsMode (StopBefore _) = True
347 needsInputsMode DoMake = True
348 needsInputsMode _ = False
350 -- True if we are going to attempt to link in this mode.
351 -- (we might not actually link, depending on the GhcLink flag)
352 isLinkMode :: CmdLineMode -> Bool
353 isLinkMode (StopBefore StopLn) = True
354 isLinkMode DoMake = True
357 isCompManagerMode :: CmdLineMode -> Bool
358 isCompManagerMode DoMake = True
359 isCompManagerMode DoInteractive = True
360 isCompManagerMode (DoEval _) = True
361 isCompManagerMode _ = False
364 -- -----------------------------------------------------------------------------
365 -- Parsing the mode flag
367 parseModeFlags :: [Located String]
368 -> IO (CmdLineMode, [Located String], [Located String])
369 parseModeFlags args = do
370 let ((leftover, errs, warns), (mode, _, flags')) =
371 runCmdLine (processArgs mode_flags args) (StopBefore StopLn, "", [])
372 when (not (null errs)) $ ghcError $ errorsToGhcException errs
373 return (mode, flags' ++ leftover, warns)
375 type ModeM = CmdLineP (CmdLineMode, String, [Located String])
376 -- mode flags sometimes give rise to new DynFlags (eg. -C, see below)
377 -- so we collect the new ones and return them.
379 mode_flags :: [Flag ModeM]
381 [ ------- help / version ----------------------------------------------
382 Flag "?" (PassFlag (setMode ShowUsage))
384 , Flag "-help" (PassFlag (setMode ShowUsage))
386 , Flag "-print-libdir" (PassFlag (setMode PrintLibdir))
388 , Flag "V" (PassFlag (setMode ShowVersion))
390 , Flag "-version" (PassFlag (setMode ShowVersion))
392 , Flag "-numeric-version" (PassFlag (setMode ShowNumVersion))
394 , Flag "-info" (PassFlag (setMode ShowInfo))
396 , Flag "-supported-languages" (PassFlag (setMode ShowSupportedLanguages))
399 ------- interfaces ----------------------------------------------------
400 , Flag "-show-iface" (HasArg (\f -> setMode (ShowInterface f)
404 ------- primary modes ------------------------------------------------
405 , Flag "M" (PassFlag (setMode DoMkDependHS))
407 , Flag "E" (PassFlag (setMode (StopBefore anyHsc)))
409 , Flag "C" (PassFlag (\f -> do setMode (StopBefore HCc) f
412 , Flag "S" (PassFlag (setMode (StopBefore As)))
414 , Flag "-make" (PassFlag (setMode DoMake))
416 , Flag "-interactive" (PassFlag (setMode DoInteractive))
418 , Flag "e" (HasArg (\s -> updateMode (updateDoEval s) "-e"))
421 -- -fno-code says to stop after Hsc but don't generate any code.
422 , Flag "fno-code" (PassFlag (\f -> do setMode (StopBefore HCc) f
424 addFlag "-fforce-recomp"))
428 setMode :: CmdLineMode -> String -> ModeM ()
429 setMode m flag = updateMode (\_ -> m) flag
431 updateDoEval :: String -> CmdLineMode -> CmdLineMode
432 updateDoEval expr (DoEval exprs) = DoEval (expr : exprs)
433 updateDoEval expr _ = DoEval [expr]
435 updateMode :: (CmdLineMode -> CmdLineMode) -> String -> ModeM ()
436 updateMode f flag = do
437 (old_mode, old_flag, flags') <- getCmdLineState
438 if notNull old_flag && flag /= old_flag
439 then ghcError (UsageError
440 ("cannot use `" ++ old_flag ++ "' with `" ++ flag ++ "'"))
441 else putCmdLineState (f old_mode, flag, flags')
443 addFlag :: String -> ModeM ()
445 (m, f, flags') <- getCmdLineState
446 -- XXX Can we get a useful Loc?
447 putCmdLineState (m, f, mkGeneralLocated "addFlag" s : flags')
450 -- ----------------------------------------------------------------------------
453 doMake :: Session -> [(String,Maybe Phase)] -> IO ()
454 doMake _ [] = ghcError (UsageError "no input files")
455 doMake sess srcs = do
456 let (hs_srcs, non_hs_srcs) = partition haskellish srcs
458 haskellish (f,Nothing) =
459 looksLikeModuleName f || isHaskellSrcFilename f || '.' `notElem` f
460 haskellish (_,Just phase) =
461 phase `notElem` [As, Cc, CmmCpp, Cmm, StopLn]
463 hsc_env <- GHC.sessionHscEnv sess
464 o_files <- mapM (compileFile hsc_env StopLn) non_hs_srcs
465 mapM_ (consIORef v_Ld_inputs) (reverse o_files)
467 targets <- mapM (uncurry GHC.guessTarget) hs_srcs
468 GHC.setTargets sess targets
469 ok_flag <- GHC.load sess LoadAllTargets
470 when (failed ok_flag) (exitWith (ExitFailure 1))
474 -- ---------------------------------------------------------------------------
477 doShowIface :: DynFlags -> FilePath -> IO ()
478 doShowIface dflags file = do
479 hsc_env <- newHscEnv dflags
480 showIface hsc_env file
482 -- ---------------------------------------------------------------------------
483 -- Various banners and verbosity output.
485 showBanner :: CmdLineMode -> DynFlags -> IO ()
486 showBanner _cli_mode dflags = do
487 let verb = verbosity dflags
490 -- Show the GHCi banner
491 when (isInteractiveMode _cli_mode && verb >= 1) $ putStrLn ghciWelcomeMsg
494 -- Display details of the configuration in verbose mode
496 do hPutStr stderr "Glasgow Haskell Compiler, Version "
497 hPutStr stderr cProjectVersion
498 hPutStr stderr ", for Haskell 98, stage "
499 hPutStr stderr cStage
500 hPutStr stderr " booted by GHC version "
501 hPutStrLn stderr cBooterVersion
503 -- We print out a Read-friendly string, but a prettier one than the
504 -- Show instance gives us
507 let sq x = " [" ++ x ++ "\n ]"
508 putStrLn $ sq $ concat $ intersperse "\n ," $ map show compilerInfo
511 showSupportedLanguages :: IO ()
512 showSupportedLanguages = do mapM_ putStrLn supportedLanguages
517 putStrLn (cProjectName ++ ", version " ++ cProjectVersion)
520 showGhcUsage :: DynFlags -> CmdLineMode -> IO ()
521 showGhcUsage dflags cli_mode = do
523 | DoInteractive <- cli_mode = ghciUsagePath dflags
524 | otherwise = ghcUsagePath dflags
525 usage <- readFile usage_path
530 dump ('$':'$':s) = putStr progName >> dump s
531 dump (c:s) = putChar c >> dump s
533 dumpFinalStats :: DynFlags -> IO ()
534 dumpFinalStats dflags =
535 when (dopt Opt_D_faststring_stats dflags) $ dumpFastStringStats dflags
537 dumpFastStringStats :: DynFlags -> IO ()
538 dumpFastStringStats dflags = do
539 buckets <- getFastStringTable
540 let (entries, longest, is_z, has_z) = countFS 0 0 0 0 buckets
541 msg = text "FastString stats:" $$
542 nest 4 (vcat [text "size: " <+> int (length buckets),
543 text "entries: " <+> int entries,
544 text "longest chain: " <+> int longest,
545 text "z-encoded: " <+> (is_z `pcntOf` entries),
546 text "has z-encoding: " <+> (has_z `pcntOf` entries)
548 -- we usually get more "has z-encoding" than "z-encoded", because
549 -- when we z-encode a string it might hash to the exact same string,
550 -- which will is not counted as "z-encoded". Only strings whose
551 -- Z-encoding is different from the original string are counted in
552 -- the "z-encoded" total.
555 x `pcntOf` y = int ((x * 100) `quot` y) <> char '%'
557 countFS :: Int -> Int -> Int -> Int -> [[FastString]] -> (Int, Int, Int, Int)
558 countFS entries longest is_z has_z [] = (entries, longest, is_z, has_z)
559 countFS entries longest is_z has_z (b:bs) =
562 longest' = max len longest
563 entries' = entries + len
564 is_zs = length (filter isZEncoded b)
565 has_zs = length (filter hasZEncoding b)
567 countFS entries' longest' (is_z + is_zs) (has_z + has_zs) bs
569 -- -----------------------------------------------------------------------------
572 unknownFlagsErr :: [String] -> a
573 unknownFlagsErr fs = ghcError (UsageError ("unrecognised flags: " ++ unwords fs))