1 {-# OPTIONS -fno-warn-incomplete-patterns -optc-DNON_POSIX_SOURCE #-}
3 -----------------------------------------------------------------------------
4 -- $Id: Main.hs,v 1.119 2003/02/17 12:24:27 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"
22 import DriverPhases( objish_file )
26 import CompManager ( cmInit, cmLoadModules, cmDepAnal )
27 import HscTypes ( GhciMode(..) )
28 import Config ( cBooterVersion, cGhcUnregisterised, cProjectVersion )
29 import SysTools ( getPackageConfigPath, initSysTools, cleanTempFiles )
30 import Packages ( showPackages, getPackageConfigMap, basePackage,
33 import DriverPipeline ( staticLink, doMkDLL, genPipeline, pipeLoop )
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 ( Phase(HsPp, Hsc), haskellish_src_file, isSourceFile )
49 import DriverUtil ( add, handle, handleDyn, later, splitFilename,
50 unknownFlagsErr, getFileSuffix )
51 import CmdLineOpts ( dynFlag, restoreDynFlags,
52 saveDynFlags, setDynFlags, getDynFlags, dynFlag,
53 DynFlags(..), HscLang(..), v_Static_hsc_opts,
56 import BasicTypes ( failed )
59 import Panic ( GhcException(..), panic, installSignalHandlers )
61 import DATA_IOREF ( readIORef, writeIORef )
62 import EXCEPTION ( throwDyn, Exception(..),
63 AsyncException(StackOverflow) )
65 -- Standard Haskell libraries
67 import Directory ( doesFileExist )
68 import System ( getArgs, exitWith, ExitCode(..) )
73 -----------------------------------------------------------------------------
76 -- new mkdependHS doesn't support all the options that the old one did (-X et al.)
77 -- time commands when run with -v
81 -- Win32 support: proper signal handling
82 -- make sure OPTIONS in .hs file propogate to .hc file if -C or -keep-hc-file-too
83 -- reading the package configuration file is too slow
86 -----------------------------------------------------------------------------
87 -- Differences vs. old driver:
89 -- No more "Enter your Haskell program, end with ^D (on a line of its own):"
90 -- consistency checking removed (may do this properly later)
93 -----------------------------------------------------------------------------
97 -- top-level exception handler: any unrecognised exception is a compiler bug.
98 handle (\exception -> do
101 -- an IO exception probably isn't our fault, so don't panic
102 IOException _ -> hPutStr stderr (show exception)
103 AsyncException StackOverflow ->
104 hPutStrLn stderr "stack overflow: use +RTS -K<size> \
106 _other -> hPutStr stderr (show (Panic (show exception)))
107 exitWith (ExitFailure 1)
110 -- all error messages are propagated as exceptions
111 handleDyn (\dyn -> do
114 PhaseFailed _ code -> exitWith code
115 Interrupted -> exitWith (ExitFailure 1)
116 _ -> do hPutStrLn stderr (show (dyn :: GhcException))
117 exitWith (ExitFailure 1)
120 -- make sure we clean up after ourselves
121 later (do forget_it <- readIORef v_Keep_tmp_files
122 unless forget_it $ do
123 verb <- dynFlag verbosity
126 -- exceptions will be blocked while we clean the temporary files,
127 -- so there shouldn't be any difficulty if we receive further
130 installSignalHandlers
133 let (minusB_args, argv') = partition (prefixMatch "-B") argv
134 top_dir <- initSysTools minusB_args
136 -- Read the package configuration
137 conf_file <- getPackageConfigPath
138 readPackageConf conf_file
140 -- process all the other arguments, and get the source files
141 non_static <- processArgs static_flags argv' []
142 mode <- readIORef v_GhcMode
143 stop_flag <- readIORef v_GhcModeFlag
145 -- -O and --interactive are not a good combination
146 -- ditto with any kind of way selection
147 orig_opt_level <- readIORef v_OptLevel
148 when (orig_opt_level > 0 && mode == DoInteractive) $
149 do putStr "warning: -O conflicts with --interactive; -O turned off.\n"
150 writeIORef v_OptLevel 0
151 orig_ways <- readIORef v_Ways
152 when (notNull orig_ways && mode == DoInteractive) $
153 do throwDyn (UsageError
154 "--interactive can't be used with -prof, -ticky, -unreg or -smp.")
156 -- Find the build tag, and re-process the build-specific options.
157 -- Also add in flags for unregisterised compilation, if
158 -- GhcUnregisterised=YES.
159 way_opts <- findBuildTag
160 let unreg_opts | cGhcUnregisterised == "YES" = unregFlags
162 pkg_extra_opts <- getPackageExtraGhcOpts
163 extra_non_static <- processArgs static_flags
164 (unreg_opts ++ way_opts ++ pkg_extra_opts) []
166 -- give the static flags to hsc
167 static_opts <- buildStaticHscOpts
168 writeIORef v_Static_hsc_opts static_opts
170 -- build the default DynFlags (these may be adjusted on a per
171 -- module basis by OPTIONS pragmas and settings in the interpreter).
173 core_todo <- buildCoreToDo
174 stg_todo <- buildStgToDo
176 -- set the "global" HscLang. The HscLang can be further adjusted on a module
177 -- by module basis, using only the -fvia-C and -fasm flags. If the global
178 -- HscLang is not HscC or HscAsm, -fvia-C and -fasm have no effect.
179 dyn_flags <- getDynFlags
180 build_tag <- readIORef v_Build_tag
181 let lang = case mode of
182 DoInteractive -> HscInterpreted
183 _other | build_tag /= "" -> HscC
184 | otherwise -> hscLang dyn_flags
185 -- for ways other that the normal way, we must
188 setDynFlags (dyn_flags{ coreToDo = core_todo,
191 -- leave out hscOutName for now
192 hscOutName = panic "Main.main:hscOutName not set",
196 -- the rest of the arguments are "dynamic"
197 srcs <- processArgs dynamic_flags (extra_non_static ++ non_static) []
199 -- save the "initial DynFlags" away
202 -- perform some checks of the options set / report unknowns.
205 verb <- dynFlag verbosity
207 -- Show the GHCi banner
209 when (mode == DoInteractive && verb >= 1) $
210 hPutStrLn stdout ghciWelcomeMsg
213 -- Display details of the configuration in verbose mode
215 (do hPutStr stderr "Glasgow Haskell Compiler, Version "
216 hPutStr stderr cProjectVersion
217 hPutStr stderr ", for Haskell 98, compiled by GHC version "
218 hPutStrLn stderr cBooterVersion)
221 (hPutStrLn stderr ("Using package config file: " ++ conf_file))
223 pkg_details <- getPackageConfigMap
224 showPackages pkg_details
227 (hPutStrLn stderr ("Hsc static flags: " ++ unwords static_opts))
229 -- mkdependHS is special
230 when (mode == DoMkDependHS) beginMkDependHS
232 -- -ohi sanity checking
233 ohi <- readIORef v_Output_hi
235 (mode == DoMake || mode == DoInteractive || srcs `lengthExceeds` 1))
236 then throwDyn (UsageError "-ohi can only be used when compiling a single source file")
239 -- make/interactive require invoking the compilation manager
240 if (mode == DoMake) then beginMake srcs else do
241 if (mode == DoInteractive) then beginInteractive srcs else do
243 -- -o sanity checking
244 let real_srcs = filter isSourceFile srcs -- filters out .a and .o that might appear
245 o_file <- readIORef v_Output_file
246 if (real_srcs `lengthExceeds` 1 && isJust o_file && mode /= DoLink && mode /= DoMkDLL)
247 then throwDyn (UsageError "can't apply -o to multiple source files")
250 if null srcs then throwDyn (UsageError "no input files") else do
252 let compileFile src = do
255 exists <- doesFileExist src
257 throwDyn (CmdLineError ("file `" ++ src ++ "' does not exist"))
259 -- We compile in two stages, because the file may have an
260 -- OPTIONS pragma that affects the compilation pipeline (eg. -fvia-C)
261 let (basename, suffix) = splitFilename src
263 -- just preprocess (Haskell source only)
264 let src_and_suff = (src, getFileSuffix src)
265 let not_hs_file = not (haskellish_src_file src)
266 pp <- if not_hs_file || mode == StopBefore Hsc || mode == StopBefore HsPp
267 then return src_and_suff else do
268 phases <- genPipeline (StopBefore Hsc) stop_flag
269 False{-not persistent-} defaultHscLang
271 pipeLoop phases src_and_suff False{-no linking-} False{-no -o flag-}
274 -- rest of compilation
275 hsc_lang <- dynFlag hscLang
276 phases <- genPipeline mode stop_flag True hsc_lang pp
277 (r,_) <- pipeLoop phases pp (mode==DoLink || mode==DoMkDLL)
278 True{-use -o flag-} basename suffix
281 o_files <- mapM compileFile srcs
283 when (mode == DoMkDependHS) endMkDependHS
285 omit_linking <- readIORef v_NoLink
286 when (mode == DoLink && not omit_linking)
287 (staticLink o_files [basePackage, haskell98Package])
288 -- we always link in the base package in one-shot linking.
289 -- any other packages required must be given using -package
290 -- options on the command-line.
292 when (mode == DoMkDLL) (doMkDLL o_files)
296 beginMake :: [String] -> IO ()
297 beginMake fileish_args = do
298 -- anything that doesn't look like a Haskell source filename or
299 -- a module name is passed straight through to the linker
300 let (inputs, objects) = partition looks_like_an_input fileish_args
301 mapM_ (add v_Ld_inputs) objects
304 [] -> throwDyn (UsageError "no input files")
305 _ -> do dflags <- getDynFlags
306 state <- cmInit Batch
307 graph <- cmDepAnal state dflags inputs
308 (_, ok_flag, _) <- cmLoadModules state dflags graph
309 when (failed ok_flag) (exitWith (ExitFailure 1))
313 The following things should be considered compilation manager inputs:
315 - haskell source files (strings ending in .hs, .lhs or other
316 haskellish extension),
318 - module names (not forgetting hierarchical module names),
320 - and finally we consider everything not containing a '.' to be
321 a comp manager input, as shorthand for a .hs or .lhs filename.
323 Everything else is considered to be a linker object, and passed
324 straight through to the linker.
326 looks_like_an_input m = haskellish_src_file m
327 || looksLikeModuleName m
331 beginInteractive :: [String] -> IO ()
333 beginInteractive = throwDyn (CmdLineError "not built for interactive use")
335 beginInteractive fileish_args
336 = do state <- cmInit Interactive
338 let (objs, mods) = partition objish_file fileish_args
340 interactiveUI state mods objs
343 checkOptions :: [String] -> IO ()
344 checkOptions srcs = do
345 -- complain about any unknown flags
346 let unknown_opts = [ f | f@('-':_) <- srcs ]
347 when (notNull unknown_opts) (unknownFlagsErr unknown_opts)
348 -- verify that output files point somewhere sensible.
350 -- and anything else that it might be worth checking for
351 -- before kicking of a compilation (pipeline).