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