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(..),
20 -- Implementations of the various modes (--show-iface, mkdependHS. etc.)
21 import MkIface ( showIface )
22 import DriverPipeline ( oneShot, compileFile )
23 import DriverMkDepend ( doMkDependHS )
24 import SysTools ( getTopDir, getUsageMsgPaths )
26 import InteractiveUI ( ghciWelcomeMsg, interactiveUI )
29 -- Various other random stuff that we need
30 import Config ( cProjectVersion, cBooterVersion, cProjectName )
31 import Packages ( dumpPackages, initPackages )
32 import DriverPhases ( Phase(..), isSourceSuffix, isSourceFilename, anyHsc,
33 startPhase, isHaskellSrcFilename )
34 import StaticFlags ( staticFlags, v_Ld_inputs )
35 import BasicTypes ( failed )
39 -- Standard Haskell libraries
40 import EXCEPTION ( throwDyn )
42 import Directory ( doesFileExist, doesDirectoryExist )
43 import System ( getArgs, exitWith, ExitCode(..) )
48 -----------------------------------------------------------------------------
51 -- time commands when run with -v
53 -- Win32 support: proper signal handling
54 -- reading the package configuration file is too slow
57 -----------------------------------------------------------------------------
58 -- GHC's command-line interface
61 GHC.defaultErrorHandler $ do
64 argv1 <- GHC.init argv0
66 -- 2. Parse the "mode" flags (--make, --interactive etc.)
67 (cli_mode, argv2) <- parseModeFlags argv1
69 let mode = case cli_mode of
70 DoInteractive -> Interactive
71 DoEval _ -> Interactive
72 DoMake -> BatchCompile
73 DoMkDependHS -> MkDepend
76 -- start our GHC session
77 session <- GHC.newSession mode
79 dflags0 <- GHC.getSessionDynFlags session
81 -- set the default HscTarget. The HscTarget can be further
82 -- adjusted on a module by module basis, using only the -fvia-C and
83 -- -fasm flags. If the default HscTarget is not HscC or HscAsm,
84 -- -fvia-C and -fasm have no effect.
85 let lang = case cli_mode of
86 DoInteractive -> HscInterpreted
87 DoEval _ -> HscInterpreted
88 _other -> hscTarget dflags0
90 let dflags1 = dflags0{ ghcMode = mode,
92 -- leave out hscOutName for now
93 hscOutName = panic "Main.main:hscOutName not set",
94 verbosity = case cli_mode of
99 -- The rest of the arguments are "dynamic"
100 -- Leftover ones are presumably files
101 (dflags2, fileish_args) <- GHC.parseDynamicFlags dflags1 argv2
103 -- make sure we clean up after ourselves
104 GHC.defaultCleanupHandler dflags2 $ do
107 showBanner cli_mode dflags2
109 -- Read the package config(s), and process the package-related
110 -- command-line flags
111 dflags <- initPackages dflags2
113 -- we've finished manipulating the DynFlags, update the session
114 GHC.setSessionDynFlags session dflags
117 -- To simplify the handling of filepaths, we normalise all filepaths right
118 -- away - e.g., for win32 platforms, backslashes are converted
119 -- into forward slashes.
120 normal_fileish_paths = map normalisePath fileish_args
121 (srcs, objs) = partition_args normal_fileish_paths [] []
123 -- Note: have v_Ld_inputs maintain the order in which 'objs' occurred on
125 mapM_ (consIORef v_Ld_inputs) (reverse objs)
127 ---------------- Display configuration -----------
128 when (verbosity dflags >= 4) $
131 when (verbosity dflags >= 3) $ do
132 hPutStrLn stderr ("Hsc static flags: " ++ unwords staticFlags)
134 ---------------- Final sanity checking -----------
135 checkOptions cli_mode dflags srcs objs
137 ---------------- Do the business -----------
139 ShowUsage -> showGhcUsage cli_mode
140 PrintLibdir -> do d <- getTopDir; putStrLn d
141 ShowVersion -> showVersion
142 ShowNumVersion -> putStrLn cProjectVersion
143 ShowInterface f -> showIface f
144 DoMake -> doMake session srcs
145 DoMkDependHS -> doMkDependHS session (map fst srcs)
146 StopBefore p -> oneShot dflags p srcs
147 DoInteractive -> interactiveUI session srcs Nothing
148 DoEval expr -> interactiveUI session srcs (Just expr)
153 interactiveUI _ _ _ =
154 throwDyn (CmdLineError "not built for interactive use")
157 -- -----------------------------------------------------------------------------
158 -- Splitting arguments into source files and object files. This is where we
159 -- interpret the -x <suffix> option, and attach a (Maybe Phase) to each source
160 -- file indicating the phase specified by the -x option in force, if any.
162 partition_args [] srcs objs = (reverse srcs, reverse objs)
163 partition_args ("-x":suff:args) srcs objs
164 | "none" <- suff = partition_args args srcs objs
165 | StopLn <- phase = partition_args args srcs (slurp ++ objs)
166 | otherwise = partition_args rest (these_srcs ++ srcs) objs
167 where phase = startPhase suff
168 (slurp,rest) = break (== "-x") args
169 these_srcs = zip slurp (repeat (Just phase))
170 partition_args (arg:args) srcs objs
171 | looks_like_an_input arg = partition_args args ((arg,Nothing):srcs) objs
172 | otherwise = partition_args args srcs (arg:objs)
175 We split out the object files (.o, .dll) and add them
176 to v_Ld_inputs for use by the linker.
178 The following things should be considered compilation manager inputs:
180 - haskell source files (strings ending in .hs, .lhs or other
181 haskellish extension),
183 - module names (not forgetting hierarchical module names),
185 - and finally we consider everything not containing a '.' to be
186 a comp manager input, as shorthand for a .hs or .lhs filename.
188 Everything else is considered to be a linker object, and passed
189 straight through to the linker.
191 looks_like_an_input m = isSourceFilename m
192 || looksLikeModuleName m
195 -- -----------------------------------------------------------------------------
196 -- Option sanity checks
198 checkOptions :: CmdLineMode -> DynFlags -> [(String,Maybe Phase)] -> [String] -> IO ()
199 -- Final sanity checking before kicking off a compilation (pipeline).
200 checkOptions cli_mode dflags srcs objs = do
201 -- Complain about any unknown flags
202 let unknown_opts = [ f | (f@('-':_), _) <- srcs ]
203 when (notNull unknown_opts) (unknownFlagsErr unknown_opts)
205 -- -prof and --interactive are not a good combination
206 when (notNull (wayNames dflags) && isInterpretiveMode cli_mode) $
207 do throwDyn (UsageError
208 "--interactive can't be used with -prof, -ticky, -unreg or -smp.")
210 if (isJust (outputHi dflags) &&
211 (isCompManagerMode cli_mode || srcs `lengthExceeds` 1))
212 then throwDyn (UsageError "-ohi can only be used when compiling a single source file")
215 -- -o sanity checking
216 if (srcs `lengthExceeds` 1 && isJust (outputFile dflags)
217 && not (isLinkMode cli_mode))
218 then throwDyn (UsageError "can't apply -o to multiple source files")
221 -- Check that there are some input files
222 -- (except in the interactive case)
223 if null srcs && null objs && needsInputsMode cli_mode
224 then throwDyn (UsageError "no input files")
227 -- Verify that output files point somewhere sensible.
228 verifyOutputFiles dflags
231 -- Compiler output options
233 -- called to verify that the output files & directories
234 -- point somewhere valid.
236 -- The assumption is that the directory portion of these output
237 -- options will have to exist by the time 'verifyOutputFiles'
240 verifyOutputFiles :: DynFlags -> IO ()
241 verifyOutputFiles dflags = do
242 let odir = outputDir dflags
243 when (isJust odir) $ do
244 let dir = fromJust odir
245 flg <- doesDirectoryExist dir
246 when (not flg) (nonExistentDir "-odir" dir)
247 let ofile = outputFile dflags
248 when (isJust ofile) $ do
249 let fn = fromJust ofile
250 flg <- doesDirNameExist fn
251 when (not flg) (nonExistentDir "-o" fn)
252 let ohi = outputHi dflags
253 when (isJust ohi) $ do
254 let hi = fromJust ohi
255 flg <- doesDirNameExist hi
256 when (not flg) (nonExistentDir "-ohi" hi)
258 nonExistentDir flg dir =
259 throwDyn (CmdLineError ("error: directory portion of " ++
260 show dir ++ " does not exist (used with " ++
261 show flg ++ " option.)"))
263 -----------------------------------------------------------------------------
264 -- GHC modes of operation
267 = ShowUsage -- ghc -?
268 | PrintLibdir -- ghc --print-libdir
269 | ShowVersion -- ghc -V/--version
270 | ShowNumVersion -- ghc --numeric-version
271 | ShowInterface String -- ghc --show-iface
272 | DoMkDependHS -- ghc -M
273 | StopBefore Phase -- ghc -E | -C | -S
274 -- StopBefore StopLn is the default
275 | DoMake -- ghc --make
276 | DoInteractive -- ghc --interactive
277 | DoEval String -- ghc -e
280 isInteractiveMode, isInterpretiveMode :: CmdLineMode -> Bool
281 isLinkMode, isCompManagerMode :: CmdLineMode -> Bool
283 isInteractiveMode DoInteractive = True
284 isInteractiveMode _ = False
286 -- isInterpretiveMode: byte-code compiler involved
287 isInterpretiveMode DoInteractive = True
288 isInterpretiveMode (DoEval _) = True
289 isInterpretiveMode _ = False
291 needsInputsMode DoMkDependHS = True
292 needsInputsMode (StopBefore _) = True
293 needsInputsMode DoMake = True
294 needsInputsMode _ = False
296 -- True if we are going to attempt to link in this mode.
297 -- (we might not actually link, depending on the GhcLink flag)
298 isLinkMode (StopBefore StopLn) = True
299 isLinkMode DoMake = True
302 isCompManagerMode DoMake = True
303 isCompManagerMode DoInteractive = True
304 isCompManagerMode (DoEval _) = True
305 isCompManagerMode _ = False
308 -- -----------------------------------------------------------------------------
309 -- Parsing the mode flag
311 parseModeFlags :: [String] -> IO (CmdLineMode, [String])
312 parseModeFlags args = do
313 let ((leftover, errs), (mode, _, flags)) =
314 runCmdLine (processArgs mode_flags args) (StopBefore StopLn, "", [])
315 when (not (null errs)) $ do
316 throwDyn (UsageError (unlines errs))
317 return (mode, flags ++ leftover)
319 type ModeM a = CmdLineP (CmdLineMode, String, [String]) a
320 -- mode flags sometimes give rise to new DynFlags (eg. -C, see below)
321 -- so we collect the new ones and return them.
323 mode_flags :: [(String, OptKind (CmdLineP (CmdLineMode, String, [String])))]
325 [ ------- help / version ----------------------------------------------
326 ( "?" , PassFlag (setMode ShowUsage))
327 , ( "-help" , PassFlag (setMode ShowUsage))
328 , ( "-print-libdir" , PassFlag (setMode PrintLibdir))
329 , ( "V" , PassFlag (setMode ShowVersion))
330 , ( "-version" , PassFlag (setMode ShowVersion))
331 , ( "-numeric-version", PassFlag (setMode ShowNumVersion))
333 ------- interfaces ----------------------------------------------------
334 , ( "-show-iface" , HasArg (\f -> setMode (ShowInterface f)
337 ------- primary modes ------------------------------------------------
338 , ( "M" , PassFlag (setMode DoMkDependHS))
339 , ( "E" , PassFlag (setMode (StopBefore anyHsc)))
340 , ( "C" , PassFlag (\f -> do setMode (StopBefore HCc) f
342 , ( "S" , PassFlag (setMode (StopBefore As)))
343 , ( "-make" , PassFlag (setMode DoMake))
344 , ( "-interactive" , PassFlag (setMode DoInteractive))
345 , ( "e" , HasArg (\s -> setMode (DoEval s) "-e"))
347 -- -fno-code says to stop after Hsc but don't generate any code.
348 , ( "fno-code" , PassFlag (\f -> do setMode (StopBefore HCc) f
350 addFlag "-no-recomp"))
353 setMode :: CmdLineMode -> String -> ModeM ()
355 (old_mode, old_flag, flags) <- getCmdLineState
356 when (notNull old_flag && flag /= old_flag) $
358 ("cannot use `" ++ old_flag ++ "' with `" ++ flag ++ "'"))
359 putCmdLineState (m, flag, flags)
361 addFlag :: String -> ModeM ()
363 (m, f, flags) <- getCmdLineState
364 putCmdLineState (m, f, s:flags)
367 -- ----------------------------------------------------------------------------
370 doMake :: Session -> [(String,Maybe Phase)] -> IO ()
371 doMake sess [] = throwDyn (UsageError "no input files")
372 doMake sess srcs = do
373 let (hs_srcs, non_hs_srcs) = partition haskellish srcs
375 haskellish (f,Nothing) =
376 looksLikeModuleName f || isHaskellSrcFilename f || '.' `notElem` f
377 haskellish (f,Just phase) =
378 phase `notElem` [As, Cc, CmmCpp, Cmm, StopLn]
380 dflags <- GHC.getSessionDynFlags sess
381 o_files <- mapM (compileFile dflags StopLn) non_hs_srcs
382 mapM_ (consIORef v_Ld_inputs) (reverse o_files)
384 targets <- mapM (uncurry GHC.guessTarget) hs_srcs
385 GHC.setTargets sess targets
386 ok_flag <- GHC.load sess LoadAllTargets
387 when (failed ok_flag) (exitWith (ExitFailure 1))
390 -- ---------------------------------------------------------------------------
391 -- Various banners and verbosity output.
393 showBanner :: CmdLineMode -> DynFlags -> IO ()
394 showBanner cli_mode dflags = do
395 let verb = verbosity dflags
396 -- Show the GHCi banner
398 when (isInteractiveMode cli_mode && verb >= 1) $
399 hPutStrLn stdout ghciWelcomeMsg
402 -- Display details of the configuration in verbose mode
403 when (not (isInteractiveMode cli_mode) && verb >= 2) $
404 do hPutStr stderr "Glasgow Haskell Compiler, Version "
405 hPutStr stderr cProjectVersion
406 hPutStr stderr ", for Haskell 98, compiled by GHC version "
407 hPutStrLn stderr cBooterVersion
411 putStrLn (cProjectName ++ ", version " ++ cProjectVersion)
414 showGhcUsage cli_mode = do
415 (ghc_usage_path,ghci_usage_path) <- getUsageMsgPaths
417 | DoInteractive <- cli_mode = ghci_usage_path
418 | otherwise = ghc_usage_path
419 usage <- readFile usage_path
424 dump ('$':'$':s) = hPutStr stderr progName >> dump s
425 dump (c:s) = hPutChar stderr c >> dump s
427 -- -----------------------------------------------------------------------------
430 unknownFlagsErr :: [String] -> a
431 unknownFlagsErr fs = throwDyn (UsageError ("unrecognised flags: " ++ unwords fs))