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