1 {-# OPTIONS -fno-warn-incomplete-patterns #-}
2 -----------------------------------------------------------------------------
3 -- $Id: Main.hs,v 1.82 2001/08/03 20:40:43 sof Exp $
7 -- (c) Simon Marlow 2000
9 -----------------------------------------------------------------------------
11 -- with path so that ghc -M can find config.h
12 #include "../includes/config.h"
14 module Main (main) where
16 #include "HsVersions.h"
20 import InteractiveUI(ghciWelcomeMsg, interactiveUI)
24 import Finder ( initFinder )
25 import CompManager ( cmInit, cmLoadModule )
26 import HscTypes ( GhciMode(..) )
27 import Config ( cBooterVersion, cGhcUnregisterised, cProjectVersion )
28 import SysTools ( packageConfigPath, initSysTools, cleanTempFiles )
29 import Packages ( showPackages, mungePackagePaths )
30 import ParsePkgConf ( loadPackageConfig )
32 import DriverPipeline ( GhcMode(..), doLink, doMkDLL, genPipeline,
33 getGhcMode, pipeLoop, v_GhcMode
35 import DriverState ( buildCoreToDo, buildStgToDo, defaultHscLang,
36 findBuildTag, getPackageInfo, unregFlags,
37 v_Cmdline_libraries, v_Keep_tmp_files, v_Ld_inputs,
38 v_OptLevel, v_Output_file, v_Output_hi,
39 v_Package_details, v_Ways, getPackageExtraGhcOpts
41 import DriverFlags ( dynFlag, buildStaticHscOpts, dynamic_flags,
42 processArgs, static_flags)
44 import DriverMkDepend ( beginMkDependHS, endMkDependHS )
45 import DriverPhases ( Phase(Hsc, HCc), haskellish_src_file, objish_file )
47 import DriverUtil ( add, handle, handleDyn, later, splitFilename,
48 unknownFlagErr, getFileSuffix )
49 import CmdLineOpts ( dynFlag, defaultDynFlags, restoreDynFlags,
50 saveDynFlags, setDynFlags,
51 DynFlags(..), HscLang(..), v_Static_hsc_opts
56 import Panic ( GhcException(..), panic )
58 -- Standard Haskell libraries
60 import Directory ( doesFileExist )
61 import IOExts ( readIORef, writeIORef )
62 import Exception ( throwDyn, Exception(..) )
63 import System ( getArgs, exitWith, ExitCode(..) )
68 #ifndef mingw32_TARGET_OS
69 import Concurrent ( myThreadId )
70 #if __GLASGOW_HASKELL__ < 500
71 import Exception ( raiseInThread )
72 #define throwTo raiseInThread
74 import Exception ( throwTo )
77 import Posix ( Handler(Catch), installHandler, sigINT, sigQUIT )
78 import Dynamic ( toDyn )
82 -----------------------------------------------------------------------------
85 -- * -fglasgow-exts NO LONGER IMPLIES -package lang!!! (-fglasgow-exts is a
86 -- dynamic flag whereas -package is a static flag.)
88 -----------------------------------------------------------------------------
91 -- new mkdependHS doesn't support all the options that the old one did (-X et al.)
92 -- time commands when run with -v
96 -- Win32 support: proper signal handling
97 -- make sure OPTIONS in .hs file propogate to .hc file if -C or -keep-hc-file-too
98 -- reading the package configuration file is too slow
101 -----------------------------------------------------------------------------
102 -- Differences vs. old driver:
104 -- No more "Enter your Haskell program, end with ^D (on a line of its own):"
105 -- 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
116 -- an IO exception probably isn't our fault, so don't panic
117 IOException _ -> hPutStr stderr (show exception)
118 -- let exit exceptions bubble all the way out.
119 ExitException e -> exitWith e
120 _other -> hPutStr stderr (show (Panic (show exception)))
121 exitWith (ExitFailure 1)
124 -- all error messages are propagated as exceptions
125 handleDyn (\dyn -> case dyn of
126 PhaseFailed _phase code -> do
127 hPutStr stderr "\nCompilation had errors\n"
129 Interrupted -> exitWith (ExitFailure 1)
130 _ -> do hPutStrLn stderr (show (dyn :: GhcException))
131 exitWith (ExitFailure 1)
134 -- make sure we clean up after ourselves
135 later (do forget_it <- readIORef v_Keep_tmp_files
136 unless forget_it $ do
137 verb <- dynFlag verbosity
140 -- exceptions will be blocked while we clean the temporary files,
141 -- so there shouldn't be any difficulty if we receive further
144 -- install signal handlers
145 #ifndef mingw32_TARGET_OS
146 main_thread <- myThreadId
147 let sig_handler = Catch (throwTo main_thread
148 (DynException (toDyn Interrupted)))
149 installHandler sigQUIT sig_handler Nothing
150 installHandler sigINT sig_handler Nothing
154 let (minusB_args, argv') = partition (prefixMatch "-B") argv
155 top_dir <- initSysTools minusB_args
157 -- Read the package configuration
158 conf_file <- packageConfigPath
159 proto_pkg_details <- loadPackageConfig conf_file
160 let pkg_details = mungePackagePaths top_dir proto_pkg_details
161 writeIORef v_Package_details pkg_details
163 -- find the phase to stop after (i.e. -E, -C, -c, -S flags)
164 (flags2, mode, stop_flag) <- getGhcMode argv'
165 writeIORef v_GhcMode mode
167 -- process all the other arguments, and get the source files
168 non_static <- processArgs static_flags flags2 []
170 -- -O and --interactive are not a good combination
171 -- ditto with any kind of way selection
172 orig_opt_level <- readIORef v_OptLevel
173 when (orig_opt_level > 0 && mode == DoInteractive) $
174 do putStr "warning: -O conflicts with --interactive; -O turned off.\n"
175 writeIORef v_OptLevel 0
176 orig_ways <- readIORef v_Ways
177 when (not (null orig_ways) && mode == DoInteractive) $
178 do throwDyn (UsageError
179 "--interactive can't be used with -prof, -ticky, -unreg or -smp.")
181 -- Find the build tag, and re-process the build-specific options.
182 -- Also add in flags for unregisterised compilation, if
183 -- GhcUnregisterised=YES.
184 way_opts <- findBuildTag
185 let unreg_opts | cGhcUnregisterised == "YES" = unregFlags
187 pkg_extra_opts <- getPackageExtraGhcOpts
188 extra_non_static <- processArgs static_flags
189 (unreg_opts ++ way_opts ++ pkg_extra_opts) []
191 -- give the static flags to hsc
192 static_opts <- buildStaticHscOpts
193 writeIORef v_Static_hsc_opts static_opts
195 -- build the default DynFlags (these may be adjusted on a per
196 -- module basis by OPTIONS pragmas and settings in the interpreter).
198 core_todo <- buildCoreToDo
199 stg_todo <- buildStgToDo
201 -- set the "global" HscLang. The HscLang can be further adjusted on a module
202 -- by module basis, using only the -fvia-C and -fasm flags. If the global
203 -- HscLang is not HscC or HscAsm, -fvia-C and -fasm have no effect.
204 opt_level <- readIORef v_OptLevel
207 let lang = case mode of
208 StopBefore HCc -> HscC
209 DoInteractive -> HscInterpreted
210 _other | opt_level >= 1 -> HscC -- -O implies -fvia-C
211 | otherwise -> defaultHscLang
213 setDynFlags (defaultDynFlags{ coreToDo = core_todo,
216 -- leave out hscOutName for now
217 hscOutName = panic "Main.main:hscOutName not set",
219 verbosity = case mode of
225 -- the rest of the arguments are "dynamic"
226 srcs <- processArgs dynamic_flags (extra_non_static ++ non_static) []
228 -- save the "initial DynFlags" away
231 -- complain about any unknown flags
232 mapM unknownFlagErr [ f | f@('-':_) <- srcs ]
234 verb <- dynFlag verbosity
236 -- Show the GHCi banner
238 when (mode == DoInteractive && verb >= 1) $
239 hPutStrLn stdout ghciWelcomeMsg
242 -- Display details of the configuration in verbose mode
244 (do hPutStr stderr "Glasgow Haskell Compiler, Version "
245 hPutStr stderr cProjectVersion
246 hPutStr stderr ", for Haskell 98, compiled by GHC version "
247 hPutStrLn stderr cBooterVersion)
250 (hPutStrLn stderr ("Using package config file: " ++ conf_file))
253 (hPutStrLn stderr ("Hsc static flags: " ++ unwords static_opts))
255 showPackages pkg_details
257 -- initialise the finder
258 pkg_avails <- getPackageInfo
259 initFinder pkg_avails
261 -- mkdependHS is special
262 when (mode == DoMkDependHS) beginMkDependHS
264 -- -ohi sanity checking
265 ohi <- readIORef v_Output_hi
267 (mode == DoMake || mode == DoInteractive || length srcs > 1))
268 then throwDyn (UsageError "-ohi can only be used when compiling a single source file")
271 -- make/interactive require invoking the compilation manager
272 if (mode == DoMake) then beginMake srcs else do
273 if (mode == DoInteractive) then beginInteractive srcs else do
275 -- -o sanity checking
276 o_file <- readIORef v_Output_file
277 if (length srcs > 1 && isJust o_file && mode /= DoLink && mode /= DoMkDLL)
278 then throwDyn (UsageError "can't apply -o to multiple source files")
281 if null srcs then throwDyn (UsageError "no input files") else do
283 let compileFile src = do
286 exists <- doesFileExist src
288 throwDyn (CmdLineError ("file `" ++ src ++ "' does not exist"))
290 -- We compile in two stages, because the file may have an
291 -- OPTIONS pragma that affects the compilation pipeline (eg. -fvia-C)
292 let (basename, suffix) = splitFilename src
294 -- just preprocess (Haskell source only)
295 let src_and_suff = (src, getFileSuffix src)
296 pp <- if not (haskellish_src_file src) || mode == StopBefore Hsc
297 then return src_and_suff else do
298 phases <- genPipeline (StopBefore Hsc) stop_flag
299 False{-not persistent-} defaultHscLang
301 pipeLoop phases src_and_suff False{-no linking-} False{-no -o flag-}
304 -- rest of compilation
305 hsc_lang <- dynFlag hscLang
306 phases <- genPipeline mode stop_flag True hsc_lang pp
307 (r,_) <- pipeLoop phases pp (mode==DoLink || mode==DoMkDLL)
308 True{-use -o flag-} basename suffix
311 o_files <- mapM compileFile srcs
313 when (mode == DoMkDependHS) endMkDependHS
314 when (mode == DoLink) (doLink o_files)
315 when (mode == DoMkDLL) (doMkDLL o_files)
319 beginMake :: [String] -> IO ()
320 beginMake fileish_args
321 = do let (objs, mods) = partition objish_file fileish_args
322 mapM (add v_Ld_inputs) objs
325 [] -> throwDyn (UsageError "no input files")
326 mod -> do state <- cmInit Batch
327 (_, ok, _) <- cmLoadModule state mods
328 when (not ok) (exitWith (ExitFailure 1))
332 beginInteractive :: [String] -> IO ()
334 beginInteractive = throwDyn (CmdLineError "not built for interactive use")
336 beginInteractive fileish_args
337 = do minus_ls <- readIORef v_Cmdline_libraries
339 let (objs, mods) = partition objish_file fileish_args
340 libs = map Left objs ++ map Right minus_ls
342 state <- cmInit Interactive
343 interactiveUI state mods libs