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 ShowSupportedLanguages -> do showSupportedLanguages
90 ShowVersion -> do showVersion
92 ShowNumVersion -> do putStrLn cProjectVersion
96 -- start our GHC session
97 session <- GHC.newSession mbMinusB
99 dflags0 <- GHC.getSessionDynFlags session
101 -- set the default GhcMode, HscTarget and GhcLink. The HscTarget
102 -- can be further adjusted on a module by module basis, using only
103 -- the -fvia-C and -fasm flags. If the default HscTarget is not
104 -- HscC or HscAsm, -fvia-C and -fasm have no effect.
105 let dflt_target = hscTarget dflags0
108 DoInteractive -> (CompManager, HscInterpreted, LinkInMemory)
109 DoEval _ -> (CompManager, HscInterpreted, LinkInMemory)
110 DoMake -> (CompManager, dflt_target, LinkBinary)
111 DoMkDependHS -> (MkDepend, dflt_target, LinkBinary)
112 _ -> (OneShot, dflt_target, LinkBinary)
114 let dflags1 = dflags0{ ghcMode = mode,
117 -- leave out hscOutName for now
118 hscOutName = panic "Main.main:hscOutName not set",
119 verbosity = case cli_mode of
124 -- The rest of the arguments are "dynamic"
125 -- Leftover ones are presumably files
126 (dflags, fileish_args) <- GHC.parseDynamicFlags dflags1 argv3
128 -- make sure we clean up after ourselves
129 GHC.defaultCleanupHandler dflags $ do
131 showBanner cli_mode dflags
133 -- we've finished manipulating the DynFlags, update the session
134 GHC.setSessionDynFlags session dflags
135 dflags <- GHC.getSessionDynFlags session
138 -- To simplify the handling of filepaths, we normalise all filepaths right
139 -- away - e.g., for win32 platforms, backslashes are converted
140 -- into forward slashes.
141 normal_fileish_paths = map normalisePath fileish_args
142 (srcs, objs) = partition_args normal_fileish_paths [] []
144 -- Note: have v_Ld_inputs maintain the order in which 'objs' occurred on
146 mapM_ (consIORef v_Ld_inputs) (reverse objs)
148 ---------------- Display configuration -----------
149 when (verbosity dflags >= 4) $
152 when (verbosity dflags >= 3) $ do
153 hPutStrLn stderr ("Hsc static flags: " ++ unwords staticFlags)
155 ---------------- Final sanity checking -----------
156 checkOptions cli_mode dflags srcs objs
158 ---------------- Do the business -----------
159 let alreadyHandled = panic (show cli_mode ++
160 " should already have been handled")
162 ShowUsage -> showGhcUsage dflags cli_mode
163 PrintLibdir -> putStrLn (topDir dflags)
164 ShowSupportedLanguages -> alreadyHandled
165 ShowVersion -> alreadyHandled
166 ShowNumVersion -> alreadyHandled
167 ShowInterface f -> doShowIface dflags f
168 DoMake -> doMake session srcs
169 DoMkDependHS -> doMkDependHS session (map fst srcs)
170 StopBefore p -> oneShot dflags p srcs
171 DoInteractive -> interactiveUI session srcs Nothing
172 DoEval expr -> interactiveUI session srcs (Just expr)
174 dumpFinalStats dflags
178 interactiveUI _ _ _ =
179 throwDyn (CmdLineError "not built for interactive use")
182 -- -----------------------------------------------------------------------------
183 -- Splitting arguments into source files and object files. This is where we
184 -- interpret the -x <suffix> option, and attach a (Maybe Phase) to each source
185 -- file indicating the phase specified by the -x option in force, if any.
187 partition_args [] srcs objs = (reverse srcs, reverse objs)
188 partition_args ("-x":suff:args) srcs objs
189 | "none" <- suff = partition_args args srcs objs
190 | StopLn <- phase = partition_args args srcs (slurp ++ objs)
191 | otherwise = partition_args rest (these_srcs ++ srcs) objs
192 where phase = startPhase suff
193 (slurp,rest) = break (== "-x") args
194 these_srcs = zip slurp (repeat (Just phase))
195 partition_args (arg:args) srcs objs
196 | looks_like_an_input arg = partition_args args ((arg,Nothing):srcs) objs
197 | otherwise = partition_args args srcs (arg:objs)
200 We split out the object files (.o, .dll) and add them
201 to v_Ld_inputs for use by the linker.
203 The following things should be considered compilation manager inputs:
205 - haskell source files (strings ending in .hs, .lhs or other
206 haskellish extension),
208 - module names (not forgetting hierarchical module names),
210 - and finally we consider everything not containing a '.' to be
211 a comp manager input, as shorthand for a .hs or .lhs filename.
213 Everything else is considered to be a linker object, and passed
214 straight through to the linker.
216 looks_like_an_input m = isSourceFilename m
217 || looksLikeModuleName m
220 -- -----------------------------------------------------------------------------
221 -- Option sanity checks
223 checkOptions :: CmdLineMode -> DynFlags -> [(String,Maybe Phase)] -> [String] -> IO ()
224 -- Final sanity checking before kicking off a compilation (pipeline).
225 checkOptions cli_mode dflags srcs objs = do
226 -- Complain about any unknown flags
227 let unknown_opts = [ f | (f@('-':_), _) <- srcs ]
228 when (notNull unknown_opts) (unknownFlagsErr unknown_opts)
230 when (notNull (filter isRTSWay (wayNames dflags))
231 && isInterpretiveMode cli_mode) $
232 putStrLn ("Warning: -debug, -threaded and -ticky are ignored by GHCi")
234 -- -prof and --interactive are not a good combination
235 when (notNull (filter (not . isRTSWay) (wayNames dflags))
236 && isInterpretiveMode cli_mode) $
237 do throwDyn (UsageError
238 "--interactive can't be used with -prof or -unreg.")
240 if (isJust (outputHi dflags) &&
241 (isCompManagerMode cli_mode || srcs `lengthExceeds` 1))
242 then throwDyn (UsageError "-ohi can only be used when compiling a single source file")
245 -- -o sanity checking
246 if (srcs `lengthExceeds` 1 && isJust (outputFile dflags)
247 && not (isLinkMode cli_mode))
248 then throwDyn (UsageError "can't apply -o to multiple source files")
251 -- Check that there are some input files
252 -- (except in the interactive case)
253 if null srcs && null objs && needsInputsMode cli_mode
254 then throwDyn (UsageError "no input files")
257 -- Verify that output files point somewhere sensible.
258 verifyOutputFiles dflags
261 -- Compiler output options
263 -- called to verify that the output files & directories
264 -- point somewhere valid.
266 -- The assumption is that the directory portion of these output
267 -- options will have to exist by the time 'verifyOutputFiles'
270 verifyOutputFiles :: DynFlags -> IO ()
271 verifyOutputFiles dflags = do
272 let odir = objectDir dflags
273 when (isJust odir) $ do
274 let dir = fromJust odir
275 flg <- doesDirectoryExist dir
276 when (not flg) (nonExistentDir "-odir" dir)
277 let ofile = outputFile dflags
278 when (isJust ofile) $ do
279 let fn = fromJust ofile
280 flg <- doesDirNameExist fn
281 when (not flg) (nonExistentDir "-o" fn)
282 let ohi = outputHi dflags
283 when (isJust ohi) $ do
284 let hi = fromJust ohi
285 flg <- doesDirNameExist hi
286 when (not flg) (nonExistentDir "-ohi" hi)
288 nonExistentDir flg dir =
289 throwDyn (CmdLineError ("error: directory portion of " ++
290 show dir ++ " does not exist (used with " ++
291 show flg ++ " option.)"))
293 -----------------------------------------------------------------------------
294 -- GHC modes of operation
297 = ShowUsage -- ghc -?
298 | PrintLibdir -- ghc --print-libdir
299 | ShowSupportedLanguages -- ghc --supported-languages
300 | ShowVersion -- ghc -V/--version
301 | ShowNumVersion -- ghc --numeric-version
302 | ShowInterface String -- ghc --show-iface
303 | DoMkDependHS -- ghc -M
304 | StopBefore Phase -- ghc -E | -C | -S
305 -- StopBefore StopLn is the default
306 | DoMake -- ghc --make
307 | DoInteractive -- ghc --interactive
308 | DoEval String -- ghc -e
311 isInteractiveMode, isInterpretiveMode :: CmdLineMode -> Bool
312 isLinkMode, isCompManagerMode :: CmdLineMode -> Bool
314 isInteractiveMode DoInteractive = True
315 isInteractiveMode _ = False
317 -- isInterpretiveMode: byte-code compiler involved
318 isInterpretiveMode DoInteractive = True
319 isInterpretiveMode (DoEval _) = True
320 isInterpretiveMode _ = False
322 needsInputsMode DoMkDependHS = True
323 needsInputsMode (StopBefore _) = True
324 needsInputsMode DoMake = True
325 needsInputsMode _ = False
327 -- True if we are going to attempt to link in this mode.
328 -- (we might not actually link, depending on the GhcLink flag)
329 isLinkMode (StopBefore StopLn) = True
330 isLinkMode DoMake = True
333 isCompManagerMode DoMake = True
334 isCompManagerMode DoInteractive = True
335 isCompManagerMode (DoEval _) = True
336 isCompManagerMode _ = False
339 -- -----------------------------------------------------------------------------
340 -- Parsing the mode flag
342 parseModeFlags :: [String] -> IO (CmdLineMode, [String])
343 parseModeFlags args = do
344 let ((leftover, errs), (mode, _, flags)) =
345 runCmdLine (processArgs mode_flags args) (StopBefore StopLn, "", [])
346 when (not (null errs)) $ do
347 throwDyn (UsageError (unlines errs))
348 return (mode, flags ++ leftover)
350 type ModeM a = CmdLineP (CmdLineMode, String, [String]) a
351 -- mode flags sometimes give rise to new DynFlags (eg. -C, see below)
352 -- so we collect the new ones and return them.
354 mode_flags :: [(String, OptKind (CmdLineP (CmdLineMode, String, [String])))]
356 [ ------- help / version ----------------------------------------------
357 ( "?" , PassFlag (setMode ShowUsage))
358 , ( "-help" , PassFlag (setMode ShowUsage))
359 , ( "-print-libdir" , PassFlag (setMode PrintLibdir))
360 , ( "V" , PassFlag (setMode ShowVersion))
361 , ( "-version" , PassFlag (setMode ShowVersion))
362 , ( "-numeric-version", PassFlag (setMode ShowNumVersion))
363 , ( "-supported-languages", PassFlag (setMode ShowSupportedLanguages))
365 ------- interfaces ----------------------------------------------------
366 , ( "-show-iface" , HasArg (\f -> setMode (ShowInterface f)
369 ------- primary modes ------------------------------------------------
370 , ( "M" , PassFlag (setMode DoMkDependHS))
371 , ( "E" , PassFlag (setMode (StopBefore anyHsc)))
372 , ( "C" , PassFlag (\f -> do setMode (StopBefore HCc) f
374 , ( "S" , PassFlag (setMode (StopBefore As)))
375 , ( "-make" , PassFlag (setMode DoMake))
376 , ( "-interactive" , PassFlag (setMode DoInteractive))
377 , ( "e" , HasArg (\s -> setMode (DoEval s) "-e"))
379 -- -fno-code says to stop after Hsc but don't generate any code.
380 , ( "fno-code" , PassFlag (\f -> do setMode (StopBefore HCc) f
382 addFlag "-no-recomp"))
385 setMode :: CmdLineMode -> String -> ModeM ()
387 (old_mode, old_flag, flags) <- getCmdLineState
388 when (notNull old_flag && flag /= old_flag) $
390 ("cannot use `" ++ old_flag ++ "' with `" ++ flag ++ "'"))
391 putCmdLineState (m, flag, flags)
393 addFlag :: String -> ModeM ()
395 (m, f, flags) <- getCmdLineState
396 putCmdLineState (m, f, s:flags)
399 -- ----------------------------------------------------------------------------
402 doMake :: Session -> [(String,Maybe Phase)] -> IO ()
403 doMake sess [] = throwDyn (UsageError "no input files")
404 doMake sess srcs = do
405 let (hs_srcs, non_hs_srcs) = partition haskellish srcs
407 haskellish (f,Nothing) =
408 looksLikeModuleName f || isHaskellSrcFilename f || '.' `notElem` f
409 haskellish (f,Just phase) =
410 phase `notElem` [As, Cc, CmmCpp, Cmm, StopLn]
412 dflags <- GHC.getSessionDynFlags sess
413 o_files <- mapM (compileFile dflags StopLn) non_hs_srcs
414 mapM_ (consIORef v_Ld_inputs) (reverse o_files)
416 targets <- mapM (uncurry GHC.guessTarget) hs_srcs
417 GHC.setTargets sess targets
418 ok_flag <- GHC.load sess LoadAllTargets
419 when (failed ok_flag) (exitWith (ExitFailure 1))
423 -- ---------------------------------------------------------------------------
426 doShowIface :: DynFlags -> FilePath -> IO ()
427 doShowIface dflags file = do
428 hsc_env <- newHscEnv dflags
429 showIface hsc_env file
431 -- ---------------------------------------------------------------------------
432 -- Various banners and verbosity output.
434 showBanner :: CmdLineMode -> DynFlags -> IO ()
435 showBanner cli_mode dflags = do
436 let verb = verbosity dflags
439 -- Show the GHCi banner
440 when (isInteractiveMode cli_mode && verb >= 1) $ putStrLn ghciWelcomeMsg
443 -- Display details of the configuration in verbose mode
445 do hPutStr stderr "Glasgow Haskell Compiler, Version "
446 hPutStr stderr cProjectVersion
447 hPutStr stderr ", for Haskell 98, stage "
448 hPutStr stderr cStage
449 hPutStr stderr " booted by GHC version "
450 hPutStrLn stderr cBooterVersion
452 showSupportedLanguages :: IO ()
453 showSupportedLanguages = do mapM_ putStrLn supportedLanguages
458 putStrLn (cProjectName ++ ", version " ++ cProjectVersion)
461 showGhcUsage dflags cli_mode = do
463 | DoInteractive <- cli_mode = ghciUsagePath dflags
464 | otherwise = ghcUsagePath dflags
465 usage <- readFile usage_path
470 dump ('$':'$':s) = putStr progName >> dump s
471 dump (c:s) = putChar c >> dump s
473 dumpFinalStats :: DynFlags -> IO ()
474 dumpFinalStats dflags =
475 when (dopt Opt_D_faststring_stats dflags) $ dumpFastStringStats dflags
477 dumpFastStringStats :: DynFlags -> IO ()
478 dumpFastStringStats dflags = do
479 buckets <- getFastStringTable
480 let (entries, longest, is_z, has_z) = countFS 0 0 0 0 buckets
481 msg = text "FastString stats:" $$
482 nest 4 (vcat [text "size: " <+> int (length buckets),
483 text "entries: " <+> int entries,
484 text "longest chain: " <+> int longest,
485 text "z-encoded: " <+> (is_z `pcntOf` entries),
486 text "has z-encoding: " <+> (has_z `pcntOf` entries)
488 -- we usually get more "has z-encoding" than "z-encoded", because
489 -- when we z-encode a string it might hash to the exact same string,
490 -- which will is not counted as "z-encoded". Only strings whose
491 -- Z-encoding is different from the original string are counted in
492 -- the "z-encoded" total.
495 x `pcntOf` y = int ((x * 100) `quot` y) <> char '%'
497 countFS entries longest is_z has_z [] = (entries, longest, is_z, has_z)
498 countFS entries longest is_z has_z (b:bs) =
501 longest' = max len longest
502 entries' = entries + len
503 is_zs = length (filter isZEncoded b)
504 has_zs = length (filter hasZEncoding b)
506 countFS entries' longest' (is_z + is_zs) (has_z + has_zs) bs
508 -- -----------------------------------------------------------------------------
511 unknownFlagsErr :: [String] -> a
512 unknownFlagsErr fs = throwDyn (UsageError ("unrecognised flags: " ++ unwords fs))