1 {-# OPTIONS -fno-warn-incomplete-patterns -optc-DNON_POSIX_SOURCE #-}
2 -----------------------------------------------------------------------------
6 -- (c) The University of Glasgow 2005
8 -----------------------------------------------------------------------------
10 module Main (main) where
12 #include "HsVersions.h"
14 -- The official GHC API
16 import GHC ( Session, DynFlags(..), HscTarget(..),
17 GhcMode(..), GhcLink(..),
18 LoadHowMuch(..), dopt, DynFlag(..) )
21 -- Implementations of the various modes (--show-iface, mkdependHS. etc.)
22 import LoadIface ( showIface )
23 import HscMain ( newHscEnv )
24 import DriverPipeline ( oneShot, compileFile )
25 import DriverMkDepend ( doMkDependHS )
27 import InteractiveUI ( interactiveUI, ghciWelcomeMsg )
30 -- Various other random stuff that we need
32 import Packages ( dumpPackages )
33 import DriverPhases ( Phase(..), isSourceFilename, anyHsc,
34 startPhase, isHaskellSrcFilename )
37 import BasicTypes ( failed )
38 import ErrUtils ( putMsg )
39 import FastString ( getFastStringTable, isZEncoded, hasZEncoding )
44 -- Standard Haskell libraries
45 import Control.Exception ( throwDyn )
47 import System.Directory ( doesDirectoryExist )
48 import System.Environment
54 -----------------------------------------------------------------------------
57 -- time commands when run with -v
59 -- Win32 support: proper signal handling
60 -- reading the package configuration file is too slow
63 -----------------------------------------------------------------------------
64 -- GHC's command-line interface
67 GHC.defaultErrorHandler defaultDynFlags $ do
69 -- 1. extract the -B flag from the args
73 (minusB_args, argv1) = partition ("-B" `isPrefixOf`) argv0
74 mbMinusB | null minusB_args = Nothing
75 | otherwise = Just (drop 2 (last minusB_args))
77 argv2 <- parseStaticFlags argv1
79 -- 2. Parse the "mode" flags (--make, --interactive etc.)
80 (cli_mode, argv3) <- parseModeFlags argv2
82 -- If all we want to do is to show the version number then do it
83 -- now, before we start a GHC session etc.
84 -- If we do it later then bootstrapping gets confused as it tries
85 -- to find out what version of GHC it's using before package.conf
86 -- exists, so starting the session fails.
88 ShowInfo -> do showInfo
90 ShowSupportedLanguages -> do showSupportedLanguages
92 ShowVersion -> do showVersion
94 ShowNumVersion -> do putStrLn cProjectVersion
98 -- start our GHC session
99 session <- GHC.newSession mbMinusB
101 dflags0 <- GHC.getSessionDynFlags session
103 -- set the default GhcMode, HscTarget and GhcLink. The HscTarget
104 -- can be further adjusted on a module by module basis, using only
105 -- the -fvia-C and -fasm flags. If the default HscTarget is not
106 -- HscC or HscAsm, -fvia-C and -fasm have no effect.
107 let dflt_target = hscTarget dflags0
110 DoInteractive -> (CompManager, HscInterpreted, LinkInMemory)
111 DoEval _ -> (CompManager, HscInterpreted, LinkInMemory)
112 DoMake -> (CompManager, dflt_target, LinkBinary)
113 DoMkDependHS -> (MkDepend, dflt_target, LinkBinary)
114 _ -> (OneShot, dflt_target, LinkBinary)
116 let dflags1 = dflags0{ ghcMode = mode,
119 -- leave out hscOutName for now
120 hscOutName = panic "Main.main:hscOutName not set",
121 verbosity = case cli_mode of
126 -- The rest of the arguments are "dynamic"
127 -- Leftover ones are presumably files
128 (dflags, fileish_args) <- GHC.parseDynamicFlags dflags1 argv3
130 -- make sure we clean up after ourselves
131 GHC.defaultCleanupHandler dflags $ do
133 showBanner cli_mode dflags
135 -- we've finished manipulating the DynFlags, update the session
136 GHC.setSessionDynFlags session dflags
137 dflags <- GHC.getSessionDynFlags session
140 -- To simplify the handling of filepaths, we normalise all filepaths right
141 -- away - e.g., for win32 platforms, backslashes are converted
142 -- into forward slashes.
143 normal_fileish_paths = map normalisePath fileish_args
144 (srcs, objs) = partition_args normal_fileish_paths [] []
146 -- Note: have v_Ld_inputs maintain the order in which 'objs' occurred on
148 mapM_ (consIORef v_Ld_inputs) (reverse objs)
150 ---------------- Display configuration -----------
151 when (verbosity dflags >= 4) $
154 when (verbosity dflags >= 3) $ do
155 hPutStrLn stderr ("Hsc static flags: " ++ unwords staticFlags)
157 ---------------- Final sanity checking -----------
158 checkOptions cli_mode dflags srcs objs
160 ---------------- Do the business -----------
161 let alreadyHandled = panic (show cli_mode ++
162 " should already have been handled")
164 ShowUsage -> showGhcUsage dflags cli_mode
165 PrintLibdir -> putStrLn (topDir dflags)
166 ShowSupportedLanguages -> alreadyHandled
167 ShowVersion -> alreadyHandled
168 ShowNumVersion -> alreadyHandled
169 ShowInterface f -> doShowIface dflags f
170 DoMake -> doMake session srcs
171 DoMkDependHS -> doMkDependHS session (map fst srcs)
172 StopBefore p -> oneShot dflags p srcs
173 DoInteractive -> interactiveUI session srcs Nothing
174 DoEval expr -> interactiveUI session srcs (Just expr)
176 dumpFinalStats dflags
180 interactiveUI _ _ _ =
181 throwDyn (CmdLineError "not built for interactive use")
184 -- -----------------------------------------------------------------------------
185 -- Splitting arguments into source files and object files. This is where we
186 -- interpret the -x <suffix> option, and attach a (Maybe Phase) to each source
187 -- file indicating the phase specified by the -x option in force, if any.
189 partition_args [] srcs objs = (reverse srcs, reverse objs)
190 partition_args ("-x":suff:args) srcs objs
191 | "none" <- suff = partition_args args srcs objs
192 | StopLn <- phase = partition_args args srcs (slurp ++ objs)
193 | otherwise = partition_args rest (these_srcs ++ srcs) objs
194 where phase = startPhase suff
195 (slurp,rest) = break (== "-x") args
196 these_srcs = zip slurp (repeat (Just phase))
197 partition_args (arg:args) srcs objs
198 | looks_like_an_input arg = partition_args args ((arg,Nothing):srcs) objs
199 | otherwise = partition_args args srcs (arg:objs)
202 We split out the object files (.o, .dll) and add them
203 to v_Ld_inputs for use by the linker.
205 The following things should be considered compilation manager inputs:
207 - haskell source files (strings ending in .hs, .lhs or other
208 haskellish extension),
210 - module names (not forgetting hierarchical module names),
212 - and finally we consider everything not containing a '.' to be
213 a comp manager input, as shorthand for a .hs or .lhs filename.
215 Everything else is considered to be a linker object, and passed
216 straight through to the linker.
218 looks_like_an_input m = isSourceFilename m
219 || looksLikeModuleName m
222 -- -----------------------------------------------------------------------------
223 -- Option sanity checks
225 checkOptions :: CmdLineMode -> DynFlags -> [(String,Maybe Phase)] -> [String] -> IO ()
226 -- Final sanity checking before kicking off a compilation (pipeline).
227 checkOptions cli_mode dflags srcs objs = do
228 -- Complain about any unknown flags
229 let unknown_opts = [ f | (f@('-':_), _) <- srcs ]
230 when (notNull unknown_opts) (unknownFlagsErr unknown_opts)
232 when (notNull (filter isRTSWay (wayNames dflags))
233 && isInterpretiveMode cli_mode) $
234 putStrLn ("Warning: -debug, -threaded and -ticky are ignored by GHCi")
236 -- -prof and --interactive are not a good combination
237 when (notNull (filter (not . isRTSWay) (wayNames dflags))
238 && isInterpretiveMode cli_mode) $
239 do throwDyn (UsageError
240 "--interactive can't be used with -prof or -unreg.")
242 if (isJust (outputHi dflags) &&
243 (isCompManagerMode cli_mode || srcs `lengthExceeds` 1))
244 then throwDyn (UsageError "-ohi can only be used when compiling a single source file")
247 -- -o sanity checking
248 if (srcs `lengthExceeds` 1 && isJust (outputFile dflags)
249 && not (isLinkMode cli_mode))
250 then throwDyn (UsageError "can't apply -o to multiple source files")
253 -- Check that there are some input files
254 -- (except in the interactive case)
255 if null srcs && null objs && needsInputsMode cli_mode
256 then throwDyn (UsageError "no input files")
259 -- Verify that output files point somewhere sensible.
260 verifyOutputFiles dflags
263 -- Compiler output options
265 -- called to verify that the output files & directories
266 -- point somewhere valid.
268 -- The assumption is that the directory portion of these output
269 -- options will have to exist by the time 'verifyOutputFiles'
272 verifyOutputFiles :: DynFlags -> IO ()
273 verifyOutputFiles dflags = do
274 let odir = objectDir dflags
275 when (isJust odir) $ do
276 let dir = fromJust odir
277 flg <- doesDirectoryExist dir
278 when (not flg) (nonExistentDir "-odir" dir)
279 let ofile = outputFile dflags
280 when (isJust ofile) $ do
281 let fn = fromJust ofile
282 flg <- doesDirNameExist fn
283 when (not flg) (nonExistentDir "-o" fn)
284 let ohi = outputHi dflags
285 when (isJust ohi) $ do
286 let hi = fromJust ohi
287 flg <- doesDirNameExist hi
288 when (not flg) (nonExistentDir "-ohi" hi)
290 nonExistentDir flg dir =
291 throwDyn (CmdLineError ("error: directory portion of " ++
292 show dir ++ " does not exist (used with " ++
293 show flg ++ " option.)"))
295 -----------------------------------------------------------------------------
296 -- GHC modes of operation
299 = ShowUsage -- ghc -?
300 | PrintLibdir -- ghc --print-libdir
301 | ShowInfo -- ghc --info
302 | ShowSupportedLanguages -- ghc --supported-languages
303 | ShowVersion -- ghc -V/--version
304 | ShowNumVersion -- ghc --numeric-version
305 | ShowInterface String -- ghc --show-iface
306 | DoMkDependHS -- ghc -M
307 | StopBefore Phase -- ghc -E | -C | -S
308 -- StopBefore StopLn is the default
309 | DoMake -- ghc --make
310 | DoInteractive -- ghc --interactive
311 | DoEval String -- ghc -e
314 isInteractiveMode, isInterpretiveMode :: CmdLineMode -> Bool
315 isLinkMode, isCompManagerMode :: CmdLineMode -> Bool
317 isInteractiveMode DoInteractive = True
318 isInteractiveMode _ = False
320 -- isInterpretiveMode: byte-code compiler involved
321 isInterpretiveMode DoInteractive = True
322 isInterpretiveMode (DoEval _) = True
323 isInterpretiveMode _ = False
325 needsInputsMode DoMkDependHS = True
326 needsInputsMode (StopBefore _) = True
327 needsInputsMode DoMake = True
328 needsInputsMode _ = False
330 -- True if we are going to attempt to link in this mode.
331 -- (we might not actually link, depending on the GhcLink flag)
332 isLinkMode (StopBefore StopLn) = True
333 isLinkMode DoMake = True
336 isCompManagerMode DoMake = True
337 isCompManagerMode DoInteractive = True
338 isCompManagerMode (DoEval _) = True
339 isCompManagerMode _ = False
342 -- -----------------------------------------------------------------------------
343 -- Parsing the mode flag
345 parseModeFlags :: [String] -> IO (CmdLineMode, [String])
346 parseModeFlags args = do
347 let ((leftover, errs), (mode, _, flags)) =
348 runCmdLine (processArgs mode_flags args) (StopBefore StopLn, "", [])
349 when (not (null errs)) $ do
350 throwDyn (UsageError (unlines errs))
351 return (mode, flags ++ leftover)
353 type ModeM a = CmdLineP (CmdLineMode, String, [String]) a
354 -- mode flags sometimes give rise to new DynFlags (eg. -C, see below)
355 -- so we collect the new ones and return them.
357 mode_flags :: [(String, OptKind (CmdLineP (CmdLineMode, String, [String])))]
359 [ ------- help / version ----------------------------------------------
360 ( "?" , PassFlag (setMode ShowUsage))
361 , ( "-help" , PassFlag (setMode ShowUsage))
362 , ( "-print-libdir" , PassFlag (setMode PrintLibdir))
363 , ( "V" , PassFlag (setMode ShowVersion))
364 , ( "-version" , PassFlag (setMode ShowVersion))
365 , ( "-numeric-version", PassFlag (setMode ShowNumVersion))
366 , ( "-info", PassFlag (setMode ShowInfo))
367 , ( "-supported-languages", PassFlag (setMode ShowSupportedLanguages))
369 ------- interfaces ----------------------------------------------------
370 , ( "-show-iface" , HasArg (\f -> setMode (ShowInterface f)
373 ------- primary modes ------------------------------------------------
374 , ( "M" , PassFlag (setMode DoMkDependHS))
375 , ( "E" , PassFlag (setMode (StopBefore anyHsc)))
376 , ( "C" , PassFlag (\f -> do setMode (StopBefore HCc) f
378 , ( "S" , PassFlag (setMode (StopBefore As)))
379 , ( "-make" , PassFlag (setMode DoMake))
380 , ( "-interactive" , PassFlag (setMode DoInteractive))
381 , ( "e" , HasArg (\s -> setMode (DoEval s) "-e"))
383 -- -fno-code says to stop after Hsc but don't generate any code.
384 , ( "fno-code" , PassFlag (\f -> do setMode (StopBefore HCc) f
386 addFlag "-no-recomp"))
389 setMode :: CmdLineMode -> String -> ModeM ()
391 (old_mode, old_flag, flags) <- getCmdLineState
392 when (notNull old_flag && flag /= old_flag) $
394 ("cannot use `" ++ old_flag ++ "' with `" ++ flag ++ "'"))
395 putCmdLineState (m, flag, flags)
397 addFlag :: String -> ModeM ()
399 (m, f, flags) <- getCmdLineState
400 putCmdLineState (m, f, s:flags)
403 -- ----------------------------------------------------------------------------
406 doMake :: Session -> [(String,Maybe Phase)] -> IO ()
407 doMake sess [] = throwDyn (UsageError "no input files")
408 doMake sess srcs = do
409 let (hs_srcs, non_hs_srcs) = partition haskellish srcs
411 haskellish (f,Nothing) =
412 looksLikeModuleName f || isHaskellSrcFilename f || '.' `notElem` f
413 haskellish (f,Just phase) =
414 phase `notElem` [As, Cc, CmmCpp, Cmm, StopLn]
416 dflags <- GHC.getSessionDynFlags sess
417 o_files <- mapM (compileFile dflags StopLn) non_hs_srcs
418 mapM_ (consIORef v_Ld_inputs) (reverse o_files)
420 targets <- mapM (uncurry GHC.guessTarget) hs_srcs
421 GHC.setTargets sess targets
422 ok_flag <- GHC.load sess LoadAllTargets
423 when (failed ok_flag) (exitWith (ExitFailure 1))
427 -- ---------------------------------------------------------------------------
430 doShowIface :: DynFlags -> FilePath -> IO ()
431 doShowIface dflags file = do
432 hsc_env <- newHscEnv dflags
433 showIface hsc_env file
435 -- ---------------------------------------------------------------------------
436 -- Various banners and verbosity output.
438 showBanner :: CmdLineMode -> DynFlags -> IO ()
439 showBanner cli_mode dflags = do
440 let verb = verbosity dflags
443 -- Show the GHCi banner
444 when (isInteractiveMode cli_mode && verb >= 1) $ putStrLn ghciWelcomeMsg
447 -- Display details of the configuration in verbose mode
449 do hPutStr stderr "Glasgow Haskell Compiler, Version "
450 hPutStr stderr cProjectVersion
451 hPutStr stderr ", for Haskell 98, stage "
452 hPutStr stderr cStage
453 hPutStr stderr " booted by GHC version "
454 hPutStrLn stderr cBooterVersion
456 -- We print out a Read-friendly string, but a prettier one than the
457 -- Show instance gives us
460 let sq x = " [" ++ x ++ "\n ]"
461 putStrLn $ sq $ concat $ intersperse "\n ," $ map show compilerInfo
464 showSupportedLanguages :: IO ()
465 showSupportedLanguages = do mapM_ putStrLn supportedLanguages
470 putStrLn (cProjectName ++ ", version " ++ cProjectVersion)
473 showGhcUsage dflags cli_mode = do
475 | DoInteractive <- cli_mode = ghciUsagePath dflags
476 | otherwise = ghcUsagePath dflags
477 usage <- readFile usage_path
482 dump ('$':'$':s) = putStr progName >> dump s
483 dump (c:s) = putChar c >> dump s
485 dumpFinalStats :: DynFlags -> IO ()
486 dumpFinalStats dflags =
487 when (dopt Opt_D_faststring_stats dflags) $ dumpFastStringStats dflags
489 dumpFastStringStats :: DynFlags -> IO ()
490 dumpFastStringStats dflags = do
491 buckets <- getFastStringTable
492 let (entries, longest, is_z, has_z) = countFS 0 0 0 0 buckets
493 msg = text "FastString stats:" $$
494 nest 4 (vcat [text "size: " <+> int (length buckets),
495 text "entries: " <+> int entries,
496 text "longest chain: " <+> int longest,
497 text "z-encoded: " <+> (is_z `pcntOf` entries),
498 text "has z-encoding: " <+> (has_z `pcntOf` entries)
500 -- we usually get more "has z-encoding" than "z-encoded", because
501 -- when we z-encode a string it might hash to the exact same string,
502 -- which will is not counted as "z-encoded". Only strings whose
503 -- Z-encoding is different from the original string are counted in
504 -- the "z-encoded" total.
507 x `pcntOf` y = int ((x * 100) `quot` y) <> char '%'
509 countFS entries longest is_z has_z [] = (entries, longest, is_z, has_z)
510 countFS entries longest is_z has_z (b:bs) =
513 longest' = max len longest
514 entries' = entries + len
515 is_zs = length (filter isZEncoded b)
516 has_zs = length (filter hasZEncoding b)
518 countFS entries' longest' (is_z + is_zs) (has_z + has_zs) bs
520 -- -----------------------------------------------------------------------------
523 unknownFlagsErr :: [String] -> a
524 unknownFlagsErr fs = throwDyn (UsageError ("unrecognised flags: " ++ unwords fs))