1 {-# OPTIONS -fno-warn-incomplete-patterns -optc-DNON_POSIX_SOURCE #-}
3 -----------------------------------------------------------------------------
4 -- $Id: Main.hs,v 1.114 2002/10/25 16:54:59 simonpj Exp $
8 -- (c) The University of Glasgow 2002
10 -----------------------------------------------------------------------------
12 -- with path so that ghc -M can find config.h
13 #include "../includes/config.h"
15 module Main (main) where
17 #include "HsVersions.h"
22 import DriverPhases( objish_file )
26 import Finder ( initFinder )
27 import CompManager ( cmInit, cmLoadModules, cmDepAnal )
28 import HscTypes ( GhciMode(..) )
29 import Config ( cBooterVersion, cGhcUnregisterised, cProjectVersion )
30 import SysTools ( getPackageConfigPath, initSysTools, cleanTempFiles )
31 import Packages ( showPackages )
33 import DriverPipeline ( staticLink, doMkDLL, genPipeline, pipeLoop )
34 import DriverState ( buildCoreToDo, buildStgToDo,
35 findBuildTag, getPackageInfo, getPackageConfigMap,
36 getPackageExtraGhcOpts, unregFlags,
37 v_GhcMode, v_GhcModeFlag, GhcMode(..),
38 v_Keep_tmp_files, v_Ld_inputs, v_Ways,
39 v_OptLevel, v_Output_file, v_Output_hi,
40 readPackageConf, verifyOutputFiles
42 import DriverFlags ( buildStaticHscOpts,
43 dynamic_flags, processArgs, static_flags)
45 import DriverMkDepend ( beginMkDependHS, endMkDependHS )
46 import DriverPhases ( Phase(HsPp, Hsc), haskellish_src_file, isSourceFile )
48 import DriverUtil ( add, handle, handleDyn, later, splitFilename,
49 unknownFlagsErr, getFileSuffix )
50 import CmdLineOpts ( dynFlag, restoreDynFlags,
51 saveDynFlags, setDynFlags, getDynFlags, dynFlag,
52 DynFlags(..), HscLang(..), v_Static_hsc_opts,
55 import BasicTypes ( failed )
58 import Panic ( GhcException(..), panic )
60 import DATA_IOREF ( readIORef, writeIORef )
61 import EXCEPTION ( throwDyn, Exception(..),
62 AsyncException(StackOverflow) )
64 #ifndef mingw32_HOST_OS
65 import CONCURRENT ( myThreadId )
66 # if __GLASGOW_HASKELL__ < 500
67 import EXCEPTION ( raiseInThread )
68 #define throwTo raiseInThread
70 import EXCEPTION ( throwTo )
73 #if __GLASGOW_HASKELL__ > 504
74 import System.Posix.Signals
76 import Posix ( Handler(Catch), installHandler, sigINT, sigQUIT )
79 import DYNAMIC ( toDyn )
82 -- Standard Haskell libraries
84 import Directory ( doesFileExist )
85 import System ( getArgs, exitWith, ExitCode(..) )
90 -----------------------------------------------------------------------------
93 -- new mkdependHS doesn't support all the options that the old one did (-X et al.)
94 -- time commands when run with -v
98 -- Win32 support: proper signal handling
99 -- make sure OPTIONS in .hs file propogate to .hc file if -C or -keep-hc-file-too
100 -- reading the package configuration file is too slow
103 -----------------------------------------------------------------------------
104 -- Differences vs. old driver:
106 -- No more "Enter your Haskell program, end with ^D (on a line of its own):"
107 -- consistency checking removed (may do this properly later)
110 -----------------------------------------------------------------------------
114 -- top-level exception handler: any unrecognised exception is a compiler bug.
115 handle (\exception -> do
118 -- an IO exception probably isn't our fault, so don't panic
119 IOException _ -> hPutStr stderr (show exception)
120 AsyncException StackOverflow ->
121 hPutStrLn stderr "stack overflow: use +RTS -K<size> \
123 _other -> hPutStr stderr (show (Panic (show exception)))
124 exitWith (ExitFailure 1)
127 -- all error messages are propagated as exceptions
128 handleDyn (\dyn -> do
131 PhaseFailed _ code -> exitWith code
132 Interrupted -> exitWith (ExitFailure 1)
133 _ -> do hPutStrLn stderr (show (dyn :: GhcException))
134 exitWith (ExitFailure 1)
137 -- make sure we clean up after ourselves
138 later (do forget_it <- readIORef v_Keep_tmp_files
139 unless forget_it $ do
140 verb <- dynFlag verbosity
143 -- exceptions will be blocked while we clean the temporary files,
144 -- so there shouldn't be any difficulty if we receive further
147 -- install signal handlers
148 #ifndef mingw32_HOST_OS
149 main_thread <- myThreadId
150 let sig_handler = Catch (throwTo main_thread
151 (DynException (toDyn Interrupted)))
152 installHandler sigQUIT sig_handler Nothing
153 installHandler sigINT sig_handler Nothing
157 let (minusB_args, argv') = partition (prefixMatch "-B") argv
158 top_dir <- initSysTools minusB_args
160 -- Read the package configuration
161 conf_file <- getPackageConfigPath
162 readPackageConf conf_file
164 -- process all the other arguments, and get the source files
165 non_static <- processArgs static_flags argv' []
166 mode <- readIORef v_GhcMode
167 stop_flag <- readIORef v_GhcModeFlag
169 -- -O and --interactive are not a good combination
170 -- ditto with any kind of way selection
171 orig_opt_level <- readIORef v_OptLevel
172 when (orig_opt_level > 0 && mode == DoInteractive) $
173 do putStr "warning: -O conflicts with --interactive; -O turned off.\n"
174 writeIORef v_OptLevel 0
175 orig_ways <- readIORef v_Ways
176 when (notNull orig_ways && mode == DoInteractive) $
177 do throwDyn (UsageError
178 "--interactive can't be used with -prof, -ticky, -unreg or -smp.")
180 -- Find the build tag, and re-process the build-specific options.
181 -- Also add in flags for unregisterised compilation, if
182 -- GhcUnregisterised=YES.
183 way_opts <- findBuildTag
184 let unreg_opts | cGhcUnregisterised == "YES" = unregFlags
186 pkg_extra_opts <- getPackageExtraGhcOpts
187 extra_non_static <- processArgs static_flags
188 (unreg_opts ++ way_opts ++ pkg_extra_opts) []
190 -- give the static flags to hsc
191 static_opts <- buildStaticHscOpts
192 writeIORef v_Static_hsc_opts static_opts
194 -- build the default DynFlags (these may be adjusted on a per
195 -- module basis by OPTIONS pragmas and settings in the interpreter).
197 core_todo <- buildCoreToDo
198 stg_todo <- buildStgToDo
200 -- set the "global" HscLang. The HscLang can be further adjusted on a module
201 -- by module basis, using only the -fvia-C and -fasm flags. If the global
202 -- HscLang is not HscC or HscAsm, -fvia-C and -fasm have no effect.
203 dyn_flags <- getDynFlags
204 let lang = case mode of
205 DoInteractive -> HscInterpreted
206 _other -> hscLang dyn_flags
208 setDynFlags (dyn_flags{ coreToDo = core_todo,
211 -- leave out hscOutName for now
212 hscOutName = panic "Main.main:hscOutName not set",
216 -- the rest of the arguments are "dynamic"
217 srcs <- processArgs dynamic_flags (extra_non_static ++ non_static) []
219 -- save the "initial DynFlags" away
222 -- perform some checks of the options set / report unknowns.
225 verb <- dynFlag verbosity
227 -- Show the GHCi banner
229 when (mode == DoInteractive && verb >= 1) $
230 hPutStrLn stdout ghciWelcomeMsg
233 -- Display details of the configuration in verbose mode
235 (do hPutStr stderr "Glasgow Haskell Compiler, Version "
236 hPutStr stderr cProjectVersion
237 hPutStr stderr ", for Haskell 98, compiled by GHC version "
238 hPutStrLn stderr cBooterVersion)
241 (hPutStrLn stderr ("Using package config file: " ++ conf_file))
243 pkg_details <- getPackageConfigMap
244 showPackages pkg_details
247 (hPutStrLn stderr ("Hsc static flags: " ++ unwords static_opts))
249 -- initialise the finder
250 pkg_avails <- getPackageInfo
251 initFinder pkg_avails
253 -- mkdependHS is special
254 when (mode == DoMkDependHS) beginMkDependHS
256 -- -ohi sanity checking
257 ohi <- readIORef v_Output_hi
259 (mode == DoMake || mode == DoInteractive || srcs `lengthExceeds` 1))
260 then throwDyn (UsageError "-ohi can only be used when compiling a single source file")
263 -- make/interactive require invoking the compilation manager
264 if (mode == DoMake) then beginMake srcs else do
265 if (mode == DoInteractive) then beginInteractive srcs else do
267 -- -o sanity checking
268 let real_srcs = filter isSourceFile srcs -- filters out .a and .o that might appear
269 o_file <- readIORef v_Output_file
270 if (real_srcs `lengthExceeds` 1 && isJust o_file && mode /= DoLink && mode /= DoMkDLL)
271 then throwDyn (UsageError "can't apply -o to multiple source files")
274 if null srcs then throwDyn (UsageError "no input files") else do
276 let compileFile src = do
279 exists <- doesFileExist src
281 throwDyn (CmdLineError ("file `" ++ src ++ "' does not exist"))
283 -- We compile in two stages, because the file may have an
284 -- OPTIONS pragma that affects the compilation pipeline (eg. -fvia-C)
285 let (basename, suffix) = splitFilename src
287 -- just preprocess (Haskell source only)
288 let src_and_suff = (src, getFileSuffix src)
289 let not_hs_file = not (haskellish_src_file src)
290 pp <- if not_hs_file || mode == StopBefore Hsc || mode == StopBefore HsPp
291 then return src_and_suff else do
292 phases <- genPipeline (StopBefore Hsc) stop_flag
293 False{-not persistent-} defaultHscLang
295 pipeLoop phases src_and_suff False{-no linking-} False{-no -o flag-}
298 -- rest of compilation
299 hsc_lang <- dynFlag hscLang
300 phases <- genPipeline mode stop_flag True hsc_lang pp
301 (r,_) <- pipeLoop phases pp (mode==DoLink || mode==DoMkDLL)
302 True{-use -o flag-} basename suffix
305 o_files <- mapM compileFile srcs
307 when (mode == DoMkDependHS) endMkDependHS
308 when (mode == DoLink) (staticLink o_files)
309 when (mode == DoMkDLL) (doMkDLL o_files)
313 beginMake :: [String] -> IO ()
314 beginMake fileish_args = do
315 -- anything that doesn't look like a Haskell source filename or
316 -- a module name is passed straight through to the linker
317 let (inputs, objects) = partition looks_like_an_input fileish_args
318 mapM_ (add v_Ld_inputs) objects
321 [] -> throwDyn (UsageError "no input files")
322 _ -> do dflags <- getDynFlags
323 state <- cmInit Batch
324 graph <- cmDepAnal state dflags inputs
325 (_, ok_flag, _) <- cmLoadModules state dflags graph
326 when (failed ok_flag) (exitWith (ExitFailure 1))
329 looks_like_an_input m = haskellish_src_file m || '.' `notElem` m
332 beginInteractive :: [String] -> IO ()
334 beginInteractive = throwDyn (CmdLineError "not built for interactive use")
336 beginInteractive fileish_args
337 = do state <- cmInit Interactive
339 let (objs, mods) = partition objish_file fileish_args
341 interactiveUI state mods objs
344 checkOptions :: [String] -> IO ()
345 checkOptions srcs = do
346 -- complain about any unknown flags
347 let unknown_opts = [ f | f@('-':_) <- srcs ]
348 when (notNull unknown_opts) (unknownFlagsErr unknown_opts)
349 -- verify that output files point somewhere sensible.
351 -- and anything else that it might be worth checking for
352 -- before kicking of a compilation (pipeline).