[project @ 2000-11-24 09:51:38 by simonpj]
[ghc-hetmet.git] / ghc / compiler / main / Main.hs
1 {-# OPTIONS -W -fno-warn-incomplete-patterns #-}
2 -----------------------------------------------------------------------------
3 -- $Id: Main.hs,v 1.33 2000/11/24 09:51:39 simonpj 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 Interpreter
21 import InteractiveUI
22 import Dynamic
23 #endif
24
25 import CompManager
26 import DriverPipeline
27 import DriverState
28 import DriverFlags
29 import DriverMkDepend
30 import DriverUtil
31 import Panic
32 import DriverPhases     ( Phase(..) )
33 import CmdLineOpts      ( HscLang(..), DynFlags(..), v_Static_hsc_opts )
34 import TmpFiles
35 import Finder           ( initFinder )
36 import CmStaticInfo
37 import Config
38 import Util
39
40
41
42 import Concurrent
43 #ifndef mingw32_TARGET_OS
44 import Posix
45 #endif
46 import Directory
47 import IOExts
48 import Exception
49
50 import IO
51 import Monad
52 import List
53 import System
54 import Maybe
55
56
57 -----------------------------------------------------------------------------
58 -- Changes:
59
60 -- * -fglasgow-exts NO LONGER IMPLIES -package lang!!!  (-fglasgow-exts is a
61 --   dynamic flag whereas -package is a static flag.)
62
63 -----------------------------------------------------------------------------
64 -- ToDo:
65
66 -- -nohi doesn't work
67 -- new mkdependHS doesn't support all the options that the old one did (-X et al.)
68 -- time commands when run with -v
69 -- split marker
70 -- mkDLL
71 -- java generation
72 -- user ways
73 -- Win32 support: proper signal handling
74 -- make sure OPTIONS in .hs file propogate to .hc file if -C or -keep-hc-file-too
75 -- reading the package configuration file is too slow
76 -- -H, -K, -Rghc-timing
77 -- hi-diffs
78 -- -ddump-all doesn't do anything
79
80 -----------------------------------------------------------------------------
81 -- Differences vs. old driver:
82
83 -- No more "Enter your Haskell program, end with ^D (on a line of its own):"
84 -- consistency checking removed (may do this properly later)
85 -- removed -noC
86 -- no hi diffs (could be added later)
87 -- no -Ofile
88
89 -----------------------------------------------------------------------------
90 -- Main loop
91
92 main =
93   -- all error messages are propagated as exceptions
94   handleDyn (\dyn -> case dyn of
95                           PhaseFailed _phase code -> exitWith code
96                           Interrupted -> exitWith (ExitFailure 1)
97                           _ -> do hPutStrLn stderr (show (dyn :: BarfKind))
98                                   exitWith (ExitFailure 1)
99               ) $ do
100
101    -- make sure we clean up after ourselves
102    later (do  forget_it <- readIORef v_Keep_tmp_files
103               unless forget_it $ do
104               verb <- dynFlag verbosity
105               cleanTempFiles (verb >= 2)
106      ) $ do
107         -- exceptions will be blocked while we clean the temporary files,
108         -- so there shouldn't be any difficulty if we receive further
109         -- signals.
110
111         -- install signal handlers
112    main_thread <- myThreadId
113 #ifndef mingw32_TARGET_OS
114    let sig_handler = Catch (throwTo main_thread 
115                                 (DynException (toDyn Interrupted)))
116    installHandler sigQUIT sig_handler Nothing 
117    installHandler sigINT  sig_handler Nothing
118 #endif
119
120    argv   <- getArgs
121
122         -- grab any -B options from the command line first
123    argv'  <- setTopDir argv
124    top_dir <- readIORef v_TopDir
125
126    let installed s = top_dir ++ '/':s
127        inplace s   = top_dir ++ '/':cCURRENT_DIR ++ '/':s
128
129        installed_pkgconfig = installed ("package.conf")
130        inplace_pkgconfig   = inplace (cGHC_DRIVER_DIR ++ "/package.conf.inplace")
131
132         -- discover whether we're running in a build tree or in an installation,
133         -- by looking for the package configuration file.
134    am_installed <- doesFileExist installed_pkgconfig
135
136    if am_installed
137         then writeIORef v_Path_package_config installed_pkgconfig
138         else do am_inplace <- doesFileExist inplace_pkgconfig
139                 if am_inplace
140                     then writeIORef v_Path_package_config inplace_pkgconfig
141                     else throwDyn (OtherError "can't find package.conf")
142
143         -- set the location of our various files
144    if am_installed
145         then do writeIORef v_Path_usage (installed "ghc-usage.txt")
146                 writeIORef v_Pgm_L (installed "unlit")
147                 writeIORef v_Pgm_m (installed "ghc-asm")
148                 writeIORef v_Pgm_s (installed "ghc-split")
149
150         else do writeIORef v_Path_usage (inplace (cGHC_DRIVER_DIR ++ "/ghc-usage.txt"))
151                 writeIORef v_Pgm_L (inplace cGHC_UNLIT)
152                 writeIORef v_Pgm_m (inplace cGHC_MANGLER)
153                 writeIORef v_Pgm_s (inplace cGHC_SPLIT)
154
155         -- read the package configuration
156    conf_file <- readIORef v_Path_package_config
157    contents <- readFile conf_file
158    let pkg_details = read contents      -- ToDo: faster
159    writeIORef v_Package_details pkg_details
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         -- find the build tag, and re-process the build-specific options
169    more_opts <- findBuildTag
170    way_non_static <- processArgs static_flags more_opts []
171
172         -- give the static flags to hsc
173    static_opts <- buildStaticHscOpts
174    writeIORef v_Static_hsc_opts static_opts
175
176         -- warnings
177    warn_level <- readIORef v_Warning_opt
178
179    let warn_opts =  case warn_level of
180                         W_default -> standardWarnings
181                         W_        -> minusWOpts
182                         W_all     -> minusWallOpts
183                         W_not     -> []
184
185         -- build the default DynFlags (these may be adjusted on a per
186         -- module basis by OPTIONS pragmas and settings in the interpreter).
187
188    core_todo <- buildCoreToDo
189    stg_todo  <- buildStgToDo
190
191    -- set the "global" HscLang.  The HscLang can be further adjusted on a module
192    -- by module basis, using only the -fvia-C and -fasm flags.  If the global
193    -- HscLang is not HscC or HscAsm, -fvia-C and -fasm have no effect.
194    opt_level  <- readIORef v_OptLevel
195    let lang = case mode of 
196                  StopBefore HCc -> HscC
197                  DoInteractive  -> HscInterpreted
198                  _other        | opt_level >= 1  -> HscC  -- -O implies -fvia-C 
199                                | otherwise       -> defaultHscLang
200
201    writeIORef v_DynFlags 
202         DynFlags{ coreToDo = core_todo,
203                   stgToDo  = stg_todo,
204                   hscLang  = lang,
205                   -- leave out hscOutName for now
206                   hscOutName = panic "Main.main:hscOutName not set",
207
208                   verbosity = case mode of
209                                 DoInteractive -> 1
210                                 DoMake        -> 1
211                                 _other        -> 0,
212
213                   flags = [] }
214
215         -- the rest of the arguments are "dynamic"
216    srcs <- processArgs dynamic_flags (way_non_static ++ 
217                                         non_static ++ warn_opts) []
218         -- save the "initial DynFlags" away
219    init_dyn_flags <- readIORef v_DynFlags
220    writeIORef v_InitDynFlags init_dyn_flags
221
222         -- complain about any unknown flags
223    mapM unknownFlagErr [ f | f@('-':_) <- srcs ]
224
225         -- save the flag state, because this could be modified by OPTIONS 
226         -- pragmas during the compilation, and we'll need to restore it
227         -- before starting the next compilation.
228    saved_driver_state <- readIORef v_Driver_state
229    writeIORef v_InitDriverState saved_driver_state
230
231    verb <- dynFlag verbosity
232
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         -- initialise the finder
243    pkg_avails <- getPackageInfo
244    initFinder pkg_avails
245
246         -- mkdependHS is special
247    when (mode == DoMkDependHS) beginMkDependHS
248
249         -- make/interactive require invoking the compilation manager
250    if (mode == DoMake)        then beginMake srcs        else do
251    if (mode == DoInteractive) then beginInteractive srcs else do
252
253         -- for each source file, find which phases to run
254    let lang = hscLang init_dyn_flags
255    pipelines <- mapM (genPipeline mode stop_flag True lang) srcs
256    let src_pipelines = zip srcs pipelines
257
258         -- sanity checking
259    o_file <- readIORef v_Output_file
260    ohi    <- readIORef v_Output_hi
261    if length srcs > 1 && (isJust ohi || (isJust o_file && mode /= DoLink))
262         then throwDyn (UsageError "can't apply -o or -ohi options to multiple source files")
263         else do
264
265    if null srcs then throwDyn (UsageError "no input files") else do
266
267    let compileFile (src, phases) = do
268           writeIORef v_Driver_state saved_driver_state
269           writeIORef v_DynFlags init_dyn_flags
270           r <- runPipeline phases src (mode==DoLink) True
271           return r
272
273    o_files <- mapM compileFile src_pipelines
274
275    when (mode == DoMkDependHS) endMkDependHS
276    when (mode == DoLink) (doLink o_files)
277
278         -- grab the last -B option on the command line, and
279         -- set topDir to its value.
280 setTopDir :: [String] -> IO [String]
281 setTopDir args = do
282   let (minusbs, others) = partition (prefixMatch "-B") args
283   (case minusbs of
284     []   -> writeIORef v_TopDir clibdir
285     some -> writeIORef v_TopDir (drop 2 (last some)))
286   return others
287
288 beginMake :: [String] -> IO ()
289 beginMake mods
290   = do case mods of
291          []    -> throwDyn (UsageError "no input files")
292          [mod] -> do state <- cmInit Batch
293                      cmLoadModule state mod
294                      return ()
295          _     -> throwDyn (UsageError "only one module allowed with --make")
296
297
298 beginInteractive :: [String] -> IO ()
299 #ifndef GHCI
300 beginInteractive = throwDyn (OtherError "not build for interactive use")
301 #else
302 beginInteractive mods
303   = do state <- cmInit Interactive
304        (state', ok, ms) 
305           <- case mods of
306                 []    -> return (state, True, [])
307                 [mod] -> cmLoadModule state mod
308                 _     -> throwDyn (UsageError 
309                                     "only one module allowed with --interactive")
310        interactiveUI state' ms
311 #endif