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 )
36 import DynFlags ( defaultDynFlags )
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 (prefixMatch "-B") 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 ShowVersion -> do showVersion
90 ShowNumVersion -> do putStrLn cProjectVersion
94 -- start our GHC session
95 session <- GHC.newSession mbMinusB
97 dflags0 <- GHC.getSessionDynFlags session
99 -- set the default GhcMode, HscTarget and GhcLink. The HscTarget
100 -- can be further adjusted on a module by module basis, using only
101 -- the -fvia-C and -fasm flags. If the default HscTarget is not
102 -- HscC or HscAsm, -fvia-C and -fasm have no effect.
103 let dflt_target = hscTarget dflags0
106 DoInteractive -> (CompManager, HscInterpreted, LinkInMemory)
107 DoEval _ -> (CompManager, HscInterpreted, LinkInMemory)
108 DoMake -> (CompManager, dflt_target, LinkBinary)
109 DoMkDependHS -> (MkDepend, dflt_target, LinkBinary)
110 _ -> (OneShot, dflt_target, LinkBinary)
112 let dflags1 = dflags0{ ghcMode = mode,
115 -- leave out hscOutName for now
116 hscOutName = panic "Main.main:hscOutName not set",
117 verbosity = case cli_mode of
122 -- The rest of the arguments are "dynamic"
123 -- Leftover ones are presumably files
124 (dflags, fileish_args) <- GHC.parseDynamicFlags dflags1 argv3
126 -- make sure we clean up after ourselves
127 GHC.defaultCleanupHandler dflags $ do
129 showBanner cli_mode dflags
131 -- we've finished manipulating the DynFlags, update the session
132 GHC.setSessionDynFlags session dflags
133 dflags <- GHC.getSessionDynFlags session
136 -- To simplify the handling of filepaths, we normalise all filepaths right
137 -- away - e.g., for win32 platforms, backslashes are converted
138 -- into forward slashes.
139 normal_fileish_paths = map normalisePath fileish_args
140 (srcs, objs) = partition_args normal_fileish_paths [] []
142 -- Note: have v_Ld_inputs maintain the order in which 'objs' occurred on
144 mapM_ (consIORef v_Ld_inputs) (reverse objs)
146 ---------------- Display configuration -----------
147 when (verbosity dflags >= 4) $
150 when (verbosity dflags >= 3) $ do
151 hPutStrLn stderr ("Hsc static flags: " ++ unwords staticFlags)
153 ---------------- Final sanity checking -----------
154 checkOptions cli_mode dflags srcs objs
156 ---------------- Do the business -----------
158 ShowUsage -> showGhcUsage dflags cli_mode
159 PrintLibdir -> putStrLn (topDir dflags)
160 ShowVersion -> panic "ShowVersion should already have been handled"
161 ShowNumVersion -> panic "ShowNumVersion should already have been handled"
162 ShowInterface f -> doShowIface dflags f
163 DoMake -> doMake session srcs
164 DoMkDependHS -> doMkDependHS session (map fst srcs)
165 StopBefore p -> oneShot dflags p srcs
166 DoInteractive -> interactiveUI session srcs Nothing
167 DoEval expr -> interactiveUI session srcs (Just expr)
169 dumpFinalStats dflags
173 interactiveUI _ _ _ =
174 throwDyn (CmdLineError "not built for interactive use")
177 -- -----------------------------------------------------------------------------
178 -- Splitting arguments into source files and object files. This is where we
179 -- interpret the -x <suffix> option, and attach a (Maybe Phase) to each source
180 -- file indicating the phase specified by the -x option in force, if any.
182 partition_args [] srcs objs = (reverse srcs, reverse objs)
183 partition_args ("-x":suff:args) srcs objs
184 | "none" <- suff = partition_args args srcs objs
185 | StopLn <- phase = partition_args args srcs (slurp ++ objs)
186 | otherwise = partition_args rest (these_srcs ++ srcs) objs
187 where phase = startPhase suff
188 (slurp,rest) = break (== "-x") args
189 these_srcs = zip slurp (repeat (Just phase))
190 partition_args (arg:args) srcs objs
191 | looks_like_an_input arg = partition_args args ((arg,Nothing):srcs) objs
192 | otherwise = partition_args args srcs (arg:objs)
195 We split out the object files (.o, .dll) and add them
196 to v_Ld_inputs for use by the linker.
198 The following things should be considered compilation manager inputs:
200 - haskell source files (strings ending in .hs, .lhs or other
201 haskellish extension),
203 - module names (not forgetting hierarchical module names),
205 - and finally we consider everything not containing a '.' to be
206 a comp manager input, as shorthand for a .hs or .lhs filename.
208 Everything else is considered to be a linker object, and passed
209 straight through to the linker.
211 looks_like_an_input m = isSourceFilename m
212 || looksLikeModuleName m
215 -- -----------------------------------------------------------------------------
216 -- Option sanity checks
218 checkOptions :: CmdLineMode -> DynFlags -> [(String,Maybe Phase)] -> [String] -> IO ()
219 -- Final sanity checking before kicking off a compilation (pipeline).
220 checkOptions cli_mode dflags srcs objs = do
221 -- Complain about any unknown flags
222 let unknown_opts = [ f | (f@('-':_), _) <- srcs ]
223 when (notNull unknown_opts) (unknownFlagsErr unknown_opts)
225 when (notNull (filter isRTSWay (wayNames dflags))
226 && isInterpretiveMode cli_mode) $
227 putStrLn ("Warning: -debug, -threaded and -ticky are ignored by GHCi")
229 -- -prof and --interactive are not a good combination
230 when (notNull (filter (not . isRTSWay) (wayNames dflags))
231 && isInterpretiveMode cli_mode) $
232 do throwDyn (UsageError
233 "--interactive can't be used with -prof or -unreg.")
235 if (isJust (outputHi dflags) &&
236 (isCompManagerMode cli_mode || srcs `lengthExceeds` 1))
237 then throwDyn (UsageError "-ohi can only be used when compiling a single source file")
240 -- -o sanity checking
241 if (srcs `lengthExceeds` 1 && isJust (outputFile dflags)
242 && not (isLinkMode cli_mode))
243 then throwDyn (UsageError "can't apply -o to multiple source files")
246 -- Check that there are some input files
247 -- (except in the interactive case)
248 if null srcs && null objs && needsInputsMode cli_mode
249 then throwDyn (UsageError "no input files")
252 -- Verify that output files point somewhere sensible.
253 verifyOutputFiles dflags
256 -- Compiler output options
258 -- called to verify that the output files & directories
259 -- point somewhere valid.
261 -- The assumption is that the directory portion of these output
262 -- options will have to exist by the time 'verifyOutputFiles'
265 verifyOutputFiles :: DynFlags -> IO ()
266 verifyOutputFiles dflags = do
267 let odir = objectDir dflags
268 when (isJust odir) $ do
269 let dir = fromJust odir
270 flg <- doesDirectoryExist dir
271 when (not flg) (nonExistentDir "-odir" dir)
272 let ofile = outputFile dflags
273 when (isJust ofile) $ do
274 let fn = fromJust ofile
275 flg <- doesDirNameExist fn
276 when (not flg) (nonExistentDir "-o" fn)
277 let ohi = outputHi dflags
278 when (isJust ohi) $ do
279 let hi = fromJust ohi
280 flg <- doesDirNameExist hi
281 when (not flg) (nonExistentDir "-ohi" hi)
283 nonExistentDir flg dir =
284 throwDyn (CmdLineError ("error: directory portion of " ++
285 show dir ++ " does not exist (used with " ++
286 show flg ++ " option.)"))
288 -----------------------------------------------------------------------------
289 -- GHC modes of operation
292 = ShowUsage -- ghc -?
293 | PrintLibdir -- ghc --print-libdir
294 | ShowVersion -- ghc -V/--version
295 | ShowNumVersion -- ghc --numeric-version
296 | ShowInterface String -- ghc --show-iface
297 | DoMkDependHS -- ghc -M
298 | StopBefore Phase -- ghc -E | -C | -S
299 -- StopBefore StopLn is the default
300 | DoMake -- ghc --make
301 | DoInteractive -- ghc --interactive
302 | DoEval String -- ghc -e
305 isInteractiveMode, isInterpretiveMode :: CmdLineMode -> Bool
306 isLinkMode, isCompManagerMode :: CmdLineMode -> Bool
308 isInteractiveMode DoInteractive = True
309 isInteractiveMode _ = False
311 -- isInterpretiveMode: byte-code compiler involved
312 isInterpretiveMode DoInteractive = True
313 isInterpretiveMode (DoEval _) = True
314 isInterpretiveMode _ = False
316 needsInputsMode DoMkDependHS = True
317 needsInputsMode (StopBefore _) = True
318 needsInputsMode DoMake = True
319 needsInputsMode _ = False
321 -- True if we are going to attempt to link in this mode.
322 -- (we might not actually link, depending on the GhcLink flag)
323 isLinkMode (StopBefore StopLn) = True
324 isLinkMode DoMake = True
327 isCompManagerMode DoMake = True
328 isCompManagerMode DoInteractive = True
329 isCompManagerMode (DoEval _) = True
330 isCompManagerMode _ = False
333 -- -----------------------------------------------------------------------------
334 -- Parsing the mode flag
336 parseModeFlags :: [String] -> IO (CmdLineMode, [String])
337 parseModeFlags args = do
338 let ((leftover, errs), (mode, _, flags)) =
339 runCmdLine (processArgs mode_flags args) (StopBefore StopLn, "", [])
340 when (not (null errs)) $ do
341 throwDyn (UsageError (unlines errs))
342 return (mode, flags ++ leftover)
344 type ModeM a = CmdLineP (CmdLineMode, String, [String]) a
345 -- mode flags sometimes give rise to new DynFlags (eg. -C, see below)
346 -- so we collect the new ones and return them.
348 mode_flags :: [(String, OptKind (CmdLineP (CmdLineMode, String, [String])))]
350 [ ------- help / version ----------------------------------------------
351 ( "?" , PassFlag (setMode ShowUsage))
352 , ( "-help" , PassFlag (setMode ShowUsage))
353 , ( "-print-libdir" , PassFlag (setMode PrintLibdir))
354 , ( "V" , PassFlag (setMode ShowVersion))
355 , ( "-version" , PassFlag (setMode ShowVersion))
356 , ( "-numeric-version", PassFlag (setMode ShowNumVersion))
358 ------- interfaces ----------------------------------------------------
359 , ( "-show-iface" , HasArg (\f -> setMode (ShowInterface f)
362 ------- primary modes ------------------------------------------------
363 , ( "M" , PassFlag (setMode DoMkDependHS))
364 , ( "E" , PassFlag (setMode (StopBefore anyHsc)))
365 , ( "C" , PassFlag (\f -> do setMode (StopBefore HCc) f
367 , ( "S" , PassFlag (setMode (StopBefore As)))
368 , ( "-make" , PassFlag (setMode DoMake))
369 , ( "-interactive" , PassFlag (setMode DoInteractive))
370 , ( "e" , HasArg (\s -> setMode (DoEval s) "-e"))
372 -- -fno-code says to stop after Hsc but don't generate any code.
373 , ( "fno-code" , PassFlag (\f -> do setMode (StopBefore HCc) f
375 addFlag "-no-recomp"))
378 setMode :: CmdLineMode -> String -> ModeM ()
380 (old_mode, old_flag, flags) <- getCmdLineState
381 when (notNull old_flag && flag /= old_flag) $
383 ("cannot use `" ++ old_flag ++ "' with `" ++ flag ++ "'"))
384 putCmdLineState (m, flag, flags)
386 addFlag :: String -> ModeM ()
388 (m, f, flags) <- getCmdLineState
389 putCmdLineState (m, f, s:flags)
392 -- ----------------------------------------------------------------------------
395 doMake :: Session -> [(String,Maybe Phase)] -> IO ()
396 doMake sess [] = throwDyn (UsageError "no input files")
397 doMake sess srcs = do
398 let (hs_srcs, non_hs_srcs) = partition haskellish srcs
400 haskellish (f,Nothing) =
401 looksLikeModuleName f || isHaskellSrcFilename f || '.' `notElem` f
402 haskellish (f,Just phase) =
403 phase `notElem` [As, Cc, CmmCpp, Cmm, StopLn]
405 dflags <- GHC.getSessionDynFlags sess
406 o_files <- mapM (compileFile dflags StopLn) non_hs_srcs
407 mapM_ (consIORef v_Ld_inputs) (reverse o_files)
409 targets <- mapM (uncurry GHC.guessTarget) hs_srcs
410 GHC.setTargets sess targets
411 ok_flag <- GHC.load sess LoadAllTargets
412 when (failed ok_flag) (exitWith (ExitFailure 1))
416 -- ---------------------------------------------------------------------------
419 doShowIface :: DynFlags -> FilePath -> IO ()
420 doShowIface dflags file = do
421 hsc_env <- newHscEnv dflags
422 showIface hsc_env file
424 -- ---------------------------------------------------------------------------
425 -- Various banners and verbosity output.
427 showBanner :: CmdLineMode -> DynFlags -> IO ()
428 showBanner cli_mode dflags = do
429 let verb = verbosity dflags
432 -- Show the GHCi banner
433 when (isInteractiveMode cli_mode && verb >= 1) $ putStrLn ghciWelcomeMsg
436 -- Display details of the configuration in verbose mode
438 do hPutStr stderr "Glasgow Haskell Compiler, Version "
439 hPutStr stderr cProjectVersion
440 hPutStr stderr ", for Haskell 98, stage "
441 hPutStr stderr cStage
442 hPutStr stderr " booted by GHC version "
443 hPutStrLn stderr cBooterVersion
447 putStrLn (cProjectName ++ ", version " ++ cProjectVersion)
450 showGhcUsage dflags cli_mode = do
452 | DoInteractive <- cli_mode = ghciUsagePath dflags
453 | otherwise = ghcUsagePath dflags
454 usage <- readFile usage_path
459 dump ('$':'$':s) = putStr progName >> dump s
460 dump (c:s) = putChar c >> dump s
462 dumpFinalStats :: DynFlags -> IO ()
463 dumpFinalStats dflags =
464 when (dopt Opt_D_faststring_stats dflags) $ dumpFastStringStats dflags
466 dumpFastStringStats :: DynFlags -> IO ()
467 dumpFastStringStats dflags = do
468 buckets <- getFastStringTable
469 let (entries, longest, is_z, has_z) = countFS 0 0 0 0 buckets
470 msg = text "FastString stats:" $$
471 nest 4 (vcat [text "size: " <+> int (length buckets),
472 text "entries: " <+> int entries,
473 text "longest chain: " <+> int longest,
474 text "z-encoded: " <+> (is_z `pcntOf` entries),
475 text "has z-encoding: " <+> (has_z `pcntOf` entries)
477 -- we usually get more "has z-encoding" than "z-encoded", because
478 -- when we z-encode a string it might hash to the exact same string,
479 -- which will is not counted as "z-encoded". Only strings whose
480 -- Z-encoding is different from the original string are counted in
481 -- the "z-encoded" total.
484 x `pcntOf` y = int ((x * 100) `quot` y) <> char '%'
486 countFS entries longest is_z has_z [] = (entries, longest, is_z, has_z)
487 countFS entries longest is_z has_z (b:bs) =
490 longest' = max len longest
491 entries' = entries + len
492 is_zs = length (filter isZEncoded b)
493 has_zs = length (filter hasZEncoding b)
495 countFS entries' longest' (is_z + is_zs) (has_z + has_zs) bs
497 -- -----------------------------------------------------------------------------
500 unknownFlagsErr :: [String] -> a
501 unknownFlagsErr fs = throwDyn (UsageError ("unrecognised flags: " ++ unwords fs))