[project @ 2002-09-06 14:35:42 by simonmar]
[ghc-hetmet.git] / ghc / compiler / main / Main.hs
1 {-# OPTIONS -fno-warn-incomplete-patterns -optc-DNON_POSIX_SOURCE #-}
2
3 -----------------------------------------------------------------------------
4 -- $Id: Main.hs,v 1.110 2002/09/06 14:35:44 simonmar Exp $
5 --
6 -- GHC Driver program
7 --
8 -- (c) The University of Glasgow 2002
9 --
10 -----------------------------------------------------------------------------
11
12 -- with path so that ghc -M can find config.h
13 #include "../includes/config.h"
14
15 module Main (main) where
16
17 #include "HsVersions.h"
18
19
20 #ifdef GHCI
21 import InteractiveUI
22 #endif
23
24
25 import Finder           ( initFinder )
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 )
31
32 import DriverPipeline   ( doLink, doMkDLL, genPipeline, pipeLoop )
33 import DriverState      ( buildCoreToDo, buildStgToDo,
34                           findBuildTag, getPackageInfo, unregFlags, 
35                           v_GhcMode, v_GhcModeFlag, GhcMode(..),
36                           v_Cmdline_libraries, v_Keep_tmp_files, v_Ld_inputs,
37                           v_OptLevel, v_Output_file, v_Output_hi, 
38                           v_Package_details, v_Ways, getPackageExtraGhcOpts,
39                           readPackageConf, verifyOutputFiles
40                         )
41 import DriverFlags      ( buildStaticHscOpts,
42                           dynamic_flags, processArgs, static_flags)
43
44 import DriverMkDepend   ( beginMkDependHS, endMkDependHS )
45 import DriverPhases     ( Phase(HsPp, Hsc), haskellish_src_file, objish_file,
46                           isSourceFile )
47
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,
53                           defaultHscLang
54                         )
55 import Outputable
56 import Util
57 import Panic            ( GhcException(..), panic )
58
59 import DATA_IOREF       ( readIORef, writeIORef )
60 import EXCEPTION        ( throwDyn, Exception(..), 
61                           AsyncException(StackOverflow) )
62
63 #ifndef mingw32_HOST_OS
64 import CONCURRENT       ( myThreadId )
65 # if __GLASGOW_HASKELL__ < 500
66 import EXCEPTION        ( raiseInThread )
67 #define throwTo  raiseInThread
68 # else
69 import EXCEPTION        ( throwTo )
70 # endif
71
72 #if __GLASGOW_HASKELL__ > 504
73 import System.Posix.Signals
74 #else
75 import Posix            ( Handler(Catch), installHandler, sigINT, sigQUIT )
76 #endif
77
78 import DYNAMIC          ( toDyn )
79 #endif
80
81 -- Standard Haskell libraries
82 import IO
83 import Directory        ( doesFileExist )
84 import System           ( getArgs, exitWith, ExitCode(..) )
85 import Monad
86 import List
87 import Maybe
88
89 -----------------------------------------------------------------------------
90 -- ToDo:
91
92 -- new mkdependHS doesn't support all the options that the old one did (-X et al.)
93 -- time commands when run with -v
94 -- split marker
95 -- java generation
96 -- user ways
97 -- Win32 support: proper signal handling
98 -- make sure OPTIONS in .hs file propogate to .hc file if -C or -keep-hc-file-too
99 -- reading the package configuration file is too slow
100 -- -K<size>
101
102 -----------------------------------------------------------------------------
103 -- Differences vs. old driver:
104
105 -- No more "Enter your Haskell program, end with ^D (on a line of its own):"
106 -- consistency checking removed (may do this properly later)
107 -- no -Ofile
108
109 -----------------------------------------------------------------------------
110 -- Main loop
111
112 main =
113   -- top-level exception handler: any unrecognised exception is a compiler bug.
114   handle (\exception -> do
115            hFlush stdout
116            case exception of
117                 -- an IO exception probably isn't our fault, so don't panic
118                 IOException _ ->  hPutStr stderr (show exception)
119                 AsyncException StackOverflow ->
120                         hPutStrLn stderr "stack overflow: use +RTS -K<size> \ 
121                                          \to increase it"
122                 _other ->  hPutStr stderr (show (Panic (show exception)))
123            exitWith (ExitFailure 1)
124          ) $ do
125
126   -- all error messages are propagated as exceptions
127   handleDyn (\dyn -> do
128                 hFlush stdout
129                 case dyn of
130                      PhaseFailed _ code -> exitWith code
131                      Interrupted -> exitWith (ExitFailure 1)
132                      _ -> do hPutStrLn stderr (show (dyn :: GhcException))
133                              exitWith (ExitFailure 1)
134             ) $ do
135
136    -- make sure we clean up after ourselves
137    later (do  forget_it <- readIORef v_Keep_tmp_files
138               unless forget_it $ do
139               verb <- dynFlag verbosity
140               cleanTempFiles verb
141      ) $ do
142         -- exceptions will be blocked while we clean the temporary files,
143         -- so there shouldn't be any difficulty if we receive further
144         -- signals.
145
146         -- install signal handlers
147 #ifndef mingw32_HOST_OS
148    main_thread <- myThreadId
149    let sig_handler = Catch (throwTo main_thread 
150                                 (DynException (toDyn Interrupted)))
151    installHandler sigQUIT sig_handler Nothing 
152    installHandler sigINT  sig_handler Nothing
153 #endif
154
155    argv <- getArgs
156    let (minusB_args, argv') = partition (prefixMatch "-B") argv
157    top_dir <- initSysTools minusB_args
158
159         -- Read the package configuration
160    conf_file <- getPackageConfigPath
161    readPackageConf conf_file
162
163         -- process all the other arguments, and get the source files
164    non_static <- processArgs static_flags argv' []
165    mode <- readIORef v_GhcMode
166    stop_flag <- readIORef v_GhcModeFlag
167
168         -- -O and --interactive are not a good combination
169         -- ditto with any kind of way selection
170    orig_opt_level <- readIORef v_OptLevel
171    when (orig_opt_level > 0 && mode == DoInteractive) $
172       do putStr "warning: -O conflicts with --interactive; -O turned off.\n"
173          writeIORef v_OptLevel 0
174    orig_ways <- readIORef v_Ways
175    when (notNull orig_ways && mode == DoInteractive) $
176       do throwDyn (UsageError 
177                    "--interactive can't be used with -prof, -ticky, -unreg or -smp.")
178
179         -- Find the build tag, and re-process the build-specific options.
180         -- Also add in flags for unregisterised compilation, if 
181         -- GhcUnregisterised=YES.
182    way_opts <- findBuildTag
183    let unreg_opts | cGhcUnregisterised == "YES" = unregFlags
184                   | otherwise = []
185    pkg_extra_opts <- getPackageExtraGhcOpts
186    extra_non_static <- processArgs static_flags 
187                            (unreg_opts ++ way_opts ++ pkg_extra_opts) []
188
189         -- give the static flags to hsc
190    static_opts <- buildStaticHscOpts
191    writeIORef v_Static_hsc_opts static_opts
192
193    -- build the default DynFlags (these may be adjusted on a per
194    -- module basis by OPTIONS pragmas and settings in the interpreter).
195
196    core_todo <- buildCoreToDo
197    stg_todo  <- buildStgToDo
198
199    -- set the "global" HscLang.  The HscLang can be further adjusted on a module
200    -- by module basis, using only the -fvia-C and -fasm flags.  If the global
201    -- HscLang is not HscC or HscAsm, -fvia-C and -fasm have no effect.
202    dyn_flags <- getDynFlags
203    let lang = case mode of 
204                  DoInteractive  -> HscInterpreted
205                  _other         -> hscLang dyn_flags
206
207    setDynFlags (dyn_flags{ coreToDo = core_todo,
208                            stgToDo  = stg_todo,
209                            hscLang  = lang,
210                            -- leave out hscOutName for now
211                            hscOutName = panic "Main.main:hscOutName not set",
212                            verbosity = 1
213                         })
214
215         -- the rest of the arguments are "dynamic"
216    srcs <- processArgs dynamic_flags (extra_non_static ++ non_static) []
217
218         -- save the "initial DynFlags" away
219    saveDynFlags
220
221         -- perform some checks of the options set / report unknowns.
222    checkOptions srcs
223    
224    verb <- dynFlag verbosity
225
226         -- Show the GHCi banner
227 #  ifdef GHCI
228    when (mode == DoInteractive && verb >= 1) $
229       hPutStrLn stdout ghciWelcomeMsg
230 #  endif
231
232         -- Display details of the configuration in verbose mode
233    when (verb >= 2) 
234         (do hPutStr stderr "Glasgow Haskell Compiler, Version "
235             hPutStr stderr cProjectVersion
236             hPutStr stderr ", for Haskell 98, compiled by GHC version "
237             hPutStrLn stderr cBooterVersion)
238
239    when (verb >= 2) 
240         (hPutStrLn stderr ("Using package config file: " ++ conf_file))
241
242    pkg_details <- readIORef v_Package_details
243    showPackages pkg_details
244
245    when (verb >= 3) 
246         (hPutStrLn stderr ("Hsc static flags: " ++ unwords static_opts))
247
248         -- initialise the finder
249    pkg_avails <- getPackageInfo
250    initFinder pkg_avails
251
252         -- mkdependHS is special
253    when (mode == DoMkDependHS) beginMkDependHS
254
255         -- -ohi sanity checking
256    ohi    <- readIORef v_Output_hi
257    if (isJust ohi && 
258         (mode == DoMake || mode == DoInteractive || srcs `lengthExceeds` 1))
259         then throwDyn (UsageError "-ohi can only be used when compiling a single source file")
260         else do
261
262         -- make/interactive require invoking the compilation manager
263    if (mode == DoMake)        then beginMake srcs        else do
264    if (mode == DoInteractive) then beginInteractive srcs else do
265
266         -- -o sanity checking
267    let real_srcs = filter isSourceFile srcs -- filters out .a and .o that might appear
268    o_file <- readIORef v_Output_file
269    if (real_srcs `lengthExceeds` 1 && isJust o_file && mode /= DoLink && mode /= DoMkDLL)
270         then throwDyn (UsageError "can't apply -o to multiple source files")
271         else do
272
273    if null srcs then throwDyn (UsageError "no input files") else do
274
275    let compileFile src = do
276           restoreDynFlags
277
278           exists <- doesFileExist src
279           when (not exists) $ 
280                 throwDyn (CmdLineError ("file `" ++ src ++ "' does not exist"))
281
282           -- We compile in two stages, because the file may have an
283           -- OPTIONS pragma that affects the compilation pipeline (eg. -fvia-C)
284           let (basename, suffix) = splitFilename src
285
286           -- just preprocess (Haskell source only)
287           let src_and_suff = (src, getFileSuffix src)
288           let not_hs_file  = not (haskellish_src_file src)
289           pp <- if not_hs_file || mode == StopBefore Hsc || mode == StopBefore HsPp
290                         then return src_and_suff else do
291                 phases <- genPipeline (StopBefore Hsc) stop_flag
292                                       False{-not persistent-} defaultHscLang
293                                       src_and_suff
294                 pipeLoop phases src_and_suff False{-no linking-} False{-no -o flag-}
295                         basename suffix
296
297           -- rest of compilation
298           hsc_lang <- dynFlag hscLang
299           phases   <- genPipeline mode stop_flag True hsc_lang pp
300           (r,_)    <- pipeLoop phases pp (mode==DoLink || mode==DoMkDLL)
301                                       True{-use -o flag-} basename suffix
302           return r
303
304    o_files <- mapM compileFile srcs
305
306    when (mode == DoMkDependHS) endMkDependHS
307    when (mode == DoLink) (doLink o_files)
308    when (mode == DoMkDLL) (doMkDLL o_files)
309
310
311
312 beginMake :: [String] -> IO ()
313 beginMake fileish_args
314   = do let (objs, mods) = partition objish_file fileish_args
315        mapM_ (add v_Ld_inputs) objs
316
317        case mods of
318          []    -> throwDyn (UsageError "no input files")
319          _     -> do dflags <- getDynFlags 
320                      state <- cmInit Batch
321                      graph <- cmDepAnal state dflags mods
322                      (_, ok, _) <- cmLoadModules state dflags graph
323                      when (not ok) (exitWith (ExitFailure 1))
324                      return ()
325
326
327 beginInteractive :: [String] -> IO ()
328 #ifndef GHCI
329 beginInteractive = throwDyn (CmdLineError "not built for interactive use")
330 #else
331 beginInteractive fileish_args
332   = do minus_ls <- readIORef v_Cmdline_libraries
333
334        let (objs, mods) = partition objish_file fileish_args
335            libs = map Object objs ++ map DLL minus_ls
336
337        state <- cmInit Interactive
338        interactiveUI state mods libs
339 #endif
340
341 checkOptions :: [String] -> IO ()
342 checkOptions srcs = do
343      -- complain about any unknown flags
344    let unknown_opts = [ f | f@('-':_) <- srcs ]
345    when (notNull unknown_opts) (unknownFlagsErr unknown_opts)
346      -- verify that output files point somewhere sensible.
347    verifyOutputFiles
348      -- and anything else that it might be worth checking for
349      -- before kicking of a compilation (pipeline).
350