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(..), GhcMode(..), HscTarget(..),
17 LoadHowMuch(..), dopt, DynFlag(..) )
20 -- Implementations of the various modes (--show-iface, mkdependHS. etc.)
21 import LoadIface ( showIface )
22 import HscMain ( newHscEnv )
23 import DriverPipeline ( oneShot, compileFile )
24 import DriverMkDepend ( doMkDependHS )
26 import InteractiveUI ( ghciWelcomeMsg, interactiveUI )
29 -- Various other random stuff that we need
30 import Config ( cProjectVersion, cBooterVersion, cProjectName )
31 import Packages ( dumpPackages )
32 import DriverPhases ( Phase(..), isSourceFilename, anyHsc,
33 startPhase, isHaskellSrcFilename )
35 import DynFlags ( defaultDynFlags )
36 import BasicTypes ( failed )
37 import ErrUtils ( putMsg )
38 import FastString ( getFastStringTable, isZEncoded, hasZEncoding )
43 -- Standard Haskell libraries
44 import Control.Exception ( throwDyn )
46 import System.Directory ( doesDirectoryExist )
47 import System.Environment
53 -----------------------------------------------------------------------------
56 -- time commands when run with -v
58 -- Win32 support: proper signal handling
59 -- reading the package configuration file is too slow
62 -----------------------------------------------------------------------------
63 -- GHC's command-line interface
66 GHC.defaultErrorHandler defaultDynFlags $ do
68 -- 1. extract the -B flag from the args
72 (minusB_args, argv1) = partition (prefixMatch "-B") argv0
73 mbMinusB | null minusB_args = Nothing
74 | otherwise = Just (drop 2 (last minusB_args))
76 argv2 <- parseStaticFlags argv1
78 -- 2. Parse the "mode" flags (--make, --interactive etc.)
79 (cli_mode, argv3) <- parseModeFlags argv2
81 let mode = case cli_mode of
82 DoInteractive -> Interactive
83 DoEval _ -> Interactive
84 DoMake -> BatchCompile
85 DoMkDependHS -> MkDepend
88 -- start our GHC session
89 session <- GHC.newSession mode mbMinusB
91 dflags0 <- GHC.getSessionDynFlags session
93 -- set the default HscTarget. The HscTarget can be further
94 -- adjusted on a module by module basis, using only the -fvia-C and
95 -- -fasm flags. If the default HscTarget is not HscC or HscAsm,
96 -- -fvia-C and -fasm have no effect.
97 let lang = case cli_mode of
98 DoInteractive -> HscInterpreted
99 DoEval _ -> HscInterpreted
100 _other -> hscTarget dflags0
102 let dflags1 = dflags0{ ghcMode = mode,
104 -- leave out hscOutName for now
105 hscOutName = panic "Main.main:hscOutName not set",
106 verbosity = case cli_mode of
111 -- The rest of the arguments are "dynamic"
112 -- Leftover ones are presumably files
113 (dflags, fileish_args) <- GHC.parseDynamicFlags dflags1 argv3
115 -- make sure we clean up after ourselves
116 GHC.defaultCleanupHandler dflags $ do
119 showBanner cli_mode dflags
121 -- we've finished manipulating the DynFlags, update the session
122 GHC.setSessionDynFlags session dflags
123 dflags <- GHC.getSessionDynFlags session
126 -- To simplify the handling of filepaths, we normalise all filepaths right
127 -- away - e.g., for win32 platforms, backslashes are converted
128 -- into forward slashes.
129 normal_fileish_paths = map normalisePath fileish_args
130 (srcs, objs) = partition_args normal_fileish_paths [] []
132 -- Note: have v_Ld_inputs maintain the order in which 'objs' occurred on
134 mapM_ (consIORef v_Ld_inputs) (reverse objs)
136 ---------------- Display configuration -----------
137 when (verbosity dflags >= 4) $
140 when (verbosity dflags >= 3) $ do
141 hPutStrLn stderr ("Hsc static flags: " ++ unwords staticFlags)
143 ---------------- Final sanity checking -----------
144 checkOptions cli_mode dflags srcs objs
146 ---------------- Do the business -----------
148 ShowUsage -> showGhcUsage dflags cli_mode
149 PrintLibdir -> putStrLn (topDir dflags)
150 ShowVersion -> showVersion
151 ShowNumVersion -> putStrLn cProjectVersion
152 ShowInterface f -> doShowIface dflags f
153 DoMake -> doMake session srcs
154 DoMkDependHS -> doMkDependHS session (map fst srcs)
155 StopBefore p -> oneShot dflags p srcs
156 DoInteractive -> interactiveUI session srcs Nothing
157 DoEval expr -> interactiveUI session srcs (Just expr)
159 dumpFinalStats dflags
163 interactiveUI _ _ _ =
164 throwDyn (CmdLineError "not built for interactive use")
167 -- -----------------------------------------------------------------------------
168 -- Splitting arguments into source files and object files. This is where we
169 -- interpret the -x <suffix> option, and attach a (Maybe Phase) to each source
170 -- file indicating the phase specified by the -x option in force, if any.
172 partition_args [] srcs objs = (reverse srcs, reverse objs)
173 partition_args ("-x":suff:args) srcs objs
174 | "none" <- suff = partition_args args srcs objs
175 | StopLn <- phase = partition_args args srcs (slurp ++ objs)
176 | otherwise = partition_args rest (these_srcs ++ srcs) objs
177 where phase = startPhase suff
178 (slurp,rest) = break (== "-x") args
179 these_srcs = zip slurp (repeat (Just phase))
180 partition_args (arg:args) srcs objs
181 | looks_like_an_input arg = partition_args args ((arg,Nothing):srcs) objs
182 | otherwise = partition_args args srcs (arg:objs)
185 We split out the object files (.o, .dll) and add them
186 to v_Ld_inputs for use by the linker.
188 The following things should be considered compilation manager inputs:
190 - haskell source files (strings ending in .hs, .lhs or other
191 haskellish extension),
193 - module names (not forgetting hierarchical module names),
195 - and finally we consider everything not containing a '.' to be
196 a comp manager input, as shorthand for a .hs or .lhs filename.
198 Everything else is considered to be a linker object, and passed
199 straight through to the linker.
201 looks_like_an_input m = isSourceFilename m
202 || looksLikeModuleName m
205 -- -----------------------------------------------------------------------------
206 -- Option sanity checks
208 checkOptions :: CmdLineMode -> DynFlags -> [(String,Maybe Phase)] -> [String] -> IO ()
209 -- Final sanity checking before kicking off a compilation (pipeline).
210 checkOptions cli_mode dflags srcs objs = do
211 -- Complain about any unknown flags
212 let unknown_opts = [ f | (f@('-':_), _) <- srcs ]
213 when (notNull unknown_opts) (unknownFlagsErr unknown_opts)
215 -- -prof and --interactive are not a good combination
216 when (notNull (filter (/= WayThreaded) (wayNames dflags))
217 && isInterpretiveMode cli_mode) $
218 do throwDyn (UsageError
219 "--interactive can't be used with -prof, -ticky, or -unreg.")
221 if (isJust (outputHi dflags) &&
222 (isCompManagerMode cli_mode || srcs `lengthExceeds` 1))
223 then throwDyn (UsageError "-ohi can only be used when compiling a single source file")
226 -- -o sanity checking
227 if (srcs `lengthExceeds` 1 && isJust (outputFile dflags)
228 && not (isLinkMode cli_mode))
229 then throwDyn (UsageError "can't apply -o to multiple source files")
232 -- Check that there are some input files
233 -- (except in the interactive case)
234 if null srcs && null objs && needsInputsMode cli_mode
235 then throwDyn (UsageError "no input files")
238 -- Verify that output files point somewhere sensible.
239 verifyOutputFiles dflags
242 -- Compiler output options
244 -- called to verify that the output files & directories
245 -- point somewhere valid.
247 -- The assumption is that the directory portion of these output
248 -- options will have to exist by the time 'verifyOutputFiles'
251 verifyOutputFiles :: DynFlags -> IO ()
252 verifyOutputFiles dflags = do
253 let odir = objectDir dflags
254 when (isJust odir) $ do
255 let dir = fromJust odir
256 flg <- doesDirectoryExist dir
257 when (not flg) (nonExistentDir "-odir" dir)
258 let ofile = outputFile dflags
259 when (isJust ofile) $ do
260 let fn = fromJust ofile
261 flg <- doesDirNameExist fn
262 when (not flg) (nonExistentDir "-o" fn)
263 let ohi = outputHi dflags
264 when (isJust ohi) $ do
265 let hi = fromJust ohi
266 flg <- doesDirNameExist hi
267 when (not flg) (nonExistentDir "-ohi" hi)
269 nonExistentDir flg dir =
270 throwDyn (CmdLineError ("error: directory portion of " ++
271 show dir ++ " does not exist (used with " ++
272 show flg ++ " option.)"))
274 -----------------------------------------------------------------------------
275 -- GHC modes of operation
278 = ShowUsage -- ghc -?
279 | PrintLibdir -- ghc --print-libdir
280 | ShowVersion -- ghc -V/--version
281 | ShowNumVersion -- ghc --numeric-version
282 | ShowInterface String -- ghc --show-iface
283 | DoMkDependHS -- ghc -M
284 | StopBefore Phase -- ghc -E | -C | -S
285 -- StopBefore StopLn is the default
286 | DoMake -- ghc --make
287 | DoInteractive -- ghc --interactive
288 | DoEval String -- ghc -e
291 isInteractiveMode, isInterpretiveMode :: CmdLineMode -> Bool
292 isLinkMode, isCompManagerMode :: CmdLineMode -> Bool
294 isInteractiveMode DoInteractive = True
295 isInteractiveMode _ = False
297 -- isInterpretiveMode: byte-code compiler involved
298 isInterpretiveMode DoInteractive = True
299 isInterpretiveMode (DoEval _) = True
300 isInterpretiveMode _ = False
302 needsInputsMode DoMkDependHS = True
303 needsInputsMode (StopBefore _) = True
304 needsInputsMode DoMake = True
305 needsInputsMode _ = False
307 -- True if we are going to attempt to link in this mode.
308 -- (we might not actually link, depending on the GhcLink flag)
309 isLinkMode (StopBefore StopLn) = True
310 isLinkMode DoMake = True
313 isCompManagerMode DoMake = True
314 isCompManagerMode DoInteractive = True
315 isCompManagerMode (DoEval _) = True
316 isCompManagerMode _ = False
319 -- -----------------------------------------------------------------------------
320 -- Parsing the mode flag
322 parseModeFlags :: [String] -> IO (CmdLineMode, [String])
323 parseModeFlags args = do
324 let ((leftover, errs), (mode, _, flags)) =
325 runCmdLine (processArgs mode_flags args) (StopBefore StopLn, "", [])
326 when (not (null errs)) $ do
327 throwDyn (UsageError (unlines errs))
328 return (mode, flags ++ leftover)
330 type ModeM a = CmdLineP (CmdLineMode, String, [String]) a
331 -- mode flags sometimes give rise to new DynFlags (eg. -C, see below)
332 -- so we collect the new ones and return them.
334 mode_flags :: [(String, OptKind (CmdLineP (CmdLineMode, String, [String])))]
336 [ ------- help / version ----------------------------------------------
337 ( "?" , PassFlag (setMode ShowUsage))
338 , ( "-help" , PassFlag (setMode ShowUsage))
339 , ( "-print-libdir" , PassFlag (setMode PrintLibdir))
340 , ( "V" , PassFlag (setMode ShowVersion))
341 , ( "-version" , PassFlag (setMode ShowVersion))
342 , ( "-numeric-version", PassFlag (setMode ShowNumVersion))
344 ------- interfaces ----------------------------------------------------
345 , ( "-show-iface" , HasArg (\f -> setMode (ShowInterface f)
348 ------- primary modes ------------------------------------------------
349 , ( "M" , PassFlag (setMode DoMkDependHS))
350 , ( "E" , PassFlag (setMode (StopBefore anyHsc)))
351 , ( "C" , PassFlag (\f -> do setMode (StopBefore HCc) f
353 , ( "S" , PassFlag (setMode (StopBefore As)))
354 , ( "-make" , PassFlag (setMode DoMake))
355 , ( "-interactive" , PassFlag (setMode DoInteractive))
356 , ( "e" , HasArg (\s -> setMode (DoEval s) "-e"))
358 -- -fno-code says to stop after Hsc but don't generate any code.
359 , ( "fno-code" , PassFlag (\f -> do setMode (StopBefore HCc) f
361 addFlag "-no-recomp"))
364 setMode :: CmdLineMode -> String -> ModeM ()
366 (old_mode, old_flag, flags) <- getCmdLineState
367 when (notNull old_flag && flag /= old_flag) $
369 ("cannot use `" ++ old_flag ++ "' with `" ++ flag ++ "'"))
370 putCmdLineState (m, flag, flags)
372 addFlag :: String -> ModeM ()
374 (m, f, flags) <- getCmdLineState
375 putCmdLineState (m, f, s:flags)
378 -- ----------------------------------------------------------------------------
381 doMake :: Session -> [(String,Maybe Phase)] -> IO ()
382 doMake sess [] = throwDyn (UsageError "no input files")
383 doMake sess srcs = do
384 let (hs_srcs, non_hs_srcs) = partition haskellish srcs
386 haskellish (f,Nothing) =
387 looksLikeModuleName f || isHaskellSrcFilename f || '.' `notElem` f
388 haskellish (f,Just phase) =
389 phase `notElem` [As, Cc, CmmCpp, Cmm, StopLn]
391 dflags <- GHC.getSessionDynFlags sess
392 o_files <- mapM (compileFile dflags StopLn) non_hs_srcs
393 mapM_ (consIORef v_Ld_inputs) (reverse o_files)
395 targets <- mapM (uncurry GHC.guessTarget) hs_srcs
396 GHC.setTargets sess targets
397 ok_flag <- GHC.load sess LoadAllTargets
398 when (failed ok_flag) (exitWith (ExitFailure 1))
402 -- ---------------------------------------------------------------------------
405 doShowIface :: DynFlags -> FilePath -> IO ()
406 doShowIface dflags file = do
407 hsc_env <- newHscEnv dflags
408 showIface hsc_env file
410 -- ---------------------------------------------------------------------------
411 -- Various banners and verbosity output.
413 showBanner :: CmdLineMode -> DynFlags -> IO ()
414 showBanner cli_mode dflags = do
415 let verb = verbosity dflags
416 -- Show the GHCi banner
418 when (isInteractiveMode cli_mode && verb >= 1) $
419 hPutStrLn stdout ghciWelcomeMsg
422 -- Display details of the configuration in verbose mode
423 when (not (isInteractiveMode cli_mode) && verb >= 2) $
424 do hPutStr stderr "Glasgow Haskell Compiler, Version "
425 hPutStr stderr cProjectVersion
426 hPutStr stderr ", for Haskell 98, compiled by GHC version "
428 -- GHCI is only set when we are bootstrapping...
429 hPutStrLn stderr cProjectVersion
431 hPutStrLn stderr cBooterVersion
436 putStrLn (cProjectName ++ ", version " ++ cProjectVersion)
439 showGhcUsage dflags cli_mode = do
441 | DoInteractive <- cli_mode = ghcUsagePath dflags
442 | otherwise = ghciUsagePath dflags
443 usage <- readFile usage_path
448 dump ('$':'$':s) = putStr progName >> dump s
449 dump (c:s) = putChar c >> dump s
451 dumpFinalStats :: DynFlags -> IO ()
452 dumpFinalStats dflags =
453 when (dopt Opt_D_faststring_stats dflags) $ dumpFastStringStats dflags
455 dumpFastStringStats :: DynFlags -> IO ()
456 dumpFastStringStats dflags = do
457 buckets <- getFastStringTable
458 let (entries, longest, is_z, has_z) = countFS 0 0 0 0 buckets
459 msg = text "FastString stats:" $$
460 nest 4 (vcat [text "size: " <+> int (length buckets),
461 text "entries: " <+> int entries,
462 text "longest chain: " <+> int longest,
463 text "z-encoded: " <+> (is_z `pcntOf` entries),
464 text "has z-encoding: " <+> (has_z `pcntOf` entries)
466 -- we usually get more "has z-encoding" than "z-encoded", because
467 -- when we z-encode a string it might hash to the exact same string,
468 -- which will is not counted as "z-encoded". Only strings whose
469 -- Z-encoding is different from the original string are counted in
470 -- the "z-encoded" total.
473 x `pcntOf` y = int ((x * 100) `quot` y) <> char '%'
475 countFS entries longest is_z has_z [] = (entries, longest, is_z, has_z)
476 countFS entries longest is_z has_z (b:bs) =
479 longest' = max len longest
480 entries' = entries + len
481 is_zs = length (filter isZEncoded b)
482 has_zs = length (filter hasZEncoding b)
484 countFS entries' longest' (is_z + is_zs) (has_z + has_zs) bs
486 -- -----------------------------------------------------------------------------
489 unknownFlagsErr :: [String] -> a
490 unknownFlagsErr fs = throwDyn (UsageError ("unrecognised flags: " ++ unwords fs))