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(..) )
19 -- Implementations of the various modes (--show-iface, mkdependHS. etc.)
20 import MkIface ( showIface )
21 import DriverPipeline ( oneShot )
22 import DriverMkDepend ( doMkDependHS )
23 import SysTools ( getTopDir, getUsageMsgPaths )
25 import InteractiveUI ( ghciWelcomeMsg, interactiveUI )
28 -- Various other random stuff that we need
29 import Config ( cProjectVersion, cBooterVersion, cProjectName )
30 import Packages ( dumpPackages, initPackages )
31 import DriverPhases ( Phase(..), isSourceFilename, anyHsc )
32 import StaticFlags ( staticFlags, v_Ld_inputs )
33 import BasicTypes ( failed )
37 -- Standard Haskell libraries
38 import EXCEPTION ( throwDyn )
40 import Directory ( doesFileExist, doesDirectoryExist )
41 import System ( getArgs, exitWith, ExitCode(..) )
46 -----------------------------------------------------------------------------
49 -- time commands when run with -v
51 -- Win32 support: proper signal handling
52 -- reading the package configuration file is too slow
55 -----------------------------------------------------------------------------
56 -- GHC's command-line interface
59 GHC.defaultErrorHandler $ do
62 argv1 <- GHC.init argv0
64 -- 2. Parse the "mode" flags (--make, --interactive etc.)
65 (cli_mode, argv2) <- parseModeFlags argv1
67 let mode = case cli_mode of
68 DoInteractive -> Interactive
69 DoEval _ -> Interactive
70 DoMake -> BatchCompile
71 DoMkDependHS -> MkDepend
74 -- start our GHC session
75 session <- GHC.newSession mode
77 dflags0 <- GHC.getSessionDynFlags session
79 -- set the default HscTarget. The HscTarget can be further
80 -- adjusted on a module by module basis, using only the -fvia-C and
81 -- -fasm flags. If the default HscTarget is not HscC or HscAsm,
82 -- -fvia-C and -fasm have no effect.
83 let lang = case cli_mode of
84 DoInteractive -> HscInterpreted
85 DoEval _ -> HscInterpreted
86 _other -> hscTarget dflags0
88 let dflags1 = dflags0{ ghcMode = mode,
90 -- leave out hscOutName for now
91 hscOutName = panic "Main.main:hscOutName not set",
92 verbosity = case cli_mode of
97 -- The rest of the arguments are "dynamic"
98 -- Leftover ones are presumably files
99 (dflags2, fileish_args) <- GHC.parseDynamicFlags dflags1 argv2
101 -- make sure we clean up after ourselves
102 GHC.defaultCleanupHandler dflags2 $ do
105 showBanner cli_mode dflags2
107 -- Read the package config(s), and process the package-related
108 -- command-line flags
109 dflags <- initPackages dflags2
111 -- we've finished manipulating the DynFlags, update the session
112 GHC.setSessionDynFlags session dflags
116 We split out the object files (.o, .dll) and add them
117 to v_Ld_inputs for use by the linker.
119 The following things should be considered compilation manager inputs:
121 - haskell source files (strings ending in .hs, .lhs or other
122 haskellish extension),
124 - module names (not forgetting hierarchical module names),
126 - and finally we consider everything not containing a '.' to be
127 a comp manager input, as shorthand for a .hs or .lhs filename.
129 Everything else is considered to be a linker object, and passed
130 straight through to the linker.
132 looks_like_an_input m = isSourceFilename m
133 || looksLikeModuleName m
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 looks_like_an_input 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 cli_mode
159 PrintLibdir -> do d <- getTopDir; putStrLn d
160 ShowVersion -> showVersion
161 ShowNumVersion -> putStrLn cProjectVersion
162 ShowInterface f -> showIface f
163 DoMake -> doMake session srcs
164 DoMkDependHS -> doMkDependHS session srcs
165 StopBefore p -> oneShot dflags p srcs
166 DoInteractive -> interactiveUI session srcs Nothing
167 DoEval expr -> interactiveUI session srcs (Just expr)
172 interactiveUI _ _ _ =
173 throwDyn (CmdLineError "not built for interactive use")
177 -- -----------------------------------------------------------------------------
178 -- Option sanity checks
180 checkOptions :: CmdLineMode -> DynFlags -> [String] -> [String] -> IO ()
181 -- Final sanity checking before kicking off a compilation (pipeline).
182 checkOptions cli_mode dflags srcs objs = do
183 -- Complain about any unknown flags
184 let unknown_opts = [ f | f@('-':_) <- srcs ]
185 when (notNull unknown_opts) (unknownFlagsErr unknown_opts)
187 -- -prof and --interactive are not a good combination
188 when (notNull (wayNames dflags) && isInterpretiveMode cli_mode) $
189 do throwDyn (UsageError
190 "--interactive can't be used with -prof, -ticky, -unreg or -smp.")
192 if (isJust (outputHi dflags) &&
193 (isCompManagerMode cli_mode || srcs `lengthExceeds` 1))
194 then throwDyn (UsageError "-ohi can only be used when compiling a single source file")
197 -- -o sanity checking
198 if (srcs `lengthExceeds` 1 && isJust (outputFile dflags)
199 && not (isLinkMode cli_mode))
200 then throwDyn (UsageError "can't apply -o to multiple source files")
203 -- Check that there are some input files
204 -- (except in the interactive case)
205 if null srcs && null objs && needsInputsMode cli_mode
206 then throwDyn (UsageError "no input files")
209 -- Verify that output files point somewhere sensible.
210 verifyOutputFiles dflags
213 -- Compiler output options
215 -- called to verify that the output files & directories
216 -- point somewhere valid.
218 -- The assumption is that the directory portion of these output
219 -- options will have to exist by the time 'verifyOutputFiles'
222 verifyOutputFiles :: DynFlags -> IO ()
223 verifyOutputFiles dflags = do
224 let odir = outputDir dflags
225 when (isJust odir) $ do
226 let dir = fromJust odir
227 flg <- doesDirectoryExist dir
228 when (not flg) (nonExistentDir "-odir" dir)
229 let ofile = outputFile dflags
230 when (isJust ofile) $ do
231 let fn = fromJust ofile
232 flg <- doesDirNameExist fn
233 when (not flg) (nonExistentDir "-o" fn)
234 let ohi = outputHi dflags
235 when (isJust ohi) $ do
236 let hi = fromJust ohi
237 flg <- doesDirNameExist hi
238 when (not flg) (nonExistentDir "-ohi" hi)
240 nonExistentDir flg dir =
241 throwDyn (CmdLineError ("error: directory portion of " ++
242 show dir ++ " does not exist (used with " ++
243 show flg ++ " option.)"))
245 -----------------------------------------------------------------------------
246 -- GHC modes of operation
249 = ShowUsage -- ghc -?
250 | PrintLibdir -- ghc --print-libdir
251 | ShowVersion -- ghc -V/--version
252 | ShowNumVersion -- ghc --numeric-version
253 | ShowInterface String -- ghc --show-iface
254 | DoMkDependHS -- ghc -M
255 | StopBefore Phase -- ghc -E | -C | -S
256 -- StopBefore StopLn is the default
257 | DoMake -- ghc --make
258 | DoInteractive -- ghc --interactive
259 | DoEval String -- ghc -e
262 isInteractiveMode, isInterpretiveMode :: CmdLineMode -> Bool
263 isLinkMode, isCompManagerMode :: CmdLineMode -> Bool
265 isInteractiveMode DoInteractive = True
266 isInteractiveMode _ = False
268 -- isInterpretiveMode: byte-code compiler involved
269 isInterpretiveMode DoInteractive = True
270 isInterpretiveMode (DoEval _) = True
271 isInterpretiveMode _ = False
273 needsInputsMode DoMkDependHS = True
274 needsInputsMode (StopBefore _) = True
275 needsInputsMode DoMake = True
276 needsInputsMode _ = False
278 -- True if we are going to attempt to link in this mode.
279 -- (we might not actually link, depending on the GhcLink flag)
280 isLinkMode (StopBefore StopLn) = True
281 isLinkMode DoMake = True
284 isCompManagerMode DoMake = True
285 isCompManagerMode DoInteractive = True
286 isCompManagerMode (DoEval _) = True
287 isCompManagerMode _ = False
290 -- -----------------------------------------------------------------------------
291 -- Parsing the mode flag
293 parseModeFlags :: [String] -> IO (CmdLineMode, [String])
294 parseModeFlags args = do
295 let ((leftover, errs), (mode, _, flags)) =
296 runCmdLine (processArgs mode_flags args) (StopBefore StopLn, "", [])
297 when (not (null errs)) $ do
298 throwDyn (UsageError (unlines errs))
299 return (mode, flags ++ leftover)
301 type ModeM a = CmdLineP (CmdLineMode, String, [String]) a
302 -- mode flags sometimes give rise to new DynFlags (eg. -C, see below)
303 -- so we collect the new ones and return them.
305 mode_flags :: [(String, OptKind (CmdLineP (CmdLineMode, String, [String])))]
307 [ ------- help / version ----------------------------------------------
308 ( "?" , PassFlag (setMode ShowUsage))
309 , ( "-help" , PassFlag (setMode ShowUsage))
310 , ( "-print-libdir" , PassFlag (setMode PrintLibdir))
311 , ( "V" , PassFlag (setMode ShowVersion))
312 , ( "-version" , PassFlag (setMode ShowVersion))
313 , ( "-numeric-version", PassFlag (setMode ShowNumVersion))
315 ------- interfaces ----------------------------------------------------
316 , ( "-show-iface" , HasArg (\f -> setMode (ShowInterface f)
319 ------- primary modes ------------------------------------------------
320 , ( "M" , PassFlag (setMode DoMkDependHS))
321 , ( "E" , PassFlag (setMode (StopBefore anyHsc)))
322 , ( "C" , PassFlag (\f -> do setMode (StopBefore HCc) f
324 , ( "S" , PassFlag (setMode (StopBefore As)))
325 , ( "-make" , PassFlag (setMode DoMake))
326 , ( "-interactive" , PassFlag (setMode DoInteractive))
327 , ( "e" , HasArg (\s -> setMode (DoEval s) "-e"))
329 -- -fno-code says to stop after Hsc but don't generate any code.
330 , ( "fno-code" , PassFlag (\f -> do setMode (StopBefore HCc) f
332 addFlag "-no-recomp"))
335 setMode :: CmdLineMode -> String -> ModeM ()
337 (old_mode, old_flag, flags) <- getCmdLineState
338 when (notNull old_flag && flag /= old_flag) $
340 ("cannot use `" ++ old_flag ++ "' with `" ++ flag ++ "'"))
341 putCmdLineState (m, flag, flags)
343 addFlag :: String -> ModeM ()
345 (m, f, flags) <- getCmdLineState
346 putCmdLineState (m, f, s:flags)
349 -- ----------------------------------------------------------------------------
352 doMake :: Session -> [String] -> IO ()
353 doMake sess [] = throwDyn (UsageError "no input files")
354 doMake sess srcs = do
355 targets <- mapM GHC.guessTarget srcs
356 GHC.setTargets sess targets
357 ok_flag <- GHC.load sess Nothing
358 when (failed ok_flag) (exitWith (ExitFailure 1))
361 -- ---------------------------------------------------------------------------
362 -- Various banners and verbosity output.
364 showBanner :: CmdLineMode -> DynFlags -> IO ()
365 showBanner cli_mode dflags = do
366 let verb = verbosity dflags
367 -- Show the GHCi banner
369 when (isInteractiveMode cli_mode && verb >= 1) $
370 hPutStrLn stdout ghciWelcomeMsg
373 -- Display details of the configuration in verbose mode
374 when (not (isInteractiveMode cli_mode) && verb >= 2) $
375 do hPutStr stderr "Glasgow Haskell Compiler, Version "
376 hPutStr stderr cProjectVersion
377 hPutStr stderr ", for Haskell 98, compiled by GHC version "
378 hPutStrLn stderr cBooterVersion
382 putStrLn (cProjectName ++ ", version " ++ cProjectVersion)
385 showGhcUsage cli_mode = do
386 (ghc_usage_path,ghci_usage_path) <- getUsageMsgPaths
388 | DoInteractive <- cli_mode = ghci_usage_path
389 | otherwise = ghc_usage_path
390 usage <- readFile usage_path
395 dump ('$':'$':s) = hPutStr stderr progName >> dump s
396 dump (c:s) = hPutChar stderr c >> dump s
398 -- -----------------------------------------------------------------------------
401 unknownFlagsErr :: [String] -> a
402 unknownFlagsErr fs = throwDyn (UsageError ("unrecognised flags: " ++ unwords fs))