1 {-# OPTIONS -fno-warn-incomplete-patterns -optc-DNON_POSIX_SOURCE #-}
3 -----------------------------------------------------------------------------
4 -- $Id: Main.hs,v 1.123 2003/05/21 13:05:49 simonmar 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 -- save the "initial DynFlags" away
203 We split out the object files (.o, .dll) and add them
204 to v_Ld_inputs for use by the linker.
206 The following things should be considered compilation manager inputs:
208 - haskell source files (strings ending in .hs, .lhs or other
209 haskellish extension),
211 - module names (not forgetting hierarchical module names),
213 - and finally we consider everything not containing a '.' to be
214 a comp manager input, as shorthand for a .hs or .lhs filename.
216 Everything else is considered to be a linker object, and passed
217 straight through to the linker.
219 looks_like_an_input m = isSourceFile m
220 || looksLikeModuleName m
223 (srcs, objs) = partition looks_like_an_input fileish_args
225 mapM_ (add v_Ld_inputs) objs
227 ---------------- Display banners and configuration -----------
228 showBanners mode conf_file static_opts
230 ---------------- Final sanity checking -----------
231 checkOptions mode srcs objs
233 ---------------- Do the business -----------
235 DoMake -> doMake srcs
237 DoMkDependHS -> do { beginMkDependHS ;
238 compileFiles mode srcs;
240 StopBefore p -> do { compileFiles mode srcs; return () }
241 DoMkDLL -> do { o_files <- compileFiles mode srcs;
243 DoLink -> do { o_files <- compileFiles mode srcs;
244 omit_linking <- readIORef v_NoLink;
245 when (not omit_linking)
247 [basePackage, haskell98Package]) }
248 -- We always link in the base package in
249 -- one-shot linking. Any other packages
250 -- required must be given using -package
251 -- options on the command-line.
254 DoInteractive -> throwDyn (CmdLineError "not built for interactive use")
256 DoInteractive -> interactiveUI srcs
259 -- -----------------------------------------------------------------------------
260 -- Option sanity checks
262 checkOptions :: GhcMode -> [String] -> [String] -> IO ()
263 -- Final sanity checking before kicking off a compilation (pipeline).
264 checkOptions mode srcs objs = do
266 ohi <- readIORef v_Output_hi
268 (mode == DoMake || mode == DoInteractive || srcs `lengthExceeds` 1))
269 then throwDyn (UsageError "-ohi can only be used when compiling a single source file")
272 -- -o sanity checking
273 o_file <- readIORef v_Output_file
274 if (srcs `lengthExceeds` 1 && isJust o_file && mode /= DoLink && mode /= DoMkDLL)
275 then throwDyn (UsageError "can't apply -o to multiple source files")
278 -- Check that there are some input files (except in the interactive
280 if null srcs && null objs && mode /= DoInteractive
281 then throwDyn (UsageError "no input files")
284 -- Complain about any unknown flags
285 let unknown_opts = [ f | f@('-':_) <- srcs ]
286 when (notNull unknown_opts) (unknownFlagsErr unknown_opts)
288 -- Verify that output files point somewhere sensible.
292 -- -----------------------------------------------------------------------------
293 -- Compile files in one-shot mode.
295 compileFiles :: GhcMode
296 -> [String] -- Source files
297 -> IO [String] -- Object files
298 compileFiles mode srcs = do
299 stop_flag <- readIORef v_GhcModeFlag
300 mapM (compileFile mode stop_flag) srcs
303 compileFile mode stop_flag src = do
306 exists <- doesFileExist src
308 throwDyn (CmdLineError ("file `" ++ src ++ "' does not exist"))
310 -- We compile in two stages, because the file may have an
311 -- OPTIONS pragma that affects the compilation pipeline (eg. -fvia-C)
312 let (basename, suffix) = splitFilename src
314 -- just preprocess (Haskell source only)
315 let src_and_suff = (src, getFileSuffix src)
316 let not_hs_file = not (haskellish_src_file src)
317 pp <- if not_hs_file || mode == StopBefore Hsc || mode == StopBefore HsPp
318 then return src_and_suff else do
319 phases <- genPipeline (StopBefore Hsc) stop_flag
320 False{-not persistent-} defaultHscLang
322 pipeLoop phases src_and_suff False{-no linking-} False{-no -o flag-}
325 -- rest of compilation
326 hsc_lang <- dynFlag hscLang
327 phases <- genPipeline mode stop_flag True hsc_lang pp
328 (r,_) <- pipeLoop phases pp (mode==DoLink || mode==DoMkDLL)
329 True{-use -o flag-} basename suffix
333 -- ----------------------------------------------------------------------------
336 doMake :: [String] -> IO ()
337 doMake [] = throwDyn (UsageError "no input files")
339 dflags <- getDynFlags
340 state <- cmInit Batch
341 graph <- cmDepAnal state dflags srcs
342 (_, ok_flag, _) <- cmLoadModules state dflags graph
343 when (failed ok_flag) (exitWith (ExitFailure 1))
346 -- ---------------------------------------------------------------------------
347 -- Various banners and verbosity output.
349 showBanners :: GhcMode -> FilePath -> [String] -> IO ()
350 showBanners mode conf_file static_opts = do
351 verb <- dynFlag verbosity
353 -- Show the GHCi banner
355 when (mode == DoInteractive && verb >= 1) $
356 hPutStrLn stdout ghciWelcomeMsg
359 -- Display details of the configuration in verbose mode
361 (do hPutStr stderr "Glasgow Haskell Compiler, Version "
362 hPutStr stderr cProjectVersion
363 hPutStr stderr ", for Haskell 98, compiled by GHC version "
364 hPutStrLn stderr cBooterVersion)
367 (hPutStrLn stderr ("Using package config file: " ++ conf_file))
369 pkg_details <- getPackageConfigMap
370 showPackages pkg_details
373 (hPutStrLn stderr ("Hsc static flags: " ++ unwords static_opts))