1 {-# OPTIONS -fno-warn-incomplete-patterns -optc-DNON_POSIX_SOURCE #-}
3 -----------------------------------------------------------------------------
7 -- (c) The University of Glasgow 2005
9 -----------------------------------------------------------------------------
11 module Main (main) where
13 -- The official GHC API
15 import GHC ( DynFlags(..), HscTarget(..),
16 GhcMode(..), GhcLink(..),
17 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
33 import Packages ( dumpPackages )
34 import DriverPhases ( Phase(..), isSourceFilename, anyHsc,
35 startPhase, isHaskellSrcFilename )
36 import BasicTypes ( failed )
38 import StaticFlagParser
46 import MonadUtils ( liftIO )
48 -- Standard Haskell libraries
50 import System.Environment
52 import System.FilePath
57 -----------------------------------------------------------------------------
60 -- time commands when run with -v
62 -- Win32 support: proper signal handling
63 -- reading the package configuration file is too slow
66 -----------------------------------------------------------------------------
67 -- GHC's command-line interface
72 GHC.defaultErrorHandler defaultDynFlags $ do
73 -- 1. extract the -B flag from the args
77 (minusB_args, argv1) = partition ("-B" `isPrefixOf`) argv0
78 mbMinusB | null minusB_args = Nothing
79 | otherwise = Just (drop 2 (last minusB_args))
81 let argv1' = map (mkGeneralLocated "on the commandline") argv1
82 (argv2, staticFlagWarnings) <- parseStaticFlags argv1'
84 -- 2. Parse the "mode" flags (--make, --interactive etc.)
85 (m_uber_mode, cli_mode, argv3, modeFlagWarnings) <- parseModeFlags argv2
87 -- If all we want to do is to show the version number then do it
88 -- now, before we start a GHC session etc.
89 -- If we do it later then bootstrapping gets confused as it tries
90 -- to find out what version of GHC it's using before package.conf
91 -- exists, so starting the session fails.
93 -- ShowUsage currently has to be handled specially, as it needs to
94 -- actually start up GHC so that it can find the usage.txt files
95 -- in the libdir. It would be nice to embed the text in the
96 -- executable so that we don't have to do that, and things are more
98 Just ShowUsage -> return ()
102 ShowSupportedLanguages -> showSupportedLanguages
103 ShowVersion -> showVersion
104 ShowNumVersion -> putStrLn cProjectVersion
108 -- start our GHC session
109 GHC.runGhc mbMinusB $ do
111 dflags0 <- GHC.getSessionDynFlags
113 -- set the default GhcMode, HscTarget and GhcLink. The HscTarget
114 -- can be further adjusted on a module by module basis, using only
115 -- the -fvia-C and -fasm flags. If the default HscTarget is not
116 -- HscC or HscAsm, -fvia-C and -fasm have no effect.
117 let dflt_target = hscTarget dflags0
120 DoInteractive -> (CompManager, HscInterpreted, LinkInMemory)
121 DoEval _ -> (CompManager, HscInterpreted, LinkInMemory)
122 DoMake -> (CompManager, dflt_target, LinkBinary)
123 DoMkDependHS -> (MkDepend, dflt_target, LinkBinary)
124 _ -> (OneShot, dflt_target, LinkBinary)
126 let dflags1 = dflags0{ ghcMode = mode,
129 -- leave out hscOutName for now
130 hscOutName = panic "Main.main:hscOutName not set",
131 verbosity = case cli_mode of
136 -- turn on -fimplicit-import-qualified for GHCi now, so that it
137 -- can be overriden from the command-line
138 dflags1a | DoInteractive <- cli_mode = imp_qual_enabled
139 | DoEval _ <- cli_mode = imp_qual_enabled
140 | otherwise = dflags1
141 where imp_qual_enabled = dflags1 `dopt_set` Opt_ImplicitImportQualified
143 -- The rest of the arguments are "dynamic"
144 -- Leftover ones are presumably files
145 (dflags2, fileish_args, dynamicFlagWarnings) <- GHC.parseDynamicFlags dflags1a argv3
147 -- As noted earlier, currently we hvae to handle ShowUsage down here
149 Just ShowUsage -> liftIO $ showGhcUsage dflags2 cli_mode
152 let flagWarnings = staticFlagWarnings
154 ++ dynamicFlagWarnings
156 handleSourceError (\e -> do
157 GHC.printExceptionAndWarnings e
158 liftIO $ exitWith (ExitFailure 1)) $
159 handleFlagWarnings dflags2 flagWarnings
161 -- make sure we clean up after ourselves
162 GHC.defaultCleanupHandler dflags2 $ do
164 liftIO $ showBanner cli_mode dflags2
166 -- we've finished manipulating the DynFlags, update the session
167 GHC.setSessionDynFlags dflags2
168 dflags3 <- GHC.getSessionDynFlags
169 hsc_env <- GHC.getSession
172 -- To simplify the handling of filepaths, we normalise all filepaths right
173 -- away - e.g., for win32 platforms, backslashes are converted
174 -- into forward slashes.
175 normal_fileish_paths = map (normalise . unLoc) fileish_args
176 (srcs, objs) = partition_args normal_fileish_paths [] []
178 -- Note: have v_Ld_inputs maintain the order in which 'objs' occurred on
180 liftIO $ mapM_ (consIORef v_Ld_inputs) (reverse objs)
182 ---------------- Display configuration -----------
183 when (verbosity dflags3 >= 4) $
184 liftIO $ dumpPackages dflags3
186 when (verbosity dflags3 >= 3) $ do
187 liftIO $ hPutStrLn stderr ("Hsc static flags: " ++ unwords staticFlags)
189 ---------------- Final sanity checking -----------
190 liftIO $ checkOptions cli_mode dflags3 srcs objs
192 ---------------- Do the business -----------
193 handleSourceError (\e -> do
194 GHC.printExceptionAndWarnings e
195 liftIO $ exitWith (ExitFailure 1)) $ do
197 PrintLibdir -> liftIO $ putStrLn (topDir dflags3)
198 ShowInterface f -> liftIO $ doShowIface dflags3 f
199 DoMake -> doMake srcs
200 DoMkDependHS -> doMkDependHS (map fst srcs)
201 StopBefore p -> oneShot hsc_env p srcs >> GHC.printWarnings
202 DoInteractive -> interactiveUI srcs Nothing
203 DoEval exprs -> interactiveUI srcs $ Just $ reverse exprs
205 liftIO $ dumpFinalStats dflags3
206 liftIO $ exitWith ExitSuccess
209 interactiveUI :: b -> c -> Ghc ()
211 ghcError (CmdLineError "not built for interactive use")
214 -- -----------------------------------------------------------------------------
215 -- Splitting arguments into source files and object files. This is where we
216 -- interpret the -x <suffix> option, and attach a (Maybe Phase) to each source
217 -- file indicating the phase specified by the -x option in force, if any.
219 partition_args :: [String] -> [(String, Maybe Phase)] -> [String]
220 -> ([(String, Maybe Phase)], [String])
221 partition_args [] srcs objs = (reverse srcs, reverse objs)
222 partition_args ("-x":suff:args) srcs objs
223 | "none" <- suff = partition_args args srcs objs
224 | StopLn <- phase = partition_args args srcs (slurp ++ objs)
225 | otherwise = partition_args rest (these_srcs ++ srcs) objs
226 where phase = startPhase suff
227 (slurp,rest) = break (== "-x") args
228 these_srcs = zip slurp (repeat (Just phase))
229 partition_args (arg:args) srcs objs
230 | looks_like_an_input arg = partition_args args ((arg,Nothing):srcs) objs
231 | otherwise = partition_args args srcs (arg:objs)
234 We split out the object files (.o, .dll) and add them
235 to v_Ld_inputs for use by the linker.
237 The following things should be considered compilation manager inputs:
239 - haskell source files (strings ending in .hs, .lhs or other
240 haskellish extension),
242 - module names (not forgetting hierarchical module names),
244 - and finally we consider everything not containing a '.' to be
245 a comp manager input, as shorthand for a .hs or .lhs filename.
247 Everything else is considered to be a linker object, and passed
248 straight through to the linker.
250 looks_like_an_input :: String -> Bool
251 looks_like_an_input m = isSourceFilename m
252 || looksLikeModuleName m
255 -- -----------------------------------------------------------------------------
256 -- Option sanity checks
258 -- | Ensure sanity of options.
260 -- Throws 'UsageError' or 'CmdLineError' if not.
261 checkOptions :: CmdLineMode -> DynFlags -> [(String,Maybe Phase)] -> [String] -> IO ()
262 -- Final sanity checking before kicking off a compilation (pipeline).
263 checkOptions cli_mode dflags srcs objs = do
264 -- Complain about any unknown flags
265 let unknown_opts = [ f | (f@('-':_), _) <- srcs ]
266 when (notNull unknown_opts) (unknownFlagsErr unknown_opts)
268 when (notNull (filter isRTSWay (wayNames dflags))
269 && isInterpretiveMode cli_mode) $
270 hPutStrLn stderr ("Warning: -debug, -threaded and -ticky are ignored by GHCi")
272 -- -prof and --interactive are not a good combination
273 when (notNull (filter (not . isRTSWay) (wayNames dflags))
274 && isInterpretiveMode cli_mode) $
275 do ghcError (UsageError
276 "--interactive can't be used with -prof or -unreg.")
278 if (isJust (outputHi dflags) &&
279 (isCompManagerMode cli_mode || srcs `lengthExceeds` 1))
280 then ghcError (UsageError "-ohi can only be used when compiling a single source file")
283 -- -o sanity checking
284 if (srcs `lengthExceeds` 1 && isJust (outputFile dflags)
285 && not (isLinkMode cli_mode))
286 then ghcError (UsageError "can't apply -o to multiple source files")
289 let not_linking = not (isLinkMode cli_mode) || isNoLink (ghcLink dflags)
291 when (not_linking && not (null objs)) $
292 hPutStrLn stderr ("Warning: the following files would be used as linker inputs, but linking is not being done: " ++ unwords objs)
294 -- Check that there are some input files
295 -- (except in the interactive case)
296 if null srcs && (null objs || not_linking) && needsInputsMode cli_mode
297 then ghcError (UsageError "no input files")
300 -- Verify that output files point somewhere sensible.
301 verifyOutputFiles dflags
304 -- Compiler output options
306 -- called to verify that the output files & directories
307 -- point somewhere valid.
309 -- The assumption is that the directory portion of these output
310 -- options will have to exist by the time 'verifyOutputFiles'
313 verifyOutputFiles :: DynFlags -> IO ()
314 verifyOutputFiles dflags = do
315 -- not -odir: we create the directory for -odir if it doesn't exist (#2278).
316 let ofile = outputFile dflags
317 when (isJust ofile) $ do
318 let fn = fromJust ofile
319 flg <- doesDirNameExist fn
320 when (not flg) (nonExistentDir "-o" fn)
321 let ohi = outputHi dflags
322 when (isJust ohi) $ do
323 let hi = fromJust ohi
324 flg <- doesDirNameExist hi
325 when (not flg) (nonExistentDir "-ohi" hi)
327 nonExistentDir flg dir =
328 ghcError (CmdLineError ("error: directory portion of " ++
329 show dir ++ " does not exist (used with " ++
330 show flg ++ " option.)"))
332 -----------------------------------------------------------------------------
333 -- GHC modes of operation
336 = ShowUsage -- ghc -?
337 | ShowVersion -- ghc -V/--version
338 | ShowNumVersion -- ghc --numeric-version
339 | ShowSupportedLanguages -- ghc --supported-languages
340 | ShowInfo -- ghc --info
344 = PrintLibdir -- ghc --print-libdir
345 | ShowInterface String -- ghc --show-iface
346 | DoMkDependHS -- ghc -M
347 | StopBefore Phase -- ghc -E | -C | -S
348 -- StopBefore StopLn is the default
349 | DoMake -- ghc --make
350 | DoInteractive -- ghc --interactive
351 | DoEval [String] -- ghc -e foo -e bar => DoEval ["bar", "foo"]
355 isInteractiveMode :: CmdLineMode -> Bool
356 isInteractiveMode DoInteractive = True
357 isInteractiveMode _ = False
360 -- isInterpretiveMode: byte-code compiler involved
361 isInterpretiveMode :: CmdLineMode -> Bool
362 isInterpretiveMode DoInteractive = True
363 isInterpretiveMode (DoEval _) = True
364 isInterpretiveMode _ = False
366 needsInputsMode :: CmdLineMode -> Bool
367 needsInputsMode DoMkDependHS = True
368 needsInputsMode (StopBefore _) = True
369 needsInputsMode DoMake = True
370 needsInputsMode _ = False
372 -- True if we are going to attempt to link in this mode.
373 -- (we might not actually link, depending on the GhcLink flag)
374 isLinkMode :: CmdLineMode -> Bool
375 isLinkMode (StopBefore StopLn) = True
376 isLinkMode DoMake = True
377 isLinkMode DoInteractive = True
378 isLinkMode (DoEval _) = True
381 isCompManagerMode :: CmdLineMode -> Bool
382 isCompManagerMode DoMake = True
383 isCompManagerMode DoInteractive = True
384 isCompManagerMode (DoEval _) = True
385 isCompManagerMode _ = False
388 -- -----------------------------------------------------------------------------
389 -- Parsing the mode flag
391 parseModeFlags :: [Located String]
392 -> IO (Maybe UberMode,
396 parseModeFlags args = do
397 let ((leftover, errs, warns), (mUberMode, mode, _, flags')) =
398 runCmdLine (processArgs mode_flags args)
399 (Nothing, StopBefore StopLn, "", [])
400 when (not (null errs)) $ ghcError $ errorsToGhcException errs
401 return (mUberMode, mode, flags' ++ leftover, warns)
403 type ModeM = CmdLineP (Maybe UberMode, CmdLineMode, String, [Located String])
404 -- mode flags sometimes give rise to new DynFlags (eg. -C, see below)
405 -- so we collect the new ones and return them.
407 mode_flags :: [Flag ModeM]
409 [ ------- help / version ----------------------------------------------
410 Flag "?" (NoArg (setUberMode ShowUsage))
412 , Flag "-help" (NoArg (setUberMode ShowUsage))
414 , Flag "V" (NoArg (setUberMode ShowVersion))
416 , Flag "-version" (NoArg (setUberMode ShowVersion))
418 , Flag "-numeric-version" (NoArg (setUberMode ShowNumVersion))
420 , Flag "-info" (NoArg (setUberMode ShowInfo))
422 , Flag "-supported-languages" (NoArg (setUberMode ShowSupportedLanguages))
424 , Flag "-print-libdir" (PassFlag (setMode PrintLibdir))
427 ------- interfaces ----------------------------------------------------
428 , Flag "-show-iface" (HasArg (\f -> setMode (ShowInterface f)
432 ------- primary modes ------------------------------------------------
433 , Flag "M" (PassFlag (setMode DoMkDependHS))
435 , Flag "E" (PassFlag (setMode (StopBefore anyHsc)))
437 , Flag "C" (PassFlag (\f -> do setMode (StopBefore HCc) f
440 , Flag "S" (PassFlag (setMode (StopBefore As)))
442 , Flag "-make" (PassFlag (setMode DoMake))
444 , Flag "-interactive" (PassFlag (setMode DoInteractive))
446 , Flag "e" (HasArg (\s -> updateMode (updateDoEval s) "-e"))
449 -- -fno-code says to stop after Hsc but don't generate any code.
450 , Flag "fno-code" (PassFlag (\f -> do setMode (StopBefore HCc) f
452 addFlag "-fforce-recomp"))
456 setUberMode :: UberMode -> ModeM ()
458 (_, cmdLineMode, flag, flags') <- getCmdLineState
459 putCmdLineState (Just m, cmdLineMode, flag, flags')
461 setMode :: CmdLineMode -> String -> ModeM ()
462 setMode m flag = updateMode (\_ -> m) flag
464 updateDoEval :: String -> CmdLineMode -> CmdLineMode
465 updateDoEval expr (DoEval exprs) = DoEval (expr : exprs)
466 updateDoEval expr _ = DoEval [expr]
468 updateMode :: (CmdLineMode -> CmdLineMode) -> String -> ModeM ()
469 updateMode f flag = do
470 (m_uber_mode, old_mode, old_flag, flags') <- getCmdLineState
471 if null old_flag || flag == old_flag
472 then putCmdLineState (m_uber_mode, f old_mode, flag, flags')
473 else ghcError (UsageError
474 ("cannot use `" ++ old_flag ++ "' with `" ++ flag ++ "'"))
476 addFlag :: String -> ModeM ()
478 (u, m, f, flags') <- getCmdLineState
479 -- XXX Can we get a useful Loc?
480 putCmdLineState (u, m, f, mkGeneralLocated "addFlag" s : flags')
483 -- ----------------------------------------------------------------------------
486 doMake :: [(String,Maybe Phase)] -> Ghc ()
487 doMake [] = ghcError (UsageError "no input files")
489 let (hs_srcs, non_hs_srcs) = partition haskellish srcs
491 haskellish (f,Nothing) =
492 looksLikeModuleName f || isHaskellSrcFilename f || '.' `notElem` f
493 haskellish (_,Just phase) =
494 phase `notElem` [As, Cc, CmmCpp, Cmm, StopLn]
496 hsc_env <- GHC.getSession
497 o_files <- mapM (\x -> do
498 f <- compileFile hsc_env StopLn x
502 liftIO $ mapM_ (consIORef v_Ld_inputs) (reverse o_files)
504 targets <- mapM (uncurry GHC.guessTarget) hs_srcs
505 GHC.setTargets targets
506 ok_flag <- GHC.load LoadAllTargets
508 when (failed ok_flag) (liftIO $ exitWith (ExitFailure 1))
512 -- ---------------------------------------------------------------------------
515 doShowIface :: DynFlags -> FilePath -> IO ()
516 doShowIface dflags file = do
517 hsc_env <- newHscEnv defaultCallbacks dflags
518 showIface hsc_env file
520 -- ---------------------------------------------------------------------------
521 -- Various banners and verbosity output.
523 showBanner :: CmdLineMode -> DynFlags -> IO ()
524 showBanner _cli_mode dflags = do
525 let verb = verbosity dflags
528 -- Show the GHCi banner
529 when (isInteractiveMode _cli_mode && verb >= 1) $ putStrLn ghciWelcomeMsg
532 -- Display details of the configuration in verbose mode
534 do hPutStr stderr "Glasgow Haskell Compiler, Version "
535 hPutStr stderr cProjectVersion
536 hPutStr stderr ", for Haskell 98, stage "
537 hPutStr stderr cStage
538 hPutStr stderr " booted by GHC version "
539 hPutStrLn stderr cBooterVersion
541 -- We print out a Read-friendly string, but a prettier one than the
542 -- Show instance gives us
545 let sq x = " [" ++ x ++ "\n ]"
546 putStrLn $ sq $ concat $ intersperse "\n ," $ map show compilerInfo
549 showSupportedLanguages :: IO ()
550 showSupportedLanguages = do mapM_ putStrLn supportedLanguages
555 putStrLn (cProjectName ++ ", version " ++ cProjectVersion)
558 showGhcUsage :: DynFlags -> CmdLineMode -> IO ()
559 showGhcUsage dflags cli_mode = do
561 | DoInteractive <- cli_mode = ghciUsagePath dflags
562 | otherwise = ghcUsagePath dflags
563 usage <- readFile usage_path
568 dump ('$':'$':s) = putStr progName >> dump s
569 dump (c:s) = putChar c >> dump s
571 dumpFinalStats :: DynFlags -> IO ()
572 dumpFinalStats dflags =
573 when (dopt Opt_D_faststring_stats dflags) $ dumpFastStringStats dflags
575 dumpFastStringStats :: DynFlags -> IO ()
576 dumpFastStringStats dflags = do
577 buckets <- getFastStringTable
578 let (entries, longest, is_z, has_z) = countFS 0 0 0 0 buckets
579 msg = text "FastString stats:" $$
580 nest 4 (vcat [text "size: " <+> int (length buckets),
581 text "entries: " <+> int entries,
582 text "longest chain: " <+> int longest,
583 text "z-encoded: " <+> (is_z `pcntOf` entries),
584 text "has z-encoding: " <+> (has_z `pcntOf` entries)
586 -- we usually get more "has z-encoding" than "z-encoded", because
587 -- when we z-encode a string it might hash to the exact same string,
588 -- which will is not counted as "z-encoded". Only strings whose
589 -- Z-encoding is different from the original string are counted in
590 -- the "z-encoded" total.
593 x `pcntOf` y = int ((x * 100) `quot` y) <> char '%'
595 countFS :: Int -> Int -> Int -> Int -> [[FastString]] -> (Int, Int, Int, Int)
596 countFS entries longest is_z has_z [] = (entries, longest, is_z, has_z)
597 countFS entries longest is_z has_z (b:bs) =
600 longest' = max len longest
601 entries' = entries + len
602 is_zs = length (filter isZEncoded b)
603 has_zs = length (filter hasZEncoding b)
605 countFS entries' longest' (is_z + is_zs) (has_z + has_zs) bs
607 -- -----------------------------------------------------------------------------
610 unknownFlagsErr :: [String] -> a
611 unknownFlagsErr fs = ghcError (UsageError ("unrecognised flags: " ++ unwords fs))