1 {-# OPTIONS -fno-warn-incomplete-patterns -optc-DNON_POSIX_SOURCE #-}
3 -----------------------------------------------------------------------------
4 -- $Id: Main.hs,v 1.127 2003/06/23 10:35:17 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,
30 import Packages ( showPackages, getPackageConfigMap, basePackage,
33 import DriverPipeline ( staticLink, doMkDLL, runPipeline )
34 import DriverState ( buildCoreToDo, buildStgToDo,
36 getPackageExtraGhcOpts, unregFlags,
37 v_GhcMode, v_GhcModeFlag, GhcMode(..),
38 v_Keep_tmp_files, v_Ld_inputs, v_Ways,
39 v_OptLevel, v_Output_file, v_Output_hi,
40 readPackageConf, verifyOutputFiles, v_NoLink,
43 import DriverFlags ( buildStaticHscOpts,
44 dynamic_flags, processArgs, static_flags)
46 import DriverMkDepend ( beginMkDependHS, endMkDependHS )
47 import DriverPhases ( isSourceFile )
49 import DriverUtil ( add, handle, handleDyn, later, unknownFlagsErr )
50 import CmdLineOpts ( dynFlag, restoreDynFlags,
51 saveDynFlags, setDynFlags, getDynFlags, dynFlag,
52 DynFlags(..), HscLang(..), v_Static_hsc_opts
54 import BasicTypes ( failed )
57 import Panic ( GhcException(..), panic, installSignalHandlers )
59 import DATA_IOREF ( readIORef, writeIORef )
60 import EXCEPTION ( throwDyn, Exception(..),
61 AsyncException(StackOverflow) )
63 -- Standard Haskell libraries
65 import Directory ( doesFileExist )
66 import System ( getArgs, exitWith, ExitCode(..) )
71 -----------------------------------------------------------------------------
74 -- new mkdependHS doesn't support all the options that the old one did (-X et al.)
75 -- time commands when run with -v
79 -- Win32 support: proper signal handling
80 -- make sure OPTIONS in .hs file propogate to .hc file if -C or -keep-hc-file-too
81 -- reading the package configuration file is too slow
84 -----------------------------------------------------------------------------
85 -- Differences vs. old driver:
87 -- No more "Enter your Haskell program, end with ^D (on a line of its own):"
88 -- consistency checking removed (may do this properly later)
91 -----------------------------------------------------------------------------
95 -- top-level exception handler: any unrecognised exception is a compiler bug.
96 handle (\exception -> do
99 -- an IO exception probably isn't our fault, so don't panic
100 IOException _ -> hPutStr stderr (show exception)
101 AsyncException StackOverflow ->
102 hPutStrLn stderr "stack overflow: use +RTS -K<size> \
104 _other -> hPutStr stderr (show (Panic (show exception)))
105 exitWith (ExitFailure 1)
108 -- all error messages are propagated as exceptions
109 handleDyn (\dyn -> do
112 PhaseFailed _ 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 installSignalHandlers
131 let (minusB_args, argv') = partition (prefixMatch "-B") argv
132 top_dir <- initSysTools minusB_args
134 -- Read the package configuration
135 conf_file <- getPackageConfigPath
136 readPackageConf conf_file
138 -- Process all the other arguments, and get the source files
139 non_static <- processArgs static_flags argv' []
140 mode <- readIORef v_GhcMode
142 -- -O and --interactive are not a good combination
143 -- ditto with any kind of way selection
144 orig_opt_level <- readIORef v_OptLevel
145 when (orig_opt_level > 0 && mode == DoInteractive) $
146 do putStr "warning: -O conflicts with --interactive; -O turned off.\n"
147 writeIORef v_OptLevel 0
148 orig_ways <- readIORef v_Ways
149 when (notNull orig_ways && mode == DoInteractive) $
150 do throwDyn (UsageError
151 "--interactive can't be used with -prof, -ticky, -unreg or -smp.")
153 -- Find the build tag, and re-process the build-specific options.
154 -- Also add in flags for unregisterised compilation, if
155 -- GhcUnregisterised=YES.
156 way_opts <- findBuildTag
157 let unreg_opts | cGhcUnregisterised == "YES" = unregFlags
159 pkg_extra_opts <- getPackageExtraGhcOpts
160 extra_non_static <- processArgs static_flags
161 (unreg_opts ++ way_opts ++ pkg_extra_opts) []
163 -- Give the static flags to hsc
164 static_opts <- buildStaticHscOpts
165 writeIORef v_Static_hsc_opts static_opts
167 -- build the default DynFlags (these may be adjusted on a per
168 -- module basis by OPTIONS pragmas and settings in the interpreter).
170 core_todo <- buildCoreToDo
171 stg_todo <- buildStgToDo
173 -- set the "global" HscLang. The HscLang can be further adjusted on a module
174 -- by module basis, using only the -fvia-C and -fasm flags. If the global
175 -- HscLang is not HscC or HscAsm, -fvia-C and -fasm have no effect.
176 dyn_flags <- getDynFlags
177 build_tag <- readIORef v_Build_tag
178 let lang = case mode of
179 DoInteractive -> HscInterpreted
180 _other | build_tag /= "" -> HscC
181 | otherwise -> hscLang dyn_flags
182 -- for ways other that the normal way, we must
185 setDynFlags (dyn_flags{ coreToDo = core_todo,
188 -- leave out hscOutName for now
189 hscOutName = panic "Main.main:hscOutName not set",
193 -- The rest of the arguments are "dynamic"
194 -- Leftover ones are presumably files
195 fileish_args <- processArgs dynamic_flags (extra_non_static ++ non_static) []
197 -- save the "initial DynFlags" away
202 We split out the object files (.o, .dll) and add them
203 to v_Ld_inputs for use by the linker.
205 The following things should be considered compilation manager inputs:
207 - haskell source files (strings ending in .hs, .lhs or other
208 haskellish extension),
210 - module names (not forgetting hierarchical module names),
212 - and finally we consider everything not containing a '.' to be
213 a comp manager input, as shorthand for a .hs or .lhs filename.
215 Everything else is considered to be a linker object, and passed
216 straight through to the linker.
218 looks_like_an_input m = isSourceFile m
219 || looksLikeModuleName m
222 -- To simplify the handling of filepaths, we normalise all filepaths right
223 -- away - e.g., for win32 platforms, backslashes are converted
224 -- into forward slashes.
225 normal_fileish_paths = map normalisePath fileish_args
226 (srcs, objs) = partition looks_like_an_input normal_fileish_paths
228 mapM_ (add v_Ld_inputs) objs
230 ---------------- Display banners and configuration -----------
231 showBanners mode conf_file static_opts
233 ---------------- Final sanity checking -----------
234 checkOptions mode srcs objs
236 ---------------- Do the business -----------
238 DoMake -> doMake srcs
240 DoMkDependHS -> do { beginMkDependHS ;
241 compileFiles mode srcs;
243 StopBefore p -> do { compileFiles mode srcs; return () }
244 DoMkDLL -> do { o_files <- compileFiles mode srcs;
246 DoLink -> do { o_files <- compileFiles mode srcs;
247 omit_linking <- readIORef v_NoLink;
248 when (not omit_linking)
250 [basePackage, haskell98Package]) }
251 -- We always link in the base package in
252 -- one-shot linking. Any other packages
253 -- required must be given using -package
254 -- options on the command-line.
257 DoInteractive -> throwDyn (CmdLineError "not built for interactive use")
259 DoInteractive -> interactiveUI srcs
262 -- -----------------------------------------------------------------------------
263 -- Option sanity checks
265 checkOptions :: GhcMode -> [String] -> [String] -> IO ()
266 -- Final sanity checking before kicking off a compilation (pipeline).
267 checkOptions mode srcs objs = do
269 ohi <- readIORef v_Output_hi
271 (mode == DoMake || mode == DoInteractive || srcs `lengthExceeds` 1))
272 then throwDyn (UsageError "-ohi can only be used when compiling a single source file")
275 -- -o sanity checking
276 o_file <- readIORef v_Output_file
277 if (srcs `lengthExceeds` 1 && isJust o_file && mode /= DoLink && mode /= DoMkDLL)
278 then throwDyn (UsageError "can't apply -o to multiple source files")
281 -- Check that there are some input files (except in the interactive
283 if null srcs && null objs && mode /= DoInteractive
284 then throwDyn (UsageError "no input files")
287 -- Complain about any unknown flags
288 let unknown_opts = [ f | f@('-':_) <- srcs ]
289 when (notNull unknown_opts) (unknownFlagsErr unknown_opts)
291 -- Verify that output files point somewhere sensible.
295 -- -----------------------------------------------------------------------------
296 -- Compile files in one-shot mode.
298 compileFiles :: GhcMode
299 -> [String] -- Source files
300 -> IO [String] -- Object files
301 compileFiles mode srcs = do
302 stop_flag <- readIORef v_GhcModeFlag
303 mapM (compileFile mode stop_flag) srcs
306 compileFile mode stop_flag src = do
309 exists <- doesFileExist src
311 throwDyn (CmdLineError ("file `" ++ src ++ "' does not exist"))
313 o_file <- readIORef v_Output_file
314 -- when linking, the -o argument refers to the linker's output.
315 -- otherwise, we use it as the name for the pipeline's output.
317 | mode==DoLink || mode==DoMkDLL = Nothing
320 runPipeline mode stop_flag True maybe_o_file src
323 -- ----------------------------------------------------------------------------
326 doMake :: [String] -> IO ()
327 doMake [] = throwDyn (UsageError "no input files")
329 dflags <- getDynFlags
330 state <- cmInit Batch
331 graph <- cmDepAnal state dflags srcs
332 (_, ok_flag, _) <- cmLoadModules state dflags graph
333 when (failed ok_flag) (exitWith (ExitFailure 1))
336 -- ---------------------------------------------------------------------------
337 -- Various banners and verbosity output.
339 showBanners :: GhcMode -> FilePath -> [String] -> IO ()
340 showBanners mode conf_file static_opts = do
341 verb <- dynFlag verbosity
343 -- Show the GHCi banner
345 when (mode == DoInteractive && verb >= 1) $
346 hPutStrLn stdout ghciWelcomeMsg
349 -- Display details of the configuration in verbose mode
351 (do hPutStr stderr "Glasgow Haskell Compiler, Version "
352 hPutStr stderr cProjectVersion
353 hPutStr stderr ", for Haskell 98, compiled by GHC version "
354 hPutStrLn stderr cBooterVersion)
357 (hPutStrLn stderr ("Using package config file: " ++ conf_file))
359 pkg_details <- getPackageConfigMap
360 showPackages pkg_details
363 (hPutStrLn stderr ("Hsc static flags: " ++ unwords static_opts))