1 {-# OPTIONS -fno-warn-incomplete-patterns #-}
2 -----------------------------------------------------------------------------
3 -- $Id: Main.hs,v 1.70 2001/06/14 12:50:06 simonpj 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 CmStaticInfo ( GhciMode(..), PackageConfig(..) )
27 import Config ( cBooterVersion, cGhcUnregisterised, cProjectVersion )
28 import SysTools ( packageConfigPath, initSysTools, cleanTempFiles )
29 import ParsePkgConf ( parsePkgConf )
31 import DriverPipeline ( GhcMode(..), doLink, doMkDLL, genPipeline,
32 getGhcMode, pipeLoop, v_GhcMode
34 import DriverState ( buildCoreToDo, buildStgToDo, defaultHscLang,
35 findBuildTag, getPackageInfo, unregFlags, v_Cmdline_libraries,
36 v_Keep_tmp_files, v_Ld_inputs, v_OptLevel, v_Output_file,
37 v_Output_hi, v_Package_details, v_Ways
39 import DriverFlags ( dynFlag, buildStaticHscOpts, dynamic_flags, processArgs, static_flags)
41 import DriverMkDepend ( beginMkDependHS, endMkDependHS )
42 import DriverPhases ( Phase(Hsc, HCc), haskellish_src_file, objish_file )
44 import DriverUtil ( add, handle, handleDyn, later, splitFilename, unknownFlagErr, my_prefix_match )
45 import CmdLineOpts ( dynFlag,
46 DynFlags(verbosity, stgToDo, hscOutName, hscLang, coreToDo),
47 HscLang(HscInterpreted, HscC),
48 defaultDynFlags, restoreDynFlags, saveDynFlags, setDynFlags,
54 import Panic ( GhcException(..), panic )
56 -- Standard Haskell libraries
58 import Concurrent ( myThreadId, throwTo )
59 import Directory ( doesFileExist )
60 import IOExts ( readIORef, writeIORef )
61 import Exception ( throwTo, throwDyn, Exception(DynException) )
62 import System ( getArgs, exitWith, ExitCode(..) )
64 #ifndef mingw32_TARGET_OS
65 import Posix ( Handler(Catch), installHandler, sigINT, sigQUIT )
66 import Dynamic ( toDyn )
74 -----------------------------------------------------------------------------
77 -- * -fglasgow-exts NO LONGER IMPLIES -package lang!!! (-fglasgow-exts is a
78 -- dynamic flag whereas -package is a static flag.)
80 -----------------------------------------------------------------------------
83 -- new mkdependHS doesn't support all the options that the old one did (-X et al.)
84 -- time commands when run with -v
88 -- Win32 support: proper signal handling
89 -- make sure OPTIONS in .hs file propogate to .hc file if -C or -keep-hc-file-too
90 -- reading the package configuration file is too slow
93 -----------------------------------------------------------------------------
94 -- Differences vs. old driver:
96 -- No more "Enter your Haskell program, end with ^D (on a line of its own):"
97 -- consistency checking removed (may do this properly later)
101 -----------------------------------------------------------------------------
105 -- top-level exception handler: any unrecognised exception is a compiler bug.
106 handle (\exception -> do hPutStr stderr (show (Panic (show exception)))
107 exitWith (ExitFailure 1)
110 -- all error messages are propagated as exceptions
111 handleDyn (\dyn -> case dyn of
112 PhaseFailed _phase code -> exitWith code
113 Interrupted -> exitWith (ExitFailure 1)
114 _ -> do hPutStrLn stderr (show (dyn :: GhcException))
115 exitWith (ExitFailure 1)
118 -- make sure we clean up after ourselves
119 later (do forget_it <- readIORef v_Keep_tmp_files
120 unless forget_it $ do
121 verb <- dynFlag verbosity
124 -- exceptions will be blocked while we clean the temporary files,
125 -- so there shouldn't be any difficulty if we receive further
128 -- install signal handlers
129 main_thread <- myThreadId
130 #ifndef mingw32_TARGET_OS
131 let sig_handler = Catch (throwTo main_thread
132 (DynException (toDyn Interrupted)))
133 installHandler sigQUIT sig_handler Nothing
134 installHandler sigINT sig_handler Nothing
139 -- grab any -B options from the command line first
140 let (top_dir, argv') = getTopDir argv
144 -- read the package configuration
145 conf_file <- packageConfigPath
146 r <- parsePkgConf conf_file
148 Left err -> throwDyn (InstallationError (showSDoc err));
149 Right pkg_details -> do
151 writeIORef v_Package_details (mungePackagePaths top_dir pkg_details)
153 -- find the phase to stop after (i.e. -E, -C, -c, -S flags)
154 (flags2, mode, stop_flag) <- getGhcMode argv'
155 writeIORef v_GhcMode mode
157 -- Show the GHCi banner?
159 when (mode == DoInteractive) $
160 hPutStrLn stdout ghciWelcomeMsg
163 -- process all the other arguments, and get the source files
164 non_static <- processArgs static_flags flags2 []
166 -- -O and --interactive are not a good combination
167 -- ditto with any kind of way selection
168 orig_opt_level <- readIORef v_OptLevel
169 when (orig_opt_level > 0 && mode == DoInteractive) $
170 do putStr "warning: -O conflicts with --interactive; -O turned off.\n"
171 writeIORef v_OptLevel 0
172 orig_ways <- readIORef v_Ways
173 when (not (null orig_ways) && mode == DoInteractive) $
174 do throwDyn (UsageError
175 "--interactive can't be used with -prof, -ticky, -unreg or -smp.")
177 -- Find the build tag, and re-process the build-specific options.
178 -- Also add in flags for unregisterised compilation, if
179 -- GhcUnregisterised=YES.
180 way_opts <- findBuildTag
181 let unreg_opts | cGhcUnregisterised == "YES" = unregFlags
183 way_non_static <- processArgs static_flags (unreg_opts ++ way_opts) []
185 -- give the static flags to hsc
186 static_opts <- buildStaticHscOpts
187 writeIORef v_Static_hsc_opts static_opts
189 -- build the default DynFlags (these may be adjusted on a per
190 -- module basis by OPTIONS pragmas and settings in the interpreter).
192 core_todo <- buildCoreToDo
193 stg_todo <- buildStgToDo
195 -- set the "global" HscLang. The HscLang can be further adjusted on a module
196 -- by module basis, using only the -fvia-C and -fasm flags. If the global
197 -- HscLang is not HscC or HscAsm, -fvia-C and -fasm have no effect.
198 opt_level <- readIORef v_OptLevel
201 let lang = case mode of
202 StopBefore HCc -> HscC
203 DoInteractive -> HscInterpreted
204 _other | opt_level >= 1 -> HscC -- -O implies -fvia-C
205 | otherwise -> defaultHscLang
207 setDynFlags (defaultDynFlags{ coreToDo = core_todo,
210 -- leave out hscOutName for now
211 hscOutName = panic "Main.main:hscOutName not set",
213 verbosity = case mode of
219 -- the rest of the arguments are "dynamic"
220 srcs <- processArgs dynamic_flags (way_non_static ++ non_static) []
222 -- save the "initial DynFlags" away
225 -- complain about any unknown flags
226 mapM unknownFlagErr [ f | f@('-':_) <- srcs ]
228 verb <- dynFlag verbosity
231 (do hPutStr stderr "Glasgow Haskell Compiler, Version "
232 hPutStr stderr cProjectVersion
233 hPutStr stderr ", for Haskell 98, compiled by GHC version "
234 hPutStrLn stderr cBooterVersion)
237 (hPutStrLn stderr ("Using package config file: " ++ conf_file))
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 || length srcs > 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 o_file <- readIORef v_Output_file
262 if (length srcs > 1 && isJust o_file && mode /= DoLink && mode /= DoMkDLL)
263 then throwDyn (UsageError "can't apply -o to multiple source files")
266 if null srcs then throwDyn (UsageError "no input files") else do
268 let compileFile src = do
271 exists <- doesFileExist src
273 throwDyn (CmdLineError ("file `" ++ src ++ "' does not exist"))
275 -- We compile in two stages, because the file may have an
276 -- OPTIONS pragma that affects the compilation pipeline (eg. -fvia-C)
277 let (basename, suffix) = splitFilename src
279 -- just preprocess (Haskell source only)
280 pp <- if not (haskellish_src_file src) || mode == StopBefore Hsc
281 then return src else do
282 phases <- genPipeline (StopBefore Hsc) stop_flag
283 False{-not persistent-} defaultHscLang src
284 pipeLoop phases src False{-no linking-} False{-no -o flag-}
287 -- rest of compilation
288 hsc_lang <- dynFlag hscLang
289 phases <- genPipeline mode stop_flag True hsc_lang pp
290 r <- pipeLoop phases pp (mode==DoLink || mode==DoMkDLL) True{-use -o flag-}
294 o_files <- mapM compileFile srcs
296 when (mode == DoMkDependHS) endMkDependHS
297 when (mode == DoLink) (doLink o_files)
298 when (mode == DoMkDLL) (doMkDLL o_files)
301 -- grab the last -B option on the command line, and
302 -- set topDir to its value.
303 getTopDir :: [String] -> (String, [String])
305 | null minusbs = throwDyn (InstallationError ("missing -B<dir> option"))
306 | otherwise = (drop 2 (last minusbs), others)
308 (minusbs, others) = partition (prefixMatch "-B") args
311 -- replace the string "$libdir" at the beginning of a path with the
312 -- current libdir (obtained from the -B option).
313 mungePackagePaths top_dir ps = map munge_pkg ps
315 munge_pkg p = p{ import_dirs = munge_paths (import_dirs p),
316 include_dirs = munge_paths (include_dirs p),
317 library_dirs = munge_paths (library_dirs p) }
319 munge_paths = map munge_path
322 | Just p' <- my_prefix_match "$libdir" p = top_dir ++ p'
323 | otherwise = trace ("not: " ++ p) p
326 beginMake :: [String] -> IO ()
327 beginMake fileish_args
328 = do let (objs, mods) = partition objish_file fileish_args
329 mapM (add v_Ld_inputs) objs
332 [] -> throwDyn (UsageError "no input files")
333 [mod] -> do state <- cmInit Batch
334 cmLoadModule state mod
336 _ -> throwDyn (UsageError "only one module allowed with --make")
339 beginInteractive :: [String] -> IO ()
341 beginInteractive = throwDyn (CmdLineError "not built for interactive use")
343 beginInteractive fileish_args
344 = do minus_ls <- readIORef v_Cmdline_libraries
346 let (objs, mods) = partition objish_file fileish_args
347 libs = map Left objs ++ map Right minus_ls
349 state <- cmInit Interactive
351 [] -> interactiveUI state Nothing libs
352 [mod] -> interactiveUI state (Just mod) libs
353 _ -> throwDyn (UsageError
354 "only one module allowed with --interactive")