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
157 handleSourceError (\e -> do
158 GHC.printExceptionAndWarnings e
159 liftIO $ exitWith (ExitFailure 1)) $
160 handleFlagWarnings dflags2 flagWarnings
162 -- make sure we clean up after ourselves
163 GHC.defaultCleanupHandler dflags2 $ do
165 liftIO $ showBanner cli_mode dflags2
167 -- we've finished manipulating the DynFlags, update the session
168 GHC.setSessionDynFlags dflags2
169 dflags3 <- GHC.getSessionDynFlags
170 hsc_env <- GHC.getSession
173 -- To simplify the handling of filepaths, we normalise all filepaths right
174 -- away - e.g., for win32 platforms, backslashes are converted
175 -- into forward slashes.
176 normal_fileish_paths = map (normalise . unLoc) fileish_args
177 (srcs, objs) = partition_args normal_fileish_paths [] []
179 -- Note: have v_Ld_inputs maintain the order in which 'objs' occurred on
181 liftIO $ mapM_ (consIORef v_Ld_inputs) (reverse objs)
183 ---------------- Display configuration -----------
184 when (verbosity dflags3 >= 4) $
185 liftIO $ dumpPackages dflags3
187 when (verbosity dflags3 >= 3) $ do
188 liftIO $ hPutStrLn stderr ("Hsc static flags: " ++ unwords staticFlags)
190 ---------------- Final sanity checking -----------
191 liftIO $ checkOptions cli_mode dflags3 srcs objs
193 ---------------- Do the business -----------
194 handleSourceError (\e -> do
195 GHC.printExceptionAndWarnings e
196 liftIO $ exitWith (ExitFailure 1)) $ do
198 PrintLibdir -> liftIO $ putStrLn (topDir dflags3)
199 ShowInterface f -> liftIO $ doShowIface dflags3 f
200 DoMake -> doMake srcs
201 DoMkDependHS -> doMkDependHS (map fst srcs)
202 StopBefore p -> oneShot hsc_env p srcs >> GHC.printWarnings
203 DoInteractive -> interactiveUI srcs Nothing
204 DoEval exprs -> interactiveUI srcs $ Just $ reverse exprs
206 liftIO $ dumpFinalStats dflags3
207 liftIO $ exitWith ExitSuccess
210 interactiveUI :: b -> c -> Ghc ()
212 ghcError (CmdLineError "not built for interactive use")
215 -- -----------------------------------------------------------------------------
216 -- Splitting arguments into source files and object files. This is where we
217 -- interpret the -x <suffix> option, and attach a (Maybe Phase) to each source
218 -- file indicating the phase specified by the -x option in force, if any.
220 partition_args :: [String] -> [(String, Maybe Phase)] -> [String]
221 -> ([(String, Maybe Phase)], [String])
222 partition_args [] srcs objs = (reverse srcs, reverse objs)
223 partition_args ("-x":suff:args) srcs objs
224 | "none" <- suff = partition_args args srcs objs
225 | StopLn <- phase = partition_args args srcs (slurp ++ objs)
226 | otherwise = partition_args rest (these_srcs ++ srcs) objs
227 where phase = startPhase suff
228 (slurp,rest) = break (== "-x") args
229 these_srcs = zip slurp (repeat (Just phase))
230 partition_args (arg:args) srcs objs
231 | looks_like_an_input arg = partition_args args ((arg,Nothing):srcs) objs
232 | otherwise = partition_args args srcs (arg:objs)
235 We split out the object files (.o, .dll) and add them
236 to v_Ld_inputs for use by the linker.
238 The following things should be considered compilation manager inputs:
240 - haskell source files (strings ending in .hs, .lhs or other
241 haskellish extension),
243 - module names (not forgetting hierarchical module names),
245 - and finally we consider everything not containing a '.' to be
246 a comp manager input, as shorthand for a .hs or .lhs filename.
248 Everything else is considered to be a linker object, and passed
249 straight through to the linker.
251 looks_like_an_input :: String -> Bool
252 looks_like_an_input m = isSourceFilename m
253 || looksLikeModuleName m
256 -- -----------------------------------------------------------------------------
257 -- Option sanity checks
259 -- | Ensure sanity of options.
261 -- Throws 'UsageError' or 'CmdLineError' if not.
262 checkOptions :: CmdLineMode -> DynFlags -> [(String,Maybe Phase)] -> [String] -> IO ()
263 -- Final sanity checking before kicking off a compilation (pipeline).
264 checkOptions cli_mode dflags srcs objs = do
265 -- Complain about any unknown flags
266 let unknown_opts = [ f | (f@('-':_), _) <- srcs ]
267 when (notNull unknown_opts) (unknownFlagsErr unknown_opts)
269 when (notNull (filter isRTSWay (wayNames dflags))
270 && isInterpretiveMode cli_mode) $
271 hPutStrLn stderr ("Warning: -debug, -threaded and -ticky are ignored by GHCi")
273 -- -prof and --interactive are not a good combination
274 when (notNull (filter (not . isRTSWay) (wayNames dflags))
275 && isInterpretiveMode cli_mode) $
276 do ghcError (UsageError
277 "--interactive can't be used with -prof or -unreg.")
279 if (isJust (outputHi dflags) &&
280 (isCompManagerMode cli_mode || srcs `lengthExceeds` 1))
281 then ghcError (UsageError "-ohi can only be used when compiling a single source file")
284 -- -o sanity checking
285 if (srcs `lengthExceeds` 1 && isJust (outputFile dflags)
286 && not (isLinkMode cli_mode))
287 then ghcError (UsageError "can't apply -o to multiple source files")
290 let not_linking = not (isLinkMode cli_mode) || isNoLink (ghcLink dflags)
292 when (not_linking && not (null objs)) $
293 hPutStrLn stderr ("Warning: the following files would be used as linker inputs, but linking is not being done: " ++ unwords objs)
295 -- Check that there are some input files
296 -- (except in the interactive case)
297 if null srcs && (null objs || not_linking) && needsInputsMode cli_mode
298 then ghcError (UsageError "no input files")
301 -- Verify that output files point somewhere sensible.
302 verifyOutputFiles dflags
305 -- Compiler output options
307 -- called to verify that the output files & directories
308 -- point somewhere valid.
310 -- The assumption is that the directory portion of these output
311 -- options will have to exist by the time 'verifyOutputFiles'
314 verifyOutputFiles :: DynFlags -> IO ()
315 verifyOutputFiles dflags = do
316 -- not -odir: we create the directory for -odir if it doesn't exist (#2278).
317 let ofile = outputFile dflags
318 when (isJust ofile) $ do
319 let fn = fromJust ofile
320 flg <- doesDirNameExist fn
321 when (not flg) (nonExistentDir "-o" fn)
322 let ohi = outputHi dflags
323 when (isJust ohi) $ do
324 let hi = fromJust ohi
325 flg <- doesDirNameExist hi
326 when (not flg) (nonExistentDir "-ohi" hi)
328 nonExistentDir flg dir =
329 ghcError (CmdLineError ("error: directory portion of " ++
330 show dir ++ " does not exist (used with " ++
331 show flg ++ " option.)"))
333 -----------------------------------------------------------------------------
334 -- GHC modes of operation
337 = ShowUsage -- ghc -?
338 | ShowVersion -- ghc -V/--version
339 | ShowNumVersion -- ghc --numeric-version
340 | ShowSupportedLanguages -- ghc --supported-languages
341 | ShowInfo -- ghc --info
345 = PrintLibdir -- ghc --print-libdir
346 | ShowInterface String -- ghc --show-iface
347 | DoMkDependHS -- ghc -M
348 | StopBefore Phase -- ghc -E | -C | -S
349 -- StopBefore StopLn is the default
350 | DoMake -- ghc --make
351 | DoInteractive -- ghc --interactive
352 | DoEval [String] -- ghc -e foo -e bar => DoEval ["bar", "foo"]
356 isInteractiveMode :: CmdLineMode -> Bool
357 isInteractiveMode DoInteractive = True
358 isInteractiveMode _ = False
361 -- isInterpretiveMode: byte-code compiler involved
362 isInterpretiveMode :: CmdLineMode -> Bool
363 isInterpretiveMode DoInteractive = True
364 isInterpretiveMode (DoEval _) = True
365 isInterpretiveMode _ = False
367 needsInputsMode :: CmdLineMode -> Bool
368 needsInputsMode DoMkDependHS = True
369 needsInputsMode (StopBefore _) = True
370 needsInputsMode DoMake = True
371 needsInputsMode _ = False
373 -- True if we are going to attempt to link in this mode.
374 -- (we might not actually link, depending on the GhcLink flag)
375 isLinkMode :: CmdLineMode -> Bool
376 isLinkMode (StopBefore StopLn) = True
377 isLinkMode DoMake = True
378 isLinkMode DoInteractive = True
379 isLinkMode (DoEval _) = True
382 isCompManagerMode :: CmdLineMode -> Bool
383 isCompManagerMode DoMake = True
384 isCompManagerMode DoInteractive = True
385 isCompManagerMode (DoEval _) = True
386 isCompManagerMode _ = False
389 -- -----------------------------------------------------------------------------
390 -- Parsing the mode flag
392 parseModeFlags :: [Located String]
393 -> IO (Maybe UberMode,
397 parseModeFlags args = do
398 let ((leftover, errs, warns), (mUberMode, mode, _, flags')) =
399 runCmdLine (processArgs mode_flags args)
400 (Nothing, StopBefore StopLn, "", [])
401 when (not (null errs)) $ ghcError $ errorsToGhcException errs
402 return (mUberMode, mode, flags' ++ leftover, warns)
404 type ModeM = CmdLineP (Maybe UberMode, CmdLineMode, String, [Located String])
405 -- mode flags sometimes give rise to new DynFlags (eg. -C, see below)
406 -- so we collect the new ones and return them.
408 mode_flags :: [Flag ModeM]
410 [ ------- help / version ----------------------------------------------
411 Flag "?" (NoArg (setUberMode ShowUsage))
413 , Flag "-help" (NoArg (setUberMode ShowUsage))
415 , Flag "V" (NoArg (setUberMode ShowVersion))
417 , Flag "-version" (NoArg (setUberMode ShowVersion))
419 , Flag "-numeric-version" (NoArg (setUberMode ShowNumVersion))
421 , Flag "-info" (NoArg (setUberMode ShowInfo))
423 , Flag "-supported-languages" (NoArg (setUberMode ShowSupportedLanguages))
425 , Flag "-print-libdir" (PassFlag (setMode PrintLibdir))
428 ------- interfaces ----------------------------------------------------
429 , Flag "-show-iface" (HasArg (\f -> setMode (ShowInterface f)
433 ------- primary modes ------------------------------------------------
434 , Flag "M" (PassFlag (setMode DoMkDependHS))
436 , Flag "E" (PassFlag (setMode (StopBefore anyHsc)))
438 , Flag "C" (PassFlag (\f -> do setMode (StopBefore HCc) f
441 , Flag "S" (PassFlag (setMode (StopBefore As)))
443 , Flag "-make" (PassFlag (setMode DoMake))
445 , Flag "-interactive" (PassFlag (setMode DoInteractive))
447 , Flag "e" (HasArg (\s -> updateMode (updateDoEval s) "-e"))
450 -- -fno-code says to stop after Hsc but don't generate any code.
451 , Flag "fno-code" (PassFlag (\f -> do setMode (StopBefore HCc) f
453 addFlag "-fforce-recomp"))
457 setUberMode :: UberMode -> ModeM ()
459 (_, cmdLineMode, flag, flags') <- getCmdLineState
460 putCmdLineState (Just m, cmdLineMode, flag, flags')
462 setMode :: CmdLineMode -> String -> ModeM ()
463 setMode m flag = updateMode (\_ -> m) flag
465 updateDoEval :: String -> CmdLineMode -> CmdLineMode
466 updateDoEval expr (DoEval exprs) = DoEval (expr : exprs)
467 updateDoEval expr _ = DoEval [expr]
469 updateMode :: (CmdLineMode -> CmdLineMode) -> String -> ModeM ()
470 updateMode f flag = do
471 (m_uber_mode, old_mode, old_flag, flags') <- getCmdLineState
472 if null old_flag || flag == old_flag
473 then putCmdLineState (m_uber_mode, f old_mode, flag, flags')
474 else ghcError (UsageError
475 ("cannot use `" ++ old_flag ++ "' with `" ++ flag ++ "'"))
477 addFlag :: String -> ModeM ()
479 (u, m, f, flags') <- getCmdLineState
480 -- XXX Can we get a useful Loc?
481 putCmdLineState (u, m, f, mkGeneralLocated "addFlag" s : flags')
484 -- ----------------------------------------------------------------------------
487 doMake :: [(String,Maybe Phase)] -> Ghc ()
488 doMake [] = ghcError (UsageError "no input files")
490 let (hs_srcs, non_hs_srcs) = partition haskellish srcs
492 haskellish (f,Nothing) =
493 looksLikeModuleName f || isHaskellSrcFilename f || '.' `notElem` f
494 haskellish (_,Just phase) =
495 phase `notElem` [As, Cc, CmmCpp, Cmm, StopLn]
497 hsc_env <- GHC.getSession
498 o_files <- mapM (\x -> do
499 f <- compileFile hsc_env StopLn x
503 liftIO $ mapM_ (consIORef v_Ld_inputs) (reverse o_files)
505 targets <- mapM (uncurry GHC.guessTarget) hs_srcs
506 GHC.setTargets targets
507 ok_flag <- GHC.load LoadAllTargets
509 when (failed ok_flag) (liftIO $ exitWith (ExitFailure 1))
513 -- ---------------------------------------------------------------------------
516 doShowIface :: DynFlags -> FilePath -> IO ()
517 doShowIface dflags file = do
518 hsc_env <- newHscEnv dflags
519 showIface hsc_env file
521 -- ---------------------------------------------------------------------------
522 -- Various banners and verbosity output.
524 showBanner :: CmdLineMode -> DynFlags -> IO ()
525 showBanner _cli_mode dflags = do
526 let verb = verbosity dflags
529 -- Show the GHCi banner
530 when (isInteractiveMode _cli_mode && verb >= 1) $ putStrLn ghciWelcomeMsg
533 -- Display details of the configuration in verbose mode
535 do hPutStr stderr "Glasgow Haskell Compiler, Version "
536 hPutStr stderr cProjectVersion
537 hPutStr stderr ", for Haskell 98, stage "
538 hPutStr stderr cStage
539 hPutStr stderr " booted by GHC version "
540 hPutStrLn stderr cBooterVersion
542 -- We print out a Read-friendly string, but a prettier one than the
543 -- Show instance gives us
546 let sq x = " [" ++ x ++ "\n ]"
547 putStrLn $ sq $ concat $ intersperse "\n ," $ map show compilerInfo
550 showSupportedLanguages :: IO ()
551 showSupportedLanguages = do mapM_ putStrLn supportedLanguages
556 putStrLn (cProjectName ++ ", version " ++ cProjectVersion)
559 showGhcUsage :: DynFlags -> CmdLineMode -> IO ()
560 showGhcUsage dflags cli_mode = do
562 | DoInteractive <- cli_mode = ghciUsagePath dflags
563 | otherwise = ghcUsagePath dflags
564 usage <- readFile usage_path
569 dump ('$':'$':s) = putStr progName >> dump s
570 dump (c:s) = putChar c >> dump s
572 dumpFinalStats :: DynFlags -> IO ()
573 dumpFinalStats dflags =
574 when (dopt Opt_D_faststring_stats dflags) $ dumpFastStringStats dflags
576 dumpFastStringStats :: DynFlags -> IO ()
577 dumpFastStringStats dflags = do
578 buckets <- getFastStringTable
579 let (entries, longest, is_z, has_z) = countFS 0 0 0 0 buckets
580 msg = text "FastString stats:" $$
581 nest 4 (vcat [text "size: " <+> int (length buckets),
582 text "entries: " <+> int entries,
583 text "longest chain: " <+> int longest,
584 text "z-encoded: " <+> (is_z `pcntOf` entries),
585 text "has z-encoding: " <+> (has_z `pcntOf` entries)
587 -- we usually get more "has z-encoding" than "z-encoded", because
588 -- when we z-encode a string it might hash to the exact same string,
589 -- which will is not counted as "z-encoded". Only strings whose
590 -- Z-encoding is different from the original string are counted in
591 -- the "z-encoded" total.
594 x `pcntOf` y = int ((x * 100) `quot` y) <> char '%'
596 countFS :: Int -> Int -> Int -> Int -> [[FastString]] -> (Int, Int, Int, Int)
597 countFS entries longest is_z has_z [] = (entries, longest, is_z, has_z)
598 countFS entries longest is_z has_z (b:bs) =
601 longest' = max len longest
602 entries' = entries + len
603 is_zs = length (filter isZEncoded b)
604 has_zs = length (filter hasZEncoding b)
606 countFS entries' longest' (is_z + is_zs) (has_z + has_zs) bs
608 -- -----------------------------------------------------------------------------
611 unknownFlagsErr :: [String] -> a
612 unknownFlagsErr fs = ghcError (UsageError ("unrecognised flags: " ++ unwords fs))