1 {-# OPTIONS -fno-warn-incomplete-patterns -optc-DNON_POSIX_SOURCE #-}
3 -----------------------------------------------------------------------------
4 -- $Id: Main.hs,v 1.110 2002/09/06 14:35:44 simonmar 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"
25 import Finder ( initFinder )
26 import CompManager ( cmInit, cmLoadModules, cmDepAnal )
27 import HscTypes ( GhciMode(..) )
28 import Config ( cBooterVersion, cGhcUnregisterised, cProjectVersion )
29 import SysTools ( getPackageConfigPath, initSysTools, cleanTempFiles )
30 import Packages ( showPackages )
32 import DriverPipeline ( doLink, doMkDLL, genPipeline, pipeLoop )
33 import DriverState ( buildCoreToDo, buildStgToDo,
34 findBuildTag, getPackageInfo, unregFlags,
35 v_GhcMode, v_GhcModeFlag, GhcMode(..),
36 v_Cmdline_libraries, v_Keep_tmp_files, v_Ld_inputs,
37 v_OptLevel, v_Output_file, v_Output_hi,
38 v_Package_details, v_Ways, getPackageExtraGhcOpts,
39 readPackageConf, verifyOutputFiles
41 import DriverFlags ( buildStaticHscOpts,
42 dynamic_flags, processArgs, static_flags)
44 import DriverMkDepend ( beginMkDependHS, endMkDependHS )
45 import DriverPhases ( Phase(HsPp, Hsc), haskellish_src_file, objish_file,
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,
57 import Panic ( GhcException(..), panic )
59 import DATA_IOREF ( readIORef, writeIORef )
60 import EXCEPTION ( throwDyn, Exception(..),
61 AsyncException(StackOverflow) )
63 #ifndef mingw32_HOST_OS
64 import CONCURRENT ( myThreadId )
65 # if __GLASGOW_HASKELL__ < 500
66 import EXCEPTION ( raiseInThread )
67 #define throwTo raiseInThread
69 import EXCEPTION ( throwTo )
72 #if __GLASGOW_HASKELL__ > 504
73 import System.Posix.Signals
75 import Posix ( Handler(Catch), installHandler, sigINT, sigQUIT )
78 import DYNAMIC ( toDyn )
81 -- Standard Haskell libraries
83 import Directory ( doesFileExist )
84 import System ( getArgs, exitWith, ExitCode(..) )
89 -----------------------------------------------------------------------------
92 -- new mkdependHS doesn't support all the options that the old one did (-X et al.)
93 -- time commands when run with -v
97 -- Win32 support: proper signal handling
98 -- make sure OPTIONS in .hs file propogate to .hc file if -C or -keep-hc-file-too
99 -- reading the package configuration file is too slow
102 -----------------------------------------------------------------------------
103 -- Differences vs. old driver:
105 -- No more "Enter your Haskell program, end with ^D (on a line of its own):"
106 -- consistency checking removed (may do this properly later)
109 -----------------------------------------------------------------------------
113 -- top-level exception handler: any unrecognised exception is a compiler bug.
114 handle (\exception -> do
117 -- an IO exception probably isn't our fault, so don't panic
118 IOException _ -> hPutStr stderr (show exception)
119 AsyncException StackOverflow ->
120 hPutStrLn stderr "stack overflow: use +RTS -K<size> \
122 _other -> hPutStr stderr (show (Panic (show exception)))
123 exitWith (ExitFailure 1)
126 -- all error messages are propagated as exceptions
127 handleDyn (\dyn -> do
130 PhaseFailed _ code -> exitWith code
131 Interrupted -> exitWith (ExitFailure 1)
132 _ -> do hPutStrLn stderr (show (dyn :: GhcException))
133 exitWith (ExitFailure 1)
136 -- make sure we clean up after ourselves
137 later (do forget_it <- readIORef v_Keep_tmp_files
138 unless forget_it $ do
139 verb <- dynFlag verbosity
142 -- exceptions will be blocked while we clean the temporary files,
143 -- so there shouldn't be any difficulty if we receive further
146 -- install signal handlers
147 #ifndef mingw32_HOST_OS
148 main_thread <- myThreadId
149 let sig_handler = Catch (throwTo main_thread
150 (DynException (toDyn Interrupted)))
151 installHandler sigQUIT sig_handler Nothing
152 installHandler sigINT sig_handler Nothing
156 let (minusB_args, argv') = partition (prefixMatch "-B") argv
157 top_dir <- initSysTools minusB_args
159 -- Read the package configuration
160 conf_file <- getPackageConfigPath
161 readPackageConf conf_file
163 -- process all the other arguments, and get the source files
164 non_static <- processArgs static_flags argv' []
165 mode <- readIORef v_GhcMode
166 stop_flag <- readIORef v_GhcModeFlag
168 -- -O and --interactive are not a good combination
169 -- ditto with any kind of way selection
170 orig_opt_level <- readIORef v_OptLevel
171 when (orig_opt_level > 0 && mode == DoInteractive) $
172 do putStr "warning: -O conflicts with --interactive; -O turned off.\n"
173 writeIORef v_OptLevel 0
174 orig_ways <- readIORef v_Ways
175 when (notNull orig_ways && mode == DoInteractive) $
176 do throwDyn (UsageError
177 "--interactive can't be used with -prof, -ticky, -unreg or -smp.")
179 -- Find the build tag, and re-process the build-specific options.
180 -- Also add in flags for unregisterised compilation, if
181 -- GhcUnregisterised=YES.
182 way_opts <- findBuildTag
183 let unreg_opts | cGhcUnregisterised == "YES" = unregFlags
185 pkg_extra_opts <- getPackageExtraGhcOpts
186 extra_non_static <- processArgs static_flags
187 (unreg_opts ++ way_opts ++ pkg_extra_opts) []
189 -- give the static flags to hsc
190 static_opts <- buildStaticHscOpts
191 writeIORef v_Static_hsc_opts static_opts
193 -- build the default DynFlags (these may be adjusted on a per
194 -- module basis by OPTIONS pragmas and settings in the interpreter).
196 core_todo <- buildCoreToDo
197 stg_todo <- buildStgToDo
199 -- set the "global" HscLang. The HscLang can be further adjusted on a module
200 -- by module basis, using only the -fvia-C and -fasm flags. If the global
201 -- HscLang is not HscC or HscAsm, -fvia-C and -fasm have no effect.
202 dyn_flags <- getDynFlags
203 let lang = case mode of
204 DoInteractive -> HscInterpreted
205 _other -> hscLang dyn_flags
207 setDynFlags (dyn_flags{ coreToDo = core_todo,
210 -- leave out hscOutName for now
211 hscOutName = panic "Main.main:hscOutName not set",
215 -- the rest of the arguments are "dynamic"
216 srcs <- processArgs dynamic_flags (extra_non_static ++ non_static) []
218 -- save the "initial DynFlags" away
221 -- perform some checks of the options set / report unknowns.
224 verb <- dynFlag verbosity
226 -- Show the GHCi banner
228 when (mode == DoInteractive && verb >= 1) $
229 hPutStrLn stdout ghciWelcomeMsg
232 -- Display details of the configuration in verbose mode
234 (do hPutStr stderr "Glasgow Haskell Compiler, Version "
235 hPutStr stderr cProjectVersion
236 hPutStr stderr ", for Haskell 98, compiled by GHC version "
237 hPutStrLn stderr cBooterVersion)
240 (hPutStrLn stderr ("Using package config file: " ++ conf_file))
242 pkg_details <- readIORef v_Package_details
243 showPackages pkg_details
246 (hPutStrLn stderr ("Hsc static flags: " ++ unwords static_opts))
248 -- initialise the finder
249 pkg_avails <- getPackageInfo
250 initFinder pkg_avails
252 -- mkdependHS is special
253 when (mode == DoMkDependHS) beginMkDependHS
255 -- -ohi sanity checking
256 ohi <- readIORef v_Output_hi
258 (mode == DoMake || mode == DoInteractive || srcs `lengthExceeds` 1))
259 then throwDyn (UsageError "-ohi can only be used when compiling a single source file")
262 -- make/interactive require invoking the compilation manager
263 if (mode == DoMake) then beginMake srcs else do
264 if (mode == DoInteractive) then beginInteractive srcs else do
266 -- -o sanity checking
267 let real_srcs = filter isSourceFile srcs -- filters out .a and .o that might appear
268 o_file <- readIORef v_Output_file
269 if (real_srcs `lengthExceeds` 1 && isJust o_file && mode /= DoLink && mode /= DoMkDLL)
270 then throwDyn (UsageError "can't apply -o to multiple source files")
273 if null srcs then throwDyn (UsageError "no input files") else do
275 let compileFile src = do
278 exists <- doesFileExist src
280 throwDyn (CmdLineError ("file `" ++ src ++ "' does not exist"))
282 -- We compile in two stages, because the file may have an
283 -- OPTIONS pragma that affects the compilation pipeline (eg. -fvia-C)
284 let (basename, suffix) = splitFilename src
286 -- just preprocess (Haskell source only)
287 let src_and_suff = (src, getFileSuffix src)
288 let not_hs_file = not (haskellish_src_file src)
289 pp <- if not_hs_file || mode == StopBefore Hsc || mode == StopBefore HsPp
290 then return src_and_suff else do
291 phases <- genPipeline (StopBefore Hsc) stop_flag
292 False{-not persistent-} defaultHscLang
294 pipeLoop phases src_and_suff False{-no linking-} False{-no -o flag-}
297 -- rest of compilation
298 hsc_lang <- dynFlag hscLang
299 phases <- genPipeline mode stop_flag True hsc_lang pp
300 (r,_) <- pipeLoop phases pp (mode==DoLink || mode==DoMkDLL)
301 True{-use -o flag-} basename suffix
304 o_files <- mapM compileFile srcs
306 when (mode == DoMkDependHS) endMkDependHS
307 when (mode == DoLink) (doLink o_files)
308 when (mode == DoMkDLL) (doMkDLL o_files)
312 beginMake :: [String] -> IO ()
313 beginMake fileish_args
314 = do let (objs, mods) = partition objish_file fileish_args
315 mapM_ (add v_Ld_inputs) objs
318 [] -> throwDyn (UsageError "no input files")
319 _ -> do dflags <- getDynFlags
320 state <- cmInit Batch
321 graph <- cmDepAnal state dflags mods
322 (_, ok, _) <- cmLoadModules state dflags graph
323 when (not ok) (exitWith (ExitFailure 1))
327 beginInteractive :: [String] -> IO ()
329 beginInteractive = throwDyn (CmdLineError "not built for interactive use")
331 beginInteractive fileish_args
332 = do minus_ls <- readIORef v_Cmdline_libraries
334 let (objs, mods) = partition objish_file fileish_args
335 libs = map Object objs ++ map DLL minus_ls
337 state <- cmInit Interactive
338 interactiveUI state mods libs
341 checkOptions :: [String] -> IO ()
342 checkOptions srcs = do
343 -- complain about any unknown flags
344 let unknown_opts = [ f | f@('-':_) <- srcs ]
345 when (notNull unknown_opts) (unknownFlagsErr unknown_opts)
346 -- verify that output files point somewhere sensible.
348 -- and anything else that it might be worth checking for
349 -- before kicking of a compilation (pipeline).