1 {-# OPTIONS -fno-warn-incomplete-patterns -optc-DNON_POSIX_SOURCE #-}
3 -- The above warning supression flag is a temporary kludge.
4 -- While working on this module you are encouraged to remove it and fix
5 -- any warnings in the module. See
6 -- http://hackage.haskell.org/trac/ghc/wiki/Commentary/CodingStyle#Warnings
9 -----------------------------------------------------------------------------
13 -- (c) The University of Glasgow 2005
15 -----------------------------------------------------------------------------
17 module Main (main) where
19 #include "HsVersions.h"
21 -- The official GHC API
23 import GHC ( Session, DynFlags(..), HscTarget(..),
24 GhcMode(..), GhcLink(..),
25 LoadHowMuch(..), dopt, DynFlag(..) )
28 -- Implementations of the various modes (--show-iface, mkdependHS. etc.)
29 import LoadIface ( showIface )
30 import HscMain ( newHscEnv )
31 import DriverPipeline ( oneShot, compileFile )
32 import DriverMkDepend ( doMkDependHS )
34 import InteractiveUI ( interactiveUI, ghciWelcomeMsg )
37 -- Various other random stuff that we need
39 import Packages ( dumpPackages )
40 import DriverPhases ( Phase(..), isSourceFilename, anyHsc,
41 startPhase, isHaskellSrcFilename )
44 import BasicTypes ( failed )
45 import ErrUtils ( putMsg )
46 import FastString ( getFastStringTable, isZEncoded, hasZEncoding )
51 -- Standard Haskell libraries
52 import Control.Exception ( throwDyn )
54 import System.Directory ( doesDirectoryExist )
55 import System.Environment
57 import System.FilePath
62 -----------------------------------------------------------------------------
65 -- time commands when run with -v
67 -- Win32 support: proper signal handling
68 -- reading the package configuration file is too slow
71 -----------------------------------------------------------------------------
72 -- GHC's command-line interface
75 GHC.defaultErrorHandler defaultDynFlags $ do
77 -- 1. extract the -B flag from the args
81 (minusB_args, argv1) = partition ("-B" `isPrefixOf`) argv0
82 mbMinusB | null minusB_args = Nothing
83 | otherwise = Just (drop 2 (last minusB_args))
85 argv2 <- parseStaticFlags argv1
87 -- 2. Parse the "mode" flags (--make, --interactive etc.)
88 (cli_mode, argv3) <- parseModeFlags argv2
90 -- If all we want to do is to show the version number then do it
91 -- now, before we start a GHC session etc.
92 -- If we do it later then bootstrapping gets confused as it tries
93 -- to find out what version of GHC it's using before package.conf
94 -- exists, so starting the session fails.
96 ShowInfo -> do showInfo
98 ShowSupportedLanguages -> do showSupportedLanguages
100 ShowVersion -> do showVersion
102 ShowNumVersion -> do putStrLn cProjectVersion
106 -- start our GHC session
107 session <- GHC.newSession mbMinusB
109 dflags0 <- GHC.getSessionDynFlags session
111 -- set the default GhcMode, HscTarget and GhcLink. The HscTarget
112 -- can be further adjusted on a module by module basis, using only
113 -- the -fvia-C and -fasm flags. If the default HscTarget is not
114 -- HscC or HscAsm, -fvia-C and -fasm have no effect.
115 let dflt_target = hscTarget dflags0
118 DoInteractive -> (CompManager, HscInterpreted, LinkInMemory)
119 DoEval _ -> (CompManager, HscInterpreted, LinkInMemory)
120 DoMake -> (CompManager, dflt_target, LinkBinary)
121 DoMkDependHS -> (MkDepend, dflt_target, LinkBinary)
122 _ -> (OneShot, dflt_target, LinkBinary)
124 let dflags1 = dflags0{ ghcMode = mode,
127 -- leave out hscOutName for now
128 hscOutName = panic "Main.main:hscOutName not set",
129 verbosity = case cli_mode of
134 -- The rest of the arguments are "dynamic"
135 -- Leftover ones are presumably files
136 (dflags, fileish_args) <- GHC.parseDynamicFlags dflags1 argv3
138 -- make sure we clean up after ourselves
139 GHC.defaultCleanupHandler dflags $ do
141 showBanner cli_mode dflags
143 -- we've finished manipulating the DynFlags, update the session
144 GHC.setSessionDynFlags session dflags
145 dflags <- GHC.getSessionDynFlags session
148 -- To simplify the handling of filepaths, we normalise all filepaths right
149 -- away - e.g., for win32 platforms, backslashes are converted
150 -- into forward slashes.
151 normal_fileish_paths = map normalise fileish_args
152 (srcs, objs) = partition_args normal_fileish_paths [] []
154 -- Note: have v_Ld_inputs maintain the order in which 'objs' occurred on
156 mapM_ (consIORef v_Ld_inputs) (reverse objs)
158 ---------------- Display configuration -----------
159 when (verbosity dflags >= 4) $
162 when (verbosity dflags >= 3) $ do
163 hPutStrLn stderr ("Hsc static flags: " ++ unwords staticFlags)
165 ---------------- Final sanity checking -----------
166 checkOptions cli_mode dflags srcs objs
168 ---------------- Do the business -----------
169 let alreadyHandled = panic (show cli_mode ++
170 " should already have been handled")
172 ShowUsage -> showGhcUsage dflags cli_mode
173 PrintLibdir -> putStrLn (topDir dflags)
174 ShowSupportedLanguages -> alreadyHandled
175 ShowVersion -> alreadyHandled
176 ShowNumVersion -> alreadyHandled
177 ShowInterface f -> doShowIface dflags f
178 DoMake -> doMake session srcs
179 DoMkDependHS -> doMkDependHS session (map fst srcs)
180 StopBefore p -> oneShot dflags p srcs
181 DoInteractive -> interactiveUI session srcs Nothing
182 DoEval expr -> interactiveUI session srcs (Just expr)
184 dumpFinalStats dflags
188 interactiveUI _ _ _ =
189 throwDyn (CmdLineError "not built for interactive use")
192 -- -----------------------------------------------------------------------------
193 -- Splitting arguments into source files and object files. This is where we
194 -- interpret the -x <suffix> option, and attach a (Maybe Phase) to each source
195 -- file indicating the phase specified by the -x option in force, if any.
197 partition_args [] srcs objs = (reverse srcs, reverse objs)
198 partition_args ("-x":suff:args) srcs objs
199 | "none" <- suff = partition_args args srcs objs
200 | StopLn <- phase = partition_args args srcs (slurp ++ objs)
201 | otherwise = partition_args rest (these_srcs ++ srcs) objs
202 where phase = startPhase suff
203 (slurp,rest) = break (== "-x") args
204 these_srcs = zip slurp (repeat (Just phase))
205 partition_args (arg:args) srcs objs
206 | looks_like_an_input arg = partition_args args ((arg,Nothing):srcs) objs
207 | otherwise = partition_args args srcs (arg:objs)
210 We split out the object files (.o, .dll) and add them
211 to v_Ld_inputs for use by the linker.
213 The following things should be considered compilation manager inputs:
215 - haskell source files (strings ending in .hs, .lhs or other
216 haskellish extension),
218 - module names (not forgetting hierarchical module names),
220 - and finally we consider everything not containing a '.' to be
221 a comp manager input, as shorthand for a .hs or .lhs filename.
223 Everything else is considered to be a linker object, and passed
224 straight through to the linker.
226 looks_like_an_input m = isSourceFilename m
227 || looksLikeModuleName m
230 -- -----------------------------------------------------------------------------
231 -- Option sanity checks
233 checkOptions :: CmdLineMode -> DynFlags -> [(String,Maybe Phase)] -> [String] -> IO ()
234 -- Final sanity checking before kicking off a compilation (pipeline).
235 checkOptions cli_mode dflags srcs objs = do
236 -- Complain about any unknown flags
237 let unknown_opts = [ f | (f@('-':_), _) <- srcs ]
238 when (notNull unknown_opts) (unknownFlagsErr unknown_opts)
240 when (notNull (filter isRTSWay (wayNames dflags))
241 && isInterpretiveMode cli_mode) $
242 putStrLn ("Warning: -debug, -threaded and -ticky are ignored by GHCi")
244 -- -prof and --interactive are not a good combination
245 when (notNull (filter (not . isRTSWay) (wayNames dflags))
246 && isInterpretiveMode cli_mode) $
247 do throwDyn (UsageError
248 "--interactive can't be used with -prof or -unreg.")
250 if (isJust (outputHi dflags) &&
251 (isCompManagerMode cli_mode || srcs `lengthExceeds` 1))
252 then throwDyn (UsageError "-ohi can only be used when compiling a single source file")
255 -- -o sanity checking
256 if (srcs `lengthExceeds` 1 && isJust (outputFile dflags)
257 && not (isLinkMode cli_mode))
258 then throwDyn (UsageError "can't apply -o to multiple source files")
261 -- Check that there are some input files
262 -- (except in the interactive case)
263 if null srcs && null objs && needsInputsMode cli_mode
264 then throwDyn (UsageError "no input files")
267 -- Verify that output files point somewhere sensible.
268 verifyOutputFiles dflags
271 -- Compiler output options
273 -- called to verify that the output files & directories
274 -- point somewhere valid.
276 -- The assumption is that the directory portion of these output
277 -- options will have to exist by the time 'verifyOutputFiles'
280 verifyOutputFiles :: DynFlags -> IO ()
281 verifyOutputFiles dflags = do
282 let odir = objectDir dflags
283 when (isJust odir) $ do
284 let dir = fromJust odir
285 flg <- doesDirectoryExist dir
286 when (not flg) (nonExistentDir "-odir" dir)
287 let ofile = outputFile dflags
288 when (isJust ofile) $ do
289 let fn = fromJust ofile
290 flg <- doesDirNameExist fn
291 when (not flg) (nonExistentDir "-o" fn)
292 let ohi = outputHi dflags
293 when (isJust ohi) $ do
294 let hi = fromJust ohi
295 flg <- doesDirNameExist hi
296 when (not flg) (nonExistentDir "-ohi" hi)
298 nonExistentDir flg dir =
299 throwDyn (CmdLineError ("error: directory portion of " ++
300 show dir ++ " does not exist (used with " ++
301 show flg ++ " option.)"))
303 -----------------------------------------------------------------------------
304 -- GHC modes of operation
307 = ShowUsage -- ghc -?
308 | PrintLibdir -- ghc --print-libdir
309 | ShowInfo -- ghc --info
310 | ShowSupportedLanguages -- ghc --supported-languages
311 | ShowVersion -- ghc -V/--version
312 | ShowNumVersion -- ghc --numeric-version
313 | ShowInterface String -- ghc --show-iface
314 | DoMkDependHS -- ghc -M
315 | StopBefore Phase -- ghc -E | -C | -S
316 -- StopBefore StopLn is the default
317 | DoMake -- ghc --make
318 | DoInteractive -- ghc --interactive
319 | DoEval String -- ghc -e
322 isInteractiveMode, isInterpretiveMode :: CmdLineMode -> Bool
323 isLinkMode, isCompManagerMode :: CmdLineMode -> Bool
325 isInteractiveMode DoInteractive = True
326 isInteractiveMode _ = False
328 -- isInterpretiveMode: byte-code compiler involved
329 isInterpretiveMode DoInteractive = True
330 isInterpretiveMode (DoEval _) = True
331 isInterpretiveMode _ = False
333 needsInputsMode DoMkDependHS = True
334 needsInputsMode (StopBefore _) = True
335 needsInputsMode DoMake = True
336 needsInputsMode _ = False
338 -- True if we are going to attempt to link in this mode.
339 -- (we might not actually link, depending on the GhcLink flag)
340 isLinkMode (StopBefore StopLn) = True
341 isLinkMode DoMake = True
344 isCompManagerMode DoMake = True
345 isCompManagerMode DoInteractive = True
346 isCompManagerMode (DoEval _) = True
347 isCompManagerMode _ = False
350 -- -----------------------------------------------------------------------------
351 -- Parsing the mode flag
353 parseModeFlags :: [String] -> IO (CmdLineMode, [String])
354 parseModeFlags args = do
355 let ((leftover, errs), (mode, _, flags)) =
356 runCmdLine (processArgs mode_flags args) (StopBefore StopLn, "", [])
357 when (not (null errs)) $ do
358 throwDyn (UsageError (unlines errs))
359 return (mode, flags ++ leftover)
361 type ModeM a = CmdLineP (CmdLineMode, String, [String]) a
362 -- mode flags sometimes give rise to new DynFlags (eg. -C, see below)
363 -- so we collect the new ones and return them.
365 mode_flags :: [(String, OptKind (CmdLineP (CmdLineMode, String, [String])))]
367 [ ------- help / version ----------------------------------------------
368 ( "?" , PassFlag (setMode ShowUsage))
369 , ( "-help" , PassFlag (setMode ShowUsage))
370 , ( "-print-libdir" , PassFlag (setMode PrintLibdir))
371 , ( "V" , PassFlag (setMode ShowVersion))
372 , ( "-version" , PassFlag (setMode ShowVersion))
373 , ( "-numeric-version" , PassFlag (setMode ShowNumVersion))
374 , ( "-info" , PassFlag (setMode ShowInfo))
375 , ( "-supported-languages", PassFlag (setMode ShowSupportedLanguages))
377 ------- interfaces ----------------------------------------------------
378 , ( "-show-iface" , HasArg (\f -> setMode (ShowInterface f)
381 ------- primary modes ------------------------------------------------
382 , ( "M" , PassFlag (setMode DoMkDependHS))
383 , ( "E" , PassFlag (setMode (StopBefore anyHsc)))
384 , ( "C" , PassFlag (\f -> do setMode (StopBefore HCc) f
386 , ( "S" , PassFlag (setMode (StopBefore As)))
387 , ( "-make" , PassFlag (setMode DoMake))
388 , ( "-interactive" , PassFlag (setMode DoInteractive))
389 , ( "e" , HasArg (\s -> setMode (DoEval s) "-e"))
391 -- -fno-code says to stop after Hsc but don't generate any code.
392 , ( "fno-code" , PassFlag (\f -> do setMode (StopBefore HCc) f
394 addFlag "-no-recomp"))
397 setMode :: CmdLineMode -> String -> ModeM ()
399 (old_mode, old_flag, flags) <- getCmdLineState
400 when (notNull old_flag && flag /= old_flag) $
402 ("cannot use `" ++ old_flag ++ "' with `" ++ flag ++ "'"))
403 putCmdLineState (m, flag, flags)
405 addFlag :: String -> ModeM ()
407 (m, f, flags) <- getCmdLineState
408 putCmdLineState (m, f, s:flags)
411 -- ----------------------------------------------------------------------------
414 doMake :: Session -> [(String,Maybe Phase)] -> IO ()
415 doMake sess [] = throwDyn (UsageError "no input files")
416 doMake sess srcs = do
417 let (hs_srcs, non_hs_srcs) = partition haskellish srcs
419 haskellish (f,Nothing) =
420 looksLikeModuleName f || isHaskellSrcFilename f || '.' `notElem` f
421 haskellish (f,Just phase) =
422 phase `notElem` [As, Cc, CmmCpp, Cmm, StopLn]
424 dflags <- GHC.getSessionDynFlags sess
425 o_files <- mapM (compileFile dflags StopLn) non_hs_srcs
426 mapM_ (consIORef v_Ld_inputs) (reverse o_files)
428 targets <- mapM (uncurry GHC.guessTarget) hs_srcs
429 GHC.setTargets sess targets
430 ok_flag <- GHC.load sess LoadAllTargets
431 when (failed ok_flag) (exitWith (ExitFailure 1))
435 -- ---------------------------------------------------------------------------
438 doShowIface :: DynFlags -> FilePath -> IO ()
439 doShowIface dflags file = do
440 hsc_env <- newHscEnv dflags
441 showIface hsc_env file
443 -- ---------------------------------------------------------------------------
444 -- Various banners and verbosity output.
446 showBanner :: CmdLineMode -> DynFlags -> IO ()
447 showBanner cli_mode dflags = do
448 let verb = verbosity dflags
451 -- Show the GHCi banner
452 when (isInteractiveMode cli_mode && verb >= 1) $ putStrLn ghciWelcomeMsg
455 -- Display details of the configuration in verbose mode
457 do hPutStr stderr "Glasgow Haskell Compiler, Version "
458 hPutStr stderr cProjectVersion
459 hPutStr stderr ", for Haskell 98, stage "
460 hPutStr stderr cStage
461 hPutStr stderr " booted by GHC version "
462 hPutStrLn stderr cBooterVersion
464 -- We print out a Read-friendly string, but a prettier one than the
465 -- Show instance gives us
468 let sq x = " [" ++ x ++ "\n ]"
469 putStrLn $ sq $ concat $ intersperse "\n ," $ map show compilerInfo
472 showSupportedLanguages :: IO ()
473 showSupportedLanguages = do mapM_ putStrLn supportedLanguages
478 putStrLn (cProjectName ++ ", version " ++ cProjectVersion)
481 showGhcUsage dflags cli_mode = do
483 | DoInteractive <- cli_mode = ghciUsagePath dflags
484 | otherwise = ghcUsagePath dflags
485 usage <- readFile usage_path
490 dump ('$':'$':s) = putStr progName >> dump s
491 dump (c:s) = putChar c >> dump s
493 dumpFinalStats :: DynFlags -> IO ()
494 dumpFinalStats dflags =
495 when (dopt Opt_D_faststring_stats dflags) $ dumpFastStringStats dflags
497 dumpFastStringStats :: DynFlags -> IO ()
498 dumpFastStringStats dflags = do
499 buckets <- getFastStringTable
500 let (entries, longest, is_z, has_z) = countFS 0 0 0 0 buckets
501 msg = text "FastString stats:" $$
502 nest 4 (vcat [text "size: " <+> int (length buckets),
503 text "entries: " <+> int entries,
504 text "longest chain: " <+> int longest,
505 text "z-encoded: " <+> (is_z `pcntOf` entries),
506 text "has z-encoding: " <+> (has_z `pcntOf` entries)
508 -- we usually get more "has z-encoding" than "z-encoded", because
509 -- when we z-encode a string it might hash to the exact same string,
510 -- which will is not counted as "z-encoded". Only strings whose
511 -- Z-encoding is different from the original string are counted in
512 -- the "z-encoded" total.
515 x `pcntOf` y = int ((x * 100) `quot` y) <> char '%'
517 countFS entries longest is_z has_z [] = (entries, longest, is_z, has_z)
518 countFS entries longest is_z has_z (b:bs) =
521 longest' = max len longest
522 entries' = entries + len
523 is_zs = length (filter isZEncoded b)
524 has_zs = length (filter hasZEncoding b)
526 countFS entries' longest' (is_z + is_zs) (has_z + has_zs) bs
528 -- -----------------------------------------------------------------------------
531 unknownFlagsErr :: [String] -> a
532 unknownFlagsErr fs = throwDyn (UsageError ("unrecognised flags: " ++ unwords fs))