1 {-# OPTIONS -fno-warn-incomplete-patterns -optc-DNON_POSIX_SOURCE #-}
3 -----------------------------------------------------------------------------
4 -- $Id: Main.hs,v 1.107 2002/07/05 16:15:14 sof 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 -- Standard Haskell libraries
61 import Directory ( doesFileExist )
62 import IOExts ( readIORef, writeIORef )
63 import Exception ( throwDyn, Exception(..),
64 AsyncException(StackOverflow) )
65 import System ( getArgs, exitWith, ExitCode(..) )
70 #ifndef mingw32_HOST_OS
71 import Concurrent ( myThreadId )
72 # if __GLASGOW_HASKELL__ < 500
73 import Exception ( raiseInThread )
74 #define throwTo raiseInThread
76 import Exception ( throwTo )
79 import Posix ( Handler(Catch), installHandler, sigINT, sigQUIT )
80 import Dynamic ( toDyn )
83 -----------------------------------------------------------------------------
86 -- new mkdependHS doesn't support all the options that the old one did (-X et al.)
87 -- time commands when run with -v
91 -- Win32 support: proper signal handling
92 -- make sure OPTIONS in .hs file propogate to .hc file if -C or -keep-hc-file-too
93 -- reading the package configuration file is too slow
96 -----------------------------------------------------------------------------
97 -- Differences vs. old driver:
99 -- No more "Enter your Haskell program, end with ^D (on a line of its own):"
100 -- consistency checking removed (may do this properly later)
103 -----------------------------------------------------------------------------
107 -- top-level exception handler: any unrecognised exception is a compiler bug.
108 handle (\exception -> do
111 -- an IO exception probably isn't our fault, so don't panic
112 IOException _ -> hPutStr stderr (show exception)
113 AsyncException StackOverflow ->
114 hPutStrLn stderr "stack overflow: use +RTS -K<size> \
116 _other -> hPutStr stderr (show (Panic (show exception)))
117 exitWith (ExitFailure 1)
120 -- all error messages are propagated as exceptions
121 handleDyn (\dyn -> do
124 PhaseFailed _ code -> exitWith code
125 Interrupted -> exitWith (ExitFailure 1)
126 _ -> do hPutStrLn stderr (show (dyn :: GhcException))
127 exitWith (ExitFailure 1)
130 -- make sure we clean up after ourselves
131 later (do forget_it <- readIORef v_Keep_tmp_files
132 unless forget_it $ do
133 verb <- dynFlag verbosity
136 -- exceptions will be blocked while we clean the temporary files,
137 -- so there shouldn't be any difficulty if we receive further
140 -- install signal handlers
141 #ifndef mingw32_HOST_OS
142 main_thread <- myThreadId
143 let sig_handler = Catch (throwTo main_thread
144 (DynException (toDyn Interrupted)))
145 installHandler sigQUIT sig_handler Nothing
146 installHandler sigINT sig_handler Nothing
150 let (minusB_args, argv') = partition (prefixMatch "-B") argv
151 top_dir <- initSysTools minusB_args
153 -- Read the package configuration
154 conf_file <- getPackageConfigPath
155 readPackageConf conf_file
157 -- process all the other arguments, and get the source files
158 non_static <- processArgs static_flags argv' []
159 mode <- readIORef v_GhcMode
160 stop_flag <- readIORef v_GhcModeFlag
162 -- -O and --interactive are not a good combination
163 -- ditto with any kind of way selection
164 orig_opt_level <- readIORef v_OptLevel
165 when (orig_opt_level > 0 && mode == DoInteractive) $
166 do putStr "warning: -O conflicts with --interactive; -O turned off.\n"
167 writeIORef v_OptLevel 0
168 orig_ways <- readIORef v_Ways
169 when (notNull orig_ways && mode == DoInteractive) $
170 do throwDyn (UsageError
171 "--interactive can't be used with -prof, -ticky, -unreg or -smp.")
173 -- Find the build tag, and re-process the build-specific options.
174 -- Also add in flags for unregisterised compilation, if
175 -- GhcUnregisterised=YES.
176 way_opts <- findBuildTag
177 let unreg_opts | cGhcUnregisterised == "YES" = unregFlags
179 pkg_extra_opts <- getPackageExtraGhcOpts
180 extra_non_static <- processArgs static_flags
181 (unreg_opts ++ way_opts ++ pkg_extra_opts) []
183 -- give the static flags to hsc
184 static_opts <- buildStaticHscOpts
185 writeIORef v_Static_hsc_opts static_opts
187 -- build the default DynFlags (these may be adjusted on a per
188 -- module basis by OPTIONS pragmas and settings in the interpreter).
190 core_todo <- buildCoreToDo
191 stg_todo <- buildStgToDo
193 -- set the "global" HscLang. The HscLang can be further adjusted on a module
194 -- by module basis, using only the -fvia-C and -fasm flags. If the global
195 -- HscLang is not HscC or HscAsm, -fvia-C and -fasm have no effect.
196 dyn_flags <- getDynFlags
197 let lang = case mode of
198 DoInteractive -> HscInterpreted
199 _other -> hscLang dyn_flags
201 setDynFlags (dyn_flags{ coreToDo = core_todo,
204 -- leave out hscOutName for now
205 hscOutName = panic "Main.main:hscOutName not set",
209 -- the rest of the arguments are "dynamic"
210 srcs <- processArgs dynamic_flags (extra_non_static ++ non_static) []
212 -- save the "initial DynFlags" away
215 -- perform some checks of the options set / report unknowns.
218 verb <- dynFlag verbosity
220 -- Show the GHCi banner
222 when (mode == DoInteractive && verb >= 1) $
223 hPutStrLn stdout ghciWelcomeMsg
226 -- Display details of the configuration in verbose mode
228 (do hPutStr stderr "Glasgow Haskell Compiler, Version "
229 hPutStr stderr cProjectVersion
230 hPutStr stderr ", for Haskell 98, compiled by GHC version "
231 hPutStrLn stderr cBooterVersion)
234 (hPutStrLn stderr ("Using package config file: " ++ conf_file))
236 pkg_details <- readIORef v_Package_details
237 showPackages pkg_details
240 (hPutStrLn stderr ("Hsc static flags: " ++ unwords static_opts))
242 -- initialise the finder
243 pkg_avails <- getPackageInfo
244 initFinder pkg_avails
246 -- mkdependHS is special
247 when (mode == DoMkDependHS) beginMkDependHS
249 -- -ohi sanity checking
250 ohi <- readIORef v_Output_hi
252 (mode == DoMake || mode == DoInteractive || srcs `lengthExceeds` 1))
253 then throwDyn (UsageError "-ohi can only be used when compiling a single source file")
256 -- make/interactive require invoking the compilation manager
257 if (mode == DoMake) then beginMake srcs else do
258 if (mode == DoInteractive) then beginInteractive srcs else do
260 -- -o sanity checking
261 let real_srcs = filter isSourceFile srcs -- filters out .a and .o that might appear
262 o_file <- readIORef v_Output_file
263 if (real_srcs `lengthExceeds` 1 && isJust o_file && mode /= DoLink && mode /= DoMkDLL)
264 then throwDyn (UsageError "can't apply -o to multiple source files")
267 if null real_srcs then throwDyn (UsageError "no input files") else do
269 let compileFile src = do
272 exists <- doesFileExist src
274 throwDyn (CmdLineError ("file `" ++ src ++ "' does not exist"))
276 -- We compile in two stages, because the file may have an
277 -- OPTIONS pragma that affects the compilation pipeline (eg. -fvia-C)
278 let (basename, suffix) = splitFilename src
280 -- just preprocess (Haskell source only)
281 let src_and_suff = (src, getFileSuffix src)
282 let not_hs_file = not (haskellish_src_file src)
283 pp <- if not_hs_file || mode == StopBefore Hsc || mode == StopBefore HsPp
284 then return src_and_suff else do
285 phases <- genPipeline (StopBefore Hsc) stop_flag
286 False{-not persistent-} defaultHscLang
288 pipeLoop phases src_and_suff False{-no linking-} False{-no -o flag-}
291 -- rest of compilation
292 hsc_lang <- dynFlag hscLang
293 phases <- genPipeline mode stop_flag True hsc_lang pp
294 (r,_) <- pipeLoop phases pp (mode==DoLink || mode==DoMkDLL)
295 True{-use -o flag-} basename suffix
298 o_files <- mapM compileFile srcs
300 when (mode == DoMkDependHS) endMkDependHS
301 when (mode == DoLink) (doLink o_files)
302 when (mode == DoMkDLL) (doMkDLL o_files)
306 beginMake :: [String] -> IO ()
307 beginMake fileish_args
308 = do let (objs, mods) = partition objish_file fileish_args
309 mapM_ (add v_Ld_inputs) objs
312 [] -> throwDyn (UsageError "no input files")
313 _ -> do dflags <- getDynFlags
314 state <- cmInit Batch
315 graph <- cmDepAnal state dflags mods
316 (_, ok, _) <- cmLoadModules state dflags graph
317 when (not ok) (exitWith (ExitFailure 1))
321 beginInteractive :: [String] -> IO ()
323 beginInteractive = throwDyn (CmdLineError "not built for interactive use")
325 beginInteractive fileish_args
326 = do minus_ls <- readIORef v_Cmdline_libraries
328 let (objs, mods) = partition objish_file fileish_args
329 libs = map Object objs ++ map DLL minus_ls
331 state <- cmInit Interactive
332 interactiveUI state mods libs
335 checkOptions :: [String] -> IO ()
336 checkOptions srcs = do
337 -- complain about any unknown flags
338 let unknown_opts = [ f | f@('-':_) <- srcs ]
339 when (notNull unknown_opts) (unknownFlagsErr unknown_opts)
340 -- verify that output files point somewhere sensible.
342 -- and anything else that it might be worth checking for
343 -- before kicking of a compilation (pipeline).