[project @ 2002-01-04 11:35:13 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.93 2002/01/04 11:35:13 simonmar Exp $
5 --
6 -- GHC Driver program
7 --
8 -- (c) Simon Marlow 2000
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(ghciWelcomeMsg, 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   ( GhcMode(..), doLink, doMkDLL, genPipeline,
33                           getGhcMode, pipeLoop, v_GhcMode
34                         )
35 import DriverState      ( buildCoreToDo, buildStgToDo, defaultHscLang,
36                           findBuildTag, getPackageInfo, unregFlags, 
37                           v_Cmdline_libraries, v_Keep_tmp_files, v_Ld_inputs,
38                           v_OptLevel, v_Output_file, v_Output_hi, 
39                           v_Package_details, v_Ways, getPackageExtraGhcOpts,
40                           readPackageConf
41                         )
42 import DriverFlags      ( dynFlag, getDynFlags, buildStaticHscOpts,
43                           dynamic_flags, processArgs, static_flags)
44
45 import DriverMkDepend   ( beginMkDependHS, endMkDependHS )
46 import DriverPhases     ( Phase(HsPp, Hsc, HCc), haskellish_src_file, objish_file )
47
48 import DriverUtil       ( add, handle, handleDyn, later, splitFilename,
49                           unknownFlagErr, getFileSuffix )
50 import CmdLineOpts      ( dynFlag, defaultDynFlags, restoreDynFlags,
51                           saveDynFlags, setDynFlags, 
52                           DynFlags(..), HscLang(..), v_Static_hsc_opts
53                         )
54
55 import Outputable
56 import Util
57 import Panic            ( GhcException(..), panic )
58
59 -- Standard Haskell libraries
60 import IO
61 import Directory        ( doesFileExist )
62 import IOExts           ( readIORef, writeIORef )
63 import Exception        ( throwDyn, Exception(..) )
64 import System           ( getArgs, exitWith, ExitCode(..) )
65 import Monad
66 import List
67 import Maybe
68
69 #ifndef mingw32_TARGET_OS
70 import Concurrent       ( myThreadId )
71 #if __GLASGOW_HASKELL__ < 500
72 import Exception        ( raiseInThread )
73 #define throwTo  raiseInThread
74 #else
75 import Exception        ( throwTo )
76 #endif
77
78 import Posix            ( Handler(Catch), installHandler, sigINT, sigQUIT )
79 import Dynamic          ( toDyn )
80 #endif
81
82
83 -----------------------------------------------------------------------------
84 -- Changes:
85
86 -- * -fglasgow-exts NO LONGER IMPLIES -package lang!!!  (-fglasgow-exts is a
87 --   dynamic flag whereas -package is a static flag.)
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 -- removed -noC
108 -- no -Ofile
109
110 -----------------------------------------------------------------------------
111 -- Main loop
112
113 main =
114   -- top-level exception handler: any unrecognised exception is a compiler bug.
115   handle (\exception -> do
116            hFlush stdout
117            case exception of
118                 -- an IO exception probably isn't our fault, so don't panic
119                 IOException _ ->  hPutStr stderr (show exception)
120                 _other        ->  hPutStr stderr (show (Panic (show exception)))
121            exitWith (ExitFailure 1)
122          ) $ do
123
124   -- all error messages are propagated as exceptions
125   handleDyn (\dyn -> do
126                 hFlush stdout
127                 case dyn of
128                      PhaseFailed _ code -> exitWith code
129                      Interrupted -> exitWith (ExitFailure 1)
130                      _ -> do hPutStrLn stderr (show (dyn :: GhcException))
131                              exitWith (ExitFailure 1)
132             ) $ do
133
134    -- make sure we clean up after ourselves
135    later (do  forget_it <- readIORef v_Keep_tmp_files
136               unless forget_it $ do
137               verb <- dynFlag verbosity
138               cleanTempFiles verb
139      ) $ do
140         -- exceptions will be blocked while we clean the temporary files,
141         -- so there shouldn't be any difficulty if we receive further
142         -- signals.
143
144         -- install signal handlers
145 #ifndef mingw32_TARGET_OS
146    main_thread <- myThreadId
147    let sig_handler = Catch (throwTo main_thread 
148                                 (DynException (toDyn Interrupted)))
149    installHandler sigQUIT sig_handler Nothing 
150    installHandler sigINT  sig_handler Nothing
151 #endif
152
153    argv <- getArgs
154    let (minusB_args, argv') = partition (prefixMatch "-B") argv
155    top_dir <- initSysTools minusB_args
156
157         -- Read the package configuration
158    conf_file <- getPackageConfigPath
159    readPackageConf conf_file
160
161         -- find the phase to stop after (i.e. -E, -C, -c, -S flags)
162    (flags2, mode, stop_flag) <- getGhcMode argv'
163    writeIORef v_GhcMode mode
164
165         -- process all the other arguments, and get the source files
166    non_static <- processArgs static_flags flags2 []
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 (not (null 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    opt_level  <- readIORef v_OptLevel
203
204
205    let lang = case mode of 
206                  StopBefore HCc -> HscC
207                  DoInteractive  -> HscInterpreted
208                  _other        | opt_level >= 1  -> HscC  -- -O implies -fvia-C 
209                                | otherwise       -> defaultHscLang
210
211    setDynFlags (defaultDynFlags{ coreToDo = core_todo,
212                                  stgToDo  = stg_todo,
213                                  hscLang  = lang,
214                                  -- leave out hscOutName for now
215                                  hscOutName = panic "Main.main:hscOutName not set",
216
217                                  verbosity = 1
218                                 })
219
220         -- the rest of the arguments are "dynamic"
221    srcs <- processArgs dynamic_flags (extra_non_static ++ non_static) []
222
223         -- save the "initial DynFlags" away
224    saveDynFlags
225
226         -- complain about any unknown flags
227    mapM unknownFlagErr [ f | f@('-':_) <- srcs ]
228
229    verb <- dynFlag verbosity
230
231         -- Show the GHCi banner
232 #  ifdef GHCI
233    when (mode == DoInteractive && verb >= 1) $
234       hPutStrLn stdout ghciWelcomeMsg
235 #  endif
236
237         -- Display details of the configuration in verbose mode
238    when (verb >= 2) 
239         (do hPutStr stderr "Glasgow Haskell Compiler, Version "
240             hPutStr stderr cProjectVersion
241             hPutStr stderr ", for Haskell 98, compiled by GHC version "
242             hPutStrLn stderr cBooterVersion)
243
244    when (verb >= 2) 
245         (hPutStrLn stderr ("Using package config file: " ++ conf_file))
246
247    pkg_details <- readIORef v_Package_details
248    showPackages pkg_details
249
250    when (verb >= 3) 
251         (hPutStrLn stderr ("Hsc static flags: " ++ unwords static_opts))
252
253         -- initialise the finder
254    pkg_avails <- getPackageInfo
255    initFinder pkg_avails
256
257         -- mkdependHS is special
258    when (mode == DoMkDependHS) beginMkDependHS
259
260         -- -ohi sanity checking
261    ohi    <- readIORef v_Output_hi
262    if (isJust ohi && 
263         (mode == DoMake || mode == DoInteractive || srcs `lengthExceeds` 1))
264         then throwDyn (UsageError "-ohi can only be used when compiling a single source file")
265         else do
266
267         -- make/interactive require invoking the compilation manager
268    if (mode == DoMake)        then beginMake srcs        else do
269    if (mode == DoInteractive) then beginInteractive srcs else do
270
271         -- -o sanity checking
272    o_file <- readIORef v_Output_file
273    if (srcs `lengthExceeds` 1 && isJust o_file && mode /= DoLink && mode /= DoMkDLL)
274         then throwDyn (UsageError "can't apply -o to multiple source files")
275         else do
276
277    if null srcs then throwDyn (UsageError "no input files") else do
278
279    let compileFile src = do
280           restoreDynFlags
281
282           exists <- doesFileExist src
283           when (not exists) $ 
284                 throwDyn (CmdLineError ("file `" ++ src ++ "' does not exist"))
285
286           -- We compile in two stages, because the file may have an
287           -- OPTIONS pragma that affects the compilation pipeline (eg. -fvia-C)
288           let (basename, suffix) = splitFilename src
289
290           -- just preprocess (Haskell source only)
291           let src_and_suff = (src, getFileSuffix src)
292           let not_hs_file  = not (haskellish_src_file src)
293           pp <- if not_hs_file || mode == StopBefore Hsc || mode == StopBefore HsPp
294                         then return src_and_suff else do
295                 phases <- genPipeline (StopBefore Hsc) stop_flag
296                                       False{-not persistent-} defaultHscLang
297                                       src_and_suff
298                 pipeLoop phases src_and_suff False{-no linking-} False{-no -o flag-}
299                         basename suffix
300
301           -- rest of compilation
302           hsc_lang <- dynFlag hscLang
303           phases   <- genPipeline mode stop_flag True hsc_lang pp
304           (r,_)    <- pipeLoop phases pp (mode==DoLink || mode==DoMkDLL)
305                                       True{-use -o flag-} basename suffix
306           return r
307
308    o_files <- mapM compileFile srcs
309
310    when (mode == DoMkDependHS) endMkDependHS
311    when (mode == DoLink) (doLink o_files)
312    when (mode == DoMkDLL) (doMkDLL o_files)
313
314
315
316 beginMake :: [String] -> IO ()
317 beginMake fileish_args
318   = do let (objs, mods) = partition objish_file fileish_args
319        mapM (add v_Ld_inputs) objs
320
321        case mods of
322          []    -> throwDyn (UsageError "no input files")
323          _     -> do dflags <- getDynFlags 
324                      state <- cmInit Batch
325                      graph <- cmDepAnal state dflags mods
326                      (_, ok, _) <- cmLoadModules state dflags graph
327                      when (not ok) (exitWith (ExitFailure 1))
328                      return ()
329
330
331 beginInteractive :: [String] -> IO ()
332 #ifndef GHCI
333 beginInteractive = throwDyn (CmdLineError "not built for interactive use")
334 #else
335 beginInteractive fileish_args
336   = do minus_ls <- readIORef v_Cmdline_libraries
337
338        let (objs, mods) = partition objish_file fileish_args
339            libs = map Left objs ++ map Right minus_ls
340
341        state <- cmInit Interactive
342        interactiveUI state mods libs
343 #endif