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