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