1 {-# OPTIONS -fno-warn-incomplete-patterns -optc-DNON_POSIX_SOURCE #-}
3 -----------------------------------------------------------------------------
4 -- $Id: Main.hs,v 1.120 2003/05/19 15:39:18 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"
21 import InteractiveUI( ghciWelcomeMsg, interactiveUI )
25 import CompManager ( cmInit, cmLoadModules, cmDepAnal )
26 import HscTypes ( GhciMode(..) )
27 import Config ( cBooterVersion, cGhcUnregisterised, cProjectVersion )
28 import SysTools ( getPackageConfigPath, initSysTools, cleanTempFiles )
29 import Packages ( showPackages, getPackageConfigMap, basePackage,
32 import DriverPipeline ( staticLink, doMkDLL, genPipeline, pipeLoop )
33 import DriverState ( buildCoreToDo, buildStgToDo,
35 getPackageExtraGhcOpts, unregFlags,
36 v_GhcMode, v_GhcModeFlag, GhcMode(..),
37 v_Keep_tmp_files, v_Ld_inputs, v_Ways,
38 v_OptLevel, v_Output_file, v_Output_hi,
39 readPackageConf, verifyOutputFiles, v_NoLink,
42 import DriverFlags ( buildStaticHscOpts,
43 dynamic_flags, processArgs, static_flags)
45 import DriverMkDepend ( beginMkDependHS, endMkDependHS )
46 import DriverPhases ( Phase(HsPp, Hsc), haskellish_src_file, objish_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, installSignalHandlers )
60 import DATA_IOREF ( readIORef, writeIORef )
61 import EXCEPTION ( throwDyn, Exception(..),
62 AsyncException(StackOverflow) )
64 -- Standard Haskell libraries
66 import Directory ( doesFileExist )
67 import System ( getArgs, exitWith, ExitCode(..) )
72 -----------------------------------------------------------------------------
75 -- new mkdependHS doesn't support all the options that the old one did (-X et al.)
76 -- time commands when run with -v
80 -- Win32 support: proper signal handling
81 -- make sure OPTIONS in .hs file propogate to .hc file if -C or -keep-hc-file-too
82 -- reading the package configuration file is too slow
85 -----------------------------------------------------------------------------
86 -- Differences vs. old driver:
88 -- No more "Enter your Haskell program, end with ^D (on a line of its own):"
89 -- consistency checking removed (may do this properly later)
92 -----------------------------------------------------------------------------
96 -- top-level exception handler: any unrecognised exception is a compiler bug.
97 handle (\exception -> do
100 -- an IO exception probably isn't our fault, so don't panic
101 IOException _ -> hPutStr stderr (show exception)
102 AsyncException StackOverflow ->
103 hPutStrLn stderr "stack overflow: use +RTS -K<size> \
105 _other -> hPutStr stderr (show (Panic (show exception)))
106 exitWith (ExitFailure 1)
109 -- all error messages are propagated as exceptions
110 handleDyn (\dyn -> do
113 PhaseFailed _ code -> exitWith code
114 Interrupted -> exitWith (ExitFailure 1)
115 _ -> do hPutStrLn stderr (show (dyn :: GhcException))
116 exitWith (ExitFailure 1)
119 -- make sure we clean up after ourselves
120 later (do forget_it <- readIORef v_Keep_tmp_files
121 unless forget_it $ do
122 verb <- dynFlag verbosity
125 -- exceptions will be blocked while we clean the temporary files,
126 -- so there shouldn't be any difficulty if we receive further
129 installSignalHandlers
132 let (minusB_args, argv') = partition (prefixMatch "-B") argv
133 top_dir <- initSysTools minusB_args
135 -- Read the package configuration
136 conf_file <- getPackageConfigPath
137 readPackageConf conf_file
139 -- Process all the other arguments, and get the source files
140 non_static <- processArgs static_flags argv' []
141 mode <- readIORef v_GhcMode
143 -- -O and --interactive are not a good combination
144 -- ditto with any kind of way selection
145 orig_opt_level <- readIORef v_OptLevel
146 when (orig_opt_level > 0 && mode == DoInteractive) $
147 do putStr "warning: -O conflicts with --interactive; -O turned off.\n"
148 writeIORef v_OptLevel 0
149 orig_ways <- readIORef v_Ways
150 when (notNull orig_ways && mode == DoInteractive) $
151 do throwDyn (UsageError
152 "--interactive can't be used with -prof, -ticky, -unreg or -smp.")
154 -- Find the build tag, and re-process the build-specific options.
155 -- Also add in flags for unregisterised compilation, if
156 -- GhcUnregisterised=YES.
157 way_opts <- findBuildTag
158 let unreg_opts | cGhcUnregisterised == "YES" = unregFlags
160 pkg_extra_opts <- getPackageExtraGhcOpts
161 extra_non_static <- processArgs static_flags
162 (unreg_opts ++ way_opts ++ pkg_extra_opts) []
164 -- give the static flags to hsc
165 static_opts <- buildStaticHscOpts
166 writeIORef v_Static_hsc_opts static_opts
168 -- build the default DynFlags (these may be adjusted on a per
169 -- module basis by OPTIONS pragmas and settings in the interpreter).
171 core_todo <- buildCoreToDo
172 stg_todo <- buildStgToDo
174 -- set the "global" HscLang. The HscLang can be further adjusted on a module
175 -- by module basis, using only the -fvia-C and -fasm flags. If the global
176 -- HscLang is not HscC or HscAsm, -fvia-C and -fasm have no effect.
177 dyn_flags <- getDynFlags
178 build_tag <- readIORef v_Build_tag
179 let lang = case mode of
180 DoInteractive -> HscInterpreted
181 _other | build_tag /= "" -> HscC
182 | otherwise -> hscLang dyn_flags
183 -- for ways other that the normal way, we must
186 setDynFlags (dyn_flags{ coreToDo = core_todo,
189 -- leave out hscOutName for now
190 hscOutName = panic "Main.main:hscOutName not set",
194 -- The rest of the arguments are "dynamic"
195 -- Leftover ones are presumably files
196 fileish_args <- processArgs dynamic_flags (extra_non_static ++ non_static) []
198 -- We split out the object files (.o, .dll) and add them
199 -- to v_Ld_inputs for use by the linker
200 let (objs, srcs) = partition objish_file fileish_args
201 mapM_ (add v_Ld_inputs) objs
203 ---------------- Display banners and configuration -----------
204 showBanners mode conf_file static_opts
206 ---------------- Final sanity checking -----------
207 checkOptions mode srcs objs
209 ---------------- Do the business -----------
211 DoMake -> doMake srcs
212 DoMkDependHS -> do { beginMkDependHS ;
213 compileFiles mode srcs;
215 StopBefore p -> do { compileFiles mode srcs; return () }
216 DoMkDLL -> do { o_files <- compileFiles mode srcs;
218 DoLink -> do { o_files <- compileFiles mode srcs;
219 omit_linking <- readIORef v_NoLink;
220 when (not omit_linking)
221 (staticLink o_files [basePackage, haskell98Package]) }
222 -- We always link in the base package in one-shot linking.
223 -- Any other packages required must be given using -package
224 -- options on the command-line.
226 DoInteractive -> throwDyn (CmdLineError "not built for interactive use")
228 DoInteractive -> interactiveUI srcs
231 --------------------------------------------------------------------------------------
232 checkOptions :: GhcMode -> [String] -> [String] -> IO ()
233 -- Final sanity checking before kicking of a compilation (pipeline).
234 checkOptions mode srcs objs = do
236 ohi <- readIORef v_Output_hi
238 (mode == DoMake || mode == DoInteractive || srcs `lengthExceeds` 1))
239 then throwDyn (UsageError "-ohi can only be used when compiling a single source file")
242 -- -o sanity checking
243 o_file <- readIORef v_Output_file
244 if (srcs `lengthExceeds` 1 && isJust o_file && mode /= DoLink && mode /= DoMkDLL)
245 then throwDyn (UsageError "can't apply -o to multiple source files")
248 -- Check that there are some input files (except in the interactive case)
249 if null srcs && null objs && mode /= DoInteractive
250 then throwDyn (UsageError "no input files")
253 -- Complain about any unknown flags
254 let unknown_opts = [ f | f@('-':_) <- srcs ]
255 when (notNull unknown_opts) (unknownFlagsErr unknown_opts)
257 -- Verify that output files point somewhere sensible.
261 --------------------------------------------------------------------------------------
262 compileFiles :: GhcMode
263 -> [String] -- Source files
264 -> IO [String] -- Object files
265 compileFiles mode srcs = do
266 stop_flag <- readIORef v_GhcModeFlag
268 -- Do the business; save the DynFlags at the
269 -- start, so we can restore them before each file
271 mapM (compileFile mode stop_flag) srcs
274 compileFile mode stop_flag src = do
277 exists <- doesFileExist src
279 throwDyn (CmdLineError ("file `" ++ src ++ "' does not exist"))
281 -- We compile in two stages, because the file may have an
282 -- OPTIONS pragma that affects the compilation pipeline (eg. -fvia-C)
283 let (basename, suffix) = splitFilename src
285 -- just preprocess (Haskell source only)
286 let src_and_suff = (src, getFileSuffix src)
287 let not_hs_file = not (haskellish_src_file src)
288 pp <- if not_hs_file || mode == StopBefore Hsc || mode == StopBefore HsPp
289 then return src_and_suff else do
290 phases <- genPipeline (StopBefore Hsc) stop_flag
291 False{-not persistent-} defaultHscLang
293 pipeLoop phases src_and_suff False{-no linking-} False{-no -o flag-}
296 -- rest of compilation
297 hsc_lang <- dynFlag hscLang
298 phases <- genPipeline mode stop_flag True hsc_lang pp
299 (r,_) <- pipeLoop phases pp (mode==DoLink || mode==DoMkDLL)
300 True{-use -o flag-} basename suffix
304 --------------------------------------------------------------------------------------
305 doMake :: [String] -> IO ()
306 doMake [] = throwDyn (UsageError "no input files")
308 dflags <- getDynFlags
309 state <- cmInit Batch
310 graph <- cmDepAnal state dflags srcs
311 (_, ok_flag, _) <- cmLoadModules state dflags graph
312 when (failed ok_flag) (exitWith (ExitFailure 1))
317 --------------------------------------------------------------------------------------
318 showBanners :: GhcMode -> FilePath -> [String] -> IO ()
319 showBanners mode conf_file static_opts = do
320 verb <- dynFlag verbosity
322 -- Show the GHCi banner
324 when (mode == DoInteractive && verb >= 1) $
325 hPutStrLn stdout ghciWelcomeMsg
328 -- Display details of the configuration in verbose mode
330 (do hPutStr stderr "Glasgow Haskell Compiler, Version "
331 hPutStr stderr cProjectVersion
332 hPutStr stderr ", for Haskell 98, compiled by GHC version "
333 hPutStrLn stderr cBooterVersion)
336 (hPutStrLn stderr ("Using package config file: " ++ conf_file))
338 pkg_details <- getPackageConfigMap
339 showPackages pkg_details
342 (hPutStrLn stderr ("Hsc static flags: " ++ unwords static_opts))