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