1 {-# OPTIONS -fno-warn-incomplete-patterns -optc-DNON_POSIX_SOURCE #-}
3 -----------------------------------------------------------------------------
4 -- $Id: Main.hs,v 1.144 2005/01/28 12:55:38 simonmar Exp $
8 -- (c) The University of Glasgow 2002
10 -----------------------------------------------------------------------------
12 module Main (main) where
14 #include "HsVersions.h"
17 import InteractiveUI( ghciWelcomeMsg, interactiveUI )
21 import CompManager ( cmInit, cmLoadModules, cmDepAnal )
22 import HscTypes ( GhciMode(..) )
23 import Config ( cBooterVersion, cGhcUnregisterised, cProjectVersion )
24 import SysTools ( initSysTools, cleanTempFiles, normalisePath )
25 import Packages ( dumpPackages, initPackages, haskell98PackageId, PackageIdH(..) )
26 import DriverPipeline ( staticLink, doMkDLL, compileFile )
27 import DriverState ( isLinkMode, isMakeMode, isInteractiveMode,
28 isCompManagerMode, isInterpretiveMode,
29 buildStgToDo, findBuildTag, unregFlags,
30 v_GhcMode, v_GhcModeFlag, GhcMode(..),
31 v_Keep_tmp_files, v_Ld_inputs, v_Ways,
32 v_Output_file, v_Output_hi,
33 verifyOutputFiles, v_NoLink
37 import DriverMkDepend ( doMkDependHS )
38 import DriverPhases ( isSourceFilename )
40 import DriverUtil ( add, handle, handleDyn, later, unknownFlagsErr )
41 import CmdLineOpts ( DynFlags(..), HscTarget(..), v_Static_hsc_opts,
43 import BasicTypes ( failed )
46 import Panic ( GhcException(..), panic, installSignalHandlers )
48 import DATA_IOREF ( readIORef, writeIORef )
49 import EXCEPTION ( throwDyn, Exception(..),
50 AsyncException(StackOverflow) )
52 -- Standard Haskell libraries
54 import Directory ( doesFileExist )
55 import System ( getArgs, exitWith, ExitCode(..) )
60 -----------------------------------------------------------------------------
63 -- new mkdependHS doesn't support all the options that the old one did (-X et al.)
64 -- time commands when run with -v
68 -- Win32 support: proper signal handling
69 -- make sure OPTIONS in .hs file propogate to .hc file if -C or -keep-hc-file-too
70 -- reading the package configuration file is too slow
73 -----------------------------------------------------------------------------
74 -- Differences vs. old driver:
76 -- No more "Enter your Haskell program, end with ^D (on a line of its own):"
77 -- consistency checking removed (may do this properly later)
80 -----------------------------------------------------------------------------
84 -- top-level exception handler: any unrecognised exception is a compiler bug.
85 handle (\exception -> do
88 -- an IO exception probably isn't our fault, so don't panic
89 IOException _ -> hPutStrLn stderr (show exception)
90 AsyncException StackOverflow ->
91 hPutStrLn stderr "stack overflow: use +RTS -K<size> to increase it"
92 _other -> hPutStr stderr (show (Panic (show exception)))
93 exitWith (ExitFailure 1)
96 -- all error messages are propagated as exceptions
100 PhaseFailed _ code -> exitWith code
101 Interrupted -> exitWith (ExitFailure 1)
102 _ -> do hPutStrLn stderr (show (dyn :: GhcException))
103 exitWith (ExitFailure 1)
106 installSignalHandlers
109 let (minusB_args, argv') = partition (prefixMatch "-B") argv
110 top_dir <- initSysTools minusB_args
112 -- Process all the other arguments, and get the source files
113 non_static <- processStaticFlags argv'
114 mode <- readIORef v_GhcMode
116 -- -O and --interactive are not a good combination
117 -- ditto with any kind of way selection
118 orig_ways <- readIORef v_Ways
119 when (notNull orig_ways && isInterpretiveMode mode) $
120 do throwDyn (UsageError
121 "--interactive can't be used with -prof, -ticky, -unreg or -smp.")
123 -- Find the build tag, and re-process the build-specific options.
124 -- Also add in flags for unregisterised compilation, if
125 -- GhcUnregisterised=YES.
126 way_opts <- findBuildTag
127 let unreg_opts | cGhcUnregisterised == "YES" = unregFlags
129 extra_non_static <- processStaticFlags (unreg_opts ++ way_opts)
131 -- Give the static flags to hsc
132 static_opts <- buildStaticHscOpts
133 writeIORef v_Static_hsc_opts static_opts
135 -- build the default DynFlags (these may be adjusted on a per
136 -- module basis by OPTIONS pragmas and settings in the interpreter).
138 stg_todo <- buildStgToDo
140 -- set the "global" HscTarget. The HscTarget can be further adjusted on a module
141 -- by module basis, using only the -fvia-C and -fasm flags. If the global
142 -- HscTarget is not HscC or HscAsm, -fvia-C and -fasm have no effect.
143 let dflags0 = defaultDynFlags
144 let lang = case mode of
145 DoInteractive -> HscInterpreted
146 DoEval _ -> HscInterpreted
147 _other -> hscTarget dflags0
149 let dflags1 = dflags0{ stgToDo = stg_todo,
151 -- leave out hscOutName for now
152 hscOutName = panic "Main.main:hscOutName not set",
153 verbosity = case mode of
158 -- The rest of the arguments are "dynamic"
159 -- Leftover ones are presumably files
160 (dflags2, fileish_args) <- processDynamicFlags
161 (extra_non_static ++ non_static) dflags1
163 -- make sure we clean up after ourselves
164 later (do forget_it <- readIORef v_Keep_tmp_files
165 unless forget_it $ do
166 cleanTempFiles dflags2
168 -- exceptions will be blocked while we clean the temporary files,
169 -- so there shouldn't be any difficulty if we receive further
172 -- Read the package config(s), and process the package-related
173 -- command-line flags
174 dflags <- initPackages dflags2
178 We split out the object files (.o, .dll) and add them
179 to v_Ld_inputs for use by the linker.
181 The following things should be considered compilation manager inputs:
183 - haskell source files (strings ending in .hs, .lhs or other
184 haskellish extension),
186 - module names (not forgetting hierarchical module names),
188 - and finally we consider everything not containing a '.' to be
189 a comp manager input, as shorthand for a .hs or .lhs filename.
191 Everything else is considered to be a linker object, and passed
192 straight through to the linker.
194 looks_like_an_input m = isSourceFilename m
195 || looksLikeModuleName m
198 -- To simplify the handling of filepaths, we normalise all filepaths right
199 -- away - e.g., for win32 platforms, backslashes are converted
200 -- into forward slashes.
201 normal_fileish_paths = map normalisePath fileish_args
202 (srcs, objs) = partition looks_like_an_input normal_fileish_paths
204 -- Note: have v_Ld_inputs maintain the order in which 'objs' occurred on
206 mapM_ (add v_Ld_inputs) (reverse objs)
208 ---------------- Display banners and configuration -----------
209 showBanners mode dflags static_opts
211 ---------------- Final sanity checking -----------
212 checkOptions mode srcs objs
214 ---------------- Do the business -----------
216 -- Always link in the haskell98 package for static linking. Other
217 -- packages have to be specified via the -package flag.
219 | ExtPackage h98_id <- haskell98PackageId (pkgState dflags) = [h98_id]
223 DoMake -> doMake dflags srcs
224 DoMkDependHS -> doMkDependHS dflags srcs
225 StopBefore p -> do { compileFiles mode dflags srcs; return () }
226 DoMkDLL -> do { o_files <- compileFiles mode dflags srcs;
227 doMkDLL dflags o_files link_pkgs }
228 DoLink -> do { o_files <- compileFiles mode dflags srcs;
229 omit_linking <- readIORef v_NoLink;
230 when (not omit_linking)
231 (staticLink dflags o_files link_pkgs) }
234 DoInteractive -> noInteractiveError
235 DoEval _ -> noInteractiveError
237 noInteractiveError = throwDyn (CmdLineError "not built for interactive use")
239 DoInteractive -> interactiveUI dflags srcs Nothing
240 DoEval expr -> interactiveUI dflags srcs (Just expr)
243 -- -----------------------------------------------------------------------------
244 -- Option sanity checks
246 checkOptions :: GhcMode -> [String] -> [String] -> IO ()
247 -- Final sanity checking before kicking off a compilation (pipeline).
248 checkOptions mode srcs objs = do
249 -- Complain about any unknown flags
250 let unknown_opts = [ f | f@('-':_) <- srcs ]
251 when (notNull unknown_opts) (unknownFlagsErr unknown_opts)
254 ohi <- readIORef v_Output_hi
256 (isCompManagerMode mode || srcs `lengthExceeds` 1))
257 then throwDyn (UsageError "-ohi can only be used when compiling a single source file")
260 -- -o sanity checking
261 o_file <- readIORef v_Output_file
262 if (srcs `lengthExceeds` 1 && isJust o_file && not (isLinkMode mode))
263 then throwDyn (UsageError "can't apply -o to multiple source files")
266 -- Check that there are some input files
267 -- (except in the interactive case)
268 if null srcs && null objs && not (isInterpretiveMode mode)
269 then throwDyn (UsageError "no input files")
272 -- Verify that output files point somewhere sensible.
275 -- -----------------------------------------------------------------------------
276 -- Compile files in one-shot mode.
278 compileFiles :: GhcMode
280 -> [String] -- Source files
281 -> IO [String] -- Object files
282 compileFiles mode dflags srcs = mapM (compileFile mode dflags) srcs
285 -- ----------------------------------------------------------------------------
288 doMake :: DynFlags -> [String] -> IO ()
289 doMake dflags [] = throwDyn (UsageError "no input files")
290 doMake dflags srcs = do
291 state <- cmInit Batch dflags
292 graph <- cmDepAnal state srcs
293 (_, ok_flag, _) <- cmLoadModules state graph
294 when (failed ok_flag) (exitWith (ExitFailure 1))
297 -- ---------------------------------------------------------------------------
298 -- Various banners and verbosity output.
300 showBanners :: GhcMode -> DynFlags -> [String] -> IO ()
301 showBanners mode dflags static_opts = do
302 let verb = verbosity dflags
304 -- Show the GHCi banner
306 when (isInteractiveMode mode && verb >= 1) $
307 hPutStrLn stdout ghciWelcomeMsg
310 -- Display details of the configuration in verbose mode
312 do hPutStr stderr "Glasgow Haskell Compiler, Version "
313 hPutStr stderr cProjectVersion
314 hPutStr stderr ", for Haskell 98, compiled by GHC version "
315 hPutStrLn stderr cBooterVersion
321 hPutStrLn stderr ("Hsc static flags: " ++ unwords static_opts)