1 {-# OPTIONS -fno-warn-incomplete-patterns -optc-DNON_POSIX_SOURCE #-}
3 -----------------------------------------------------------------------------
4 -- $Id: Main.hs,v 1.142 2005/01/18 12:18:34 simonpj Exp $
8 -- (c) The University of Glasgow 2002
10 -----------------------------------------------------------------------------
12 -- with path so that ghc -M can find config.h
13 #include "../includes/ghcconfig.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 ( initSysTools, cleanTempFiles, normalisePath )
29 import Packages ( dumpPackages, initPackages, haskell98PackageId, PackageIdH(..) )
30 import DriverPipeline ( staticLink, doMkDLL, runPipeline )
31 import DriverState ( buildStgToDo,
32 findBuildTag, unregFlags,
33 v_GhcMode, v_GhcModeFlag, GhcMode(..),
34 v_Keep_tmp_files, v_Ld_inputs, v_Ways,
35 v_Output_file, v_Output_hi,
36 verifyOutputFiles, v_NoLink
40 import DriverMkDepend ( beginMkDependHS, endMkDependHS )
41 import DriverPhases ( isSourceFilename )
43 import DriverUtil ( add, handle, handleDyn, later, unknownFlagsErr )
44 import CmdLineOpts ( DynFlags(..), HscLang(..), v_Static_hsc_opts,
46 import BasicTypes ( failed )
49 import Panic ( GhcException(..), panic, installSignalHandlers )
51 import DATA_IOREF ( readIORef, writeIORef )
52 import EXCEPTION ( throwDyn, Exception(..),
53 AsyncException(StackOverflow) )
55 -- Standard Haskell libraries
57 import Directory ( doesFileExist )
58 import System ( getArgs, exitWith, ExitCode(..) )
63 -----------------------------------------------------------------------------
66 -- new mkdependHS doesn't support all the options that the old one did (-X et al.)
67 -- time commands when run with -v
71 -- Win32 support: proper signal handling
72 -- make sure OPTIONS in .hs file propogate to .hc file if -C or -keep-hc-file-too
73 -- reading the package configuration file is too slow
76 -----------------------------------------------------------------------------
77 -- Differences vs. old driver:
79 -- No more "Enter your Haskell program, end with ^D (on a line of its own):"
80 -- consistency checking removed (may do this properly later)
83 -----------------------------------------------------------------------------
87 -- top-level exception handler: any unrecognised exception is a compiler bug.
88 handle (\exception -> do
91 -- an IO exception probably isn't our fault, so don't panic
92 IOException _ -> hPutStrLn stderr (show exception)
93 AsyncException StackOverflow ->
94 hPutStrLn stderr "stack overflow: use +RTS -K<size> to increase it"
95 _other -> hPutStr stderr (show (Panic (show exception)))
96 exitWith (ExitFailure 1)
99 -- all error messages are propagated as exceptions
100 handleDyn (\dyn -> do
103 PhaseFailed _ code -> exitWith code
104 Interrupted -> exitWith (ExitFailure 1)
105 _ -> do hPutStrLn stderr (show (dyn :: GhcException))
106 exitWith (ExitFailure 1)
109 installSignalHandlers
112 let (minusB_args, argv') = partition (prefixMatch "-B") argv
113 top_dir <- initSysTools minusB_args
115 -- Process all the other arguments, and get the source files
116 non_static <- processStaticFlags argv'
117 mode <- readIORef v_GhcMode
119 -- -O and --interactive are not a good combination
120 -- ditto with any kind of way selection
121 orig_ways <- readIORef v_Ways
122 when (notNull orig_ways && isInteractive mode) $
123 do throwDyn (UsageError
124 "--interactive can't be used with -prof, -ticky, -unreg or -smp.")
126 -- Find the build tag, and re-process the build-specific options.
127 -- Also add in flags for unregisterised compilation, if
128 -- GhcUnregisterised=YES.
129 way_opts <- findBuildTag
130 let unreg_opts | cGhcUnregisterised == "YES" = unregFlags
132 extra_non_static <- processStaticFlags (unreg_opts ++ way_opts)
134 -- Give the static flags to hsc
135 static_opts <- buildStaticHscOpts
136 writeIORef v_Static_hsc_opts static_opts
138 -- build the default DynFlags (these may be adjusted on a per
139 -- module basis by OPTIONS pragmas and settings in the interpreter).
141 stg_todo <- buildStgToDo
143 -- set the "global" HscLang. The HscLang can be further adjusted on a module
144 -- by module basis, using only the -fvia-C and -fasm flags. If the global
145 -- HscLang is not HscC or HscAsm, -fvia-C and -fasm have no effect.
146 let dflags0 = defaultDynFlags
147 let lang = case mode of
148 DoInteractive -> HscInterpreted
149 DoEval _ -> HscInterpreted
150 _other -> hscLang dflags0
152 let dflags1 = dflags0{ stgToDo = stg_todo,
154 -- leave out hscOutName for now
155 hscOutName = panic "Main.main:hscOutName not set",
156 verbosity = case mode of
161 -- The rest of the arguments are "dynamic"
162 -- Leftover ones are presumably files
163 (dflags2, fileish_args) <- processDynamicFlags
164 (extra_non_static ++ non_static) dflags1
166 -- make sure we clean up after ourselves
167 later (do forget_it <- readIORef v_Keep_tmp_files
168 unless forget_it $ do
169 cleanTempFiles dflags2
171 -- exceptions will be blocked while we clean the temporary files,
172 -- so there shouldn't be any difficulty if we receive further
175 -- Read the package config(s), and process the package-related
176 -- command-line flags
177 dflags <- initPackages dflags2
181 We split out the object files (.o, .dll) and add them
182 to v_Ld_inputs for use by the linker.
184 The following things should be considered compilation manager inputs:
186 - haskell source files (strings ending in .hs, .lhs or other
187 haskellish extension),
189 - module names (not forgetting hierarchical module names),
191 - and finally we consider everything not containing a '.' to be
192 a comp manager input, as shorthand for a .hs or .lhs filename.
194 Everything else is considered to be a linker object, and passed
195 straight through to the linker.
197 looks_like_an_input m = isSourceFilename m
198 || looksLikeModuleName m
201 -- To simplify the handling of filepaths, we normalise all filepaths right
202 -- away - e.g., for win32 platforms, backslashes are converted
203 -- into forward slashes.
204 normal_fileish_paths = map normalisePath fileish_args
205 (srcs, objs) = partition looks_like_an_input normal_fileish_paths
207 -- Note: have v_Ld_inputs maintain the order in which 'objs' occurred on
209 mapM_ (add v_Ld_inputs) (reverse objs)
211 ---------------- Display banners and configuration -----------
212 showBanners mode dflags static_opts
214 ---------------- Final sanity checking -----------
215 checkOptions mode srcs objs
217 ---------------- Do the business -----------
219 -- Always link in the haskell98 package for static linking. Other
220 -- packages have to be specified via the -package flag.
222 | ExtPackage h98_id <- haskell98PackageId (pkgState dflags) = [h98_id]
226 DoMake -> doMake dflags srcs
228 DoMkDependHS -> do { beginMkDependHS ;
229 compileFiles mode dflags srcs;
230 endMkDependHS dflags }
231 StopBefore p -> do { compileFiles mode dflags srcs; return () }
232 DoMkDLL -> do { o_files <- compileFiles mode dflags srcs;
233 doMkDLL dflags o_files link_pkgs }
234 DoLink -> do { o_files <- compileFiles mode dflags srcs;
235 omit_linking <- readIORef v_NoLink;
236 when (not omit_linking)
237 (staticLink dflags o_files link_pkgs) }
240 DoInteractive -> noInteractiveError
241 DoEval _ -> noInteractiveError
243 noInteractiveError = throwDyn (CmdLineError "not built for interactive use")
245 DoInteractive -> interactiveUI dflags srcs Nothing
246 DoEval expr -> interactiveUI dflags srcs (Just expr)
249 -- -----------------------------------------------------------------------------
250 -- Option sanity checks
252 checkOptions :: GhcMode -> [String] -> [String] -> IO ()
253 -- Final sanity checking before kicking off a compilation (pipeline).
254 checkOptions mode srcs objs = do
255 -- Complain about any unknown flags
256 let unknown_opts = [ f | f@('-':_) <- srcs ]
257 when (notNull unknown_opts) (unknownFlagsErr unknown_opts)
260 ohi <- readIORef v_Output_hi
262 (mode == DoMake || isInteractive mode || srcs `lengthExceeds` 1))
263 then throwDyn (UsageError "-ohi can only be used when compiling a single source file")
266 -- -o sanity checking
267 o_file <- readIORef v_Output_file
268 if (srcs `lengthExceeds` 1 && isJust o_file && mode /= DoLink && mode /= DoMkDLL)
269 then throwDyn (UsageError "can't apply -o to multiple source files")
272 -- Check that there are some input files (except in the interactive
274 if null srcs && null objs && not (isInteractive mode)
275 then throwDyn (UsageError "no input files")
278 -- Verify that output files point somewhere sensible.
281 isInteractive DoInteractive = True
282 isInteractive (DoEval _) = True
283 isInteractive _ = False
285 -- -----------------------------------------------------------------------------
286 -- Compile files in one-shot mode.
288 compileFiles :: GhcMode
290 -> [String] -- Source files
291 -> IO [String] -- Object files
292 compileFiles mode dflags srcs = do
293 stop_flag <- readIORef v_GhcModeFlag
294 mapM (compileFile mode dflags stop_flag) srcs
297 compileFile mode dflags stop_flag src = do
298 exists <- doesFileExist src
300 throwDyn (CmdLineError ("file `" ++ src ++ "' does not exist"))
302 o_file <- readIORef v_Output_file
303 -- when linking, the -o argument refers to the linker's output.
304 -- otherwise, we use it as the name for the pipeline's output.
306 | mode==DoLink || mode==DoMkDLL = Nothing
309 runPipeline mode dflags stop_flag True maybe_o_file src
310 Nothing{-no ModLocation-}
313 -- ----------------------------------------------------------------------------
316 doMake :: DynFlags -> [String] -> IO ()
317 doMake dflags [] = throwDyn (UsageError "no input files")
318 doMake dflags srcs = do
319 state <- cmInit Batch dflags
320 graph <- cmDepAnal state srcs
321 (_, ok_flag, _) <- cmLoadModules state graph
322 when (failed ok_flag) (exitWith (ExitFailure 1))
325 -- ---------------------------------------------------------------------------
326 -- Various banners and verbosity output.
328 showBanners :: GhcMode -> DynFlags -> [String] -> IO ()
329 showBanners mode dflags static_opts = do
330 let verb = verbosity dflags
332 -- Show the GHCi banner
334 when (mode == DoInteractive && verb >= 1) $
335 hPutStrLn stdout ghciWelcomeMsg
338 -- Display details of the configuration in verbose mode
340 do hPutStr stderr "Glasgow Haskell Compiler, Version "
341 hPutStr stderr cProjectVersion
342 hPutStr stderr ", for Haskell 98, compiled by GHC version "
343 hPutStrLn stderr cBooterVersion
349 hPutStrLn stderr ("Hsc static flags: " ++ unwords static_opts)