[project @ 2003-06-04 15:47:58 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.124 2003/06/04 15:47:59 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 CompManager      ( cmInit, cmLoadModules, cmDepAnal )
26 import HscTypes         ( GhciMode(..) )
27 import Config           ( cBooterVersion, cGhcUnregisterised, cProjectVersion )
28 import SysTools         ( getPackageConfigPath, initSysTools, cleanTempFiles )
29 import Packages         ( showPackages, getPackageConfigMap, basePackage,
30                           haskell98Package
31                         )
32 import DriverPipeline   ( staticLink, doMkDLL, runPipeline )
33 import DriverState      ( buildCoreToDo, buildStgToDo,
34                           findBuildTag, 
35                           getPackageExtraGhcOpts, unregFlags, 
36                           v_GhcMode, v_GhcModeFlag, GhcMode(..),
37                           v_Keep_tmp_files, v_Ld_inputs, v_Ways, 
38                           v_OptLevel, v_Output_file, v_Output_hi, 
39                           readPackageConf, verifyOutputFiles, v_NoLink,
40                           v_Build_tag
41                         )
42 import DriverFlags      ( buildStaticHscOpts,
43                           dynamic_flags, processArgs, static_flags)
44
45 import DriverMkDepend   ( beginMkDependHS, endMkDependHS )
46 import DriverPhases     ( isSourceFile )
47
48 import DriverUtil       ( add, handle, handleDyn, later, unknownFlagsErr )
49 import CmdLineOpts      ( dynFlag, restoreDynFlags,
50                           saveDynFlags, setDynFlags, getDynFlags, dynFlag,
51                           DynFlags(..), HscLang(..), v_Static_hsc_opts
52                         )
53 import BasicTypes       ( failed )
54 import Outputable
55 import Util
56 import Panic            ( GhcException(..), panic, installSignalHandlers )
57
58 import DATA_IOREF       ( readIORef, writeIORef )
59 import EXCEPTION        ( throwDyn, Exception(..), 
60                           AsyncException(StackOverflow) )
61
62 -- Standard Haskell libraries
63 import IO
64 import Directory        ( doesFileExist )
65 import System           ( getArgs, exitWith, ExitCode(..) )
66 import Monad
67 import List
68 import Maybe
69
70 -----------------------------------------------------------------------------
71 -- ToDo:
72
73 -- new mkdependHS doesn't support all the options that the old one did (-X et al.)
74 -- time commands when run with -v
75 -- split marker
76 -- java generation
77 -- user ways
78 -- Win32 support: proper signal handling
79 -- make sure OPTIONS in .hs file propogate to .hc file if -C or -keep-hc-file-too
80 -- reading the package configuration file is too slow
81 -- -K<size>
82
83 -----------------------------------------------------------------------------
84 -- Differences vs. old driver:
85
86 -- No more "Enter your Haskell program, end with ^D (on a line of its own):"
87 -- consistency checking removed (may do this properly later)
88 -- no -Ofile
89
90 -----------------------------------------------------------------------------
91 -- Main loop
92
93 main =
94   -- top-level exception handler: any unrecognised exception is a compiler bug.
95   handle (\exception -> do
96            hFlush stdout
97            case exception of
98                 -- an IO exception probably isn't our fault, so don't panic
99                 IOException _ ->  hPutStr stderr (show exception)
100                 AsyncException StackOverflow ->
101                         hPutStrLn stderr "stack overflow: use +RTS -K<size> \ 
102                                          \to increase it"
103                 _other ->  hPutStr stderr (show (Panic (show exception)))
104            exitWith (ExitFailure 1)
105          ) $ do
106
107   -- all error messages are propagated as exceptions
108   handleDyn (\dyn -> do
109                 hFlush stdout
110                 case dyn of
111                      PhaseFailed _ code -> exitWith code
112                      Interrupted -> exitWith (ExitFailure 1)
113                      _ -> do hPutStrLn stderr (show (dyn :: GhcException))
114                              exitWith (ExitFailure 1)
115             ) $ do
116
117    -- make sure we clean up after ourselves
118    later (do  forget_it <- readIORef v_Keep_tmp_files
119               unless forget_it $ do
120               verb <- dynFlag verbosity
121               cleanTempFiles verb
122      ) $ do
123         -- exceptions will be blocked while we clean the temporary files,
124         -- so there shouldn't be any difficulty if we receive further
125         -- signals.
126
127    installSignalHandlers
128
129    argv <- getArgs
130    let (minusB_args, argv') = partition (prefixMatch "-B") argv
131    top_dir <- initSysTools minusB_args
132
133         -- Read the package configuration
134    conf_file <- getPackageConfigPath
135    readPackageConf conf_file
136
137         -- Process all the other arguments, and get the source files
138    non_static <- processArgs static_flags argv' []
139    mode <- readIORef v_GhcMode
140
141         -- -O and --interactive are not a good combination
142         -- ditto with any kind of way selection
143    orig_opt_level <- readIORef v_OptLevel
144    when (orig_opt_level > 0 && mode == DoInteractive) $
145       do putStr "warning: -O conflicts with --interactive; -O turned off.\n"
146          writeIORef v_OptLevel 0
147    orig_ways <- readIORef v_Ways
148    when (notNull orig_ways && mode == DoInteractive) $
149       do throwDyn (UsageError 
150                    "--interactive can't be used with -prof, -ticky, -unreg or -smp.")
151
152         -- Find the build tag, and re-process the build-specific options.
153         -- Also add in flags for unregisterised compilation, if 
154         -- GhcUnregisterised=YES.
155    way_opts <- findBuildTag
156    let unreg_opts | cGhcUnregisterised == "YES" = unregFlags
157                   | otherwise = []
158    pkg_extra_opts <- getPackageExtraGhcOpts
159    extra_non_static <- processArgs static_flags 
160                            (unreg_opts ++ way_opts ++ pkg_extra_opts) []
161
162         -- give the static flags to hsc
163    static_opts <- buildStaticHscOpts
164    writeIORef v_Static_hsc_opts static_opts
165
166    -- build the default DynFlags (these may be adjusted on a per
167    -- module basis by OPTIONS pragmas and settings in the interpreter).
168
169    core_todo <- buildCoreToDo
170    stg_todo  <- buildStgToDo
171
172    -- set the "global" HscLang.  The HscLang can be further adjusted on a module
173    -- by module basis, using only the -fvia-C and -fasm flags.  If the global
174    -- HscLang is not HscC or HscAsm, -fvia-C and -fasm have no effect.
175    dyn_flags <- getDynFlags
176    build_tag <- readIORef v_Build_tag
177    let lang = case mode of 
178                  DoInteractive  -> HscInterpreted
179                  _other | build_tag /= "" -> HscC
180                         | otherwise       -> hscLang dyn_flags
181                 -- for ways other that the normal way, we must 
182                 -- compile via C.
183
184    setDynFlags (dyn_flags{ coreToDo = core_todo,
185                            stgToDo  = stg_todo,
186                            hscLang  = lang,
187                            -- leave out hscOutName for now
188                            hscOutName = panic "Main.main:hscOutName not set",
189                            verbosity = 1
190                         })
191
192         -- The rest of the arguments are "dynamic"
193         -- Leftover ones are presumably files
194    fileish_args <- processArgs dynamic_flags (extra_non_static ++ non_static) []
195
196         -- save the "initial DynFlags" away
197    saveDynFlags
198
199    let
200     {-
201       We split out the object files (.o, .dll) and add them
202       to v_Ld_inputs for use by the linker.
203
204       The following things should be considered compilation manager inputs:
205
206        - haskell source files (strings ending in .hs, .lhs or other 
207          haskellish extension),
208
209        - module names (not forgetting hierarchical module names),
210
211        - and finally we consider everything not containing a '.' to be
212          a comp manager input, as shorthand for a .hs or .lhs filename.
213
214       Everything else is considered to be a linker object, and passed
215       straight through to the linker.
216     -}
217     looks_like_an_input m =  isSourceFile m 
218                           || looksLikeModuleName m
219                           || '.' `notElem` m
220
221     (srcs, objs) = partition looks_like_an_input fileish_args
222
223    mapM_ (add v_Ld_inputs) objs
224
225         ---------------- Display banners and configuration -----------
226    showBanners mode conf_file static_opts
227
228         ---------------- Final sanity checking -----------
229    checkOptions mode srcs objs
230
231         ---------------- Do the business -----------
232    case mode of
233         DoMake         -> doMake srcs
234                                
235         DoMkDependHS   -> do { beginMkDependHS ; 
236                                compileFiles mode srcs; 
237                                endMkDependHS }
238         StopBefore p   -> do { compileFiles mode srcs; return () }
239         DoMkDLL        -> do { o_files <- compileFiles mode srcs; 
240                                doMkDLL o_files }
241         DoLink         -> do { o_files <- compileFiles mode srcs; 
242                                omit_linking <- readIORef v_NoLink;
243                                when (not omit_linking)
244                                     (staticLink o_files 
245                                         [basePackage, haskell98Package]) }
246                         -- We always link in the base package in
247                         -- one-shot linking.  Any other packages
248                         -- required must be given using -package
249                         -- options on the command-line.
250
251 #ifndef GHCI
252         DoInteractive -> throwDyn (CmdLineError "not built for interactive use")
253 #else
254         DoInteractive -> interactiveUI srcs
255 #endif
256
257 -- -----------------------------------------------------------------------------
258 -- Option sanity checks
259
260 checkOptions :: GhcMode -> [String] -> [String] -> IO ()
261      -- Final sanity checking before kicking off a compilation (pipeline).
262 checkOptions mode srcs objs = do
263         -- -ohi sanity check
264    ohi <- readIORef v_Output_hi
265    if (isJust ohi && 
266       (mode == DoMake || mode == DoInteractive || srcs `lengthExceeds` 1))
267         then throwDyn (UsageError "-ohi can only be used when compiling a single source file")
268         else do
269
270         -- -o sanity checking
271    o_file <- readIORef v_Output_file
272    if (srcs `lengthExceeds` 1 && isJust o_file && mode /= DoLink && mode /= DoMkDLL)
273         then throwDyn (UsageError "can't apply -o to multiple source files")
274         else do
275
276         -- Check that there are some input files (except in the interactive 
277         -- case)
278    if null srcs && null objs && mode /= DoInteractive
279         then throwDyn (UsageError "no input files")
280         else do
281
282      -- Complain about any unknown flags
283    let unknown_opts = [ f | f@('-':_) <- srcs ]
284    when (notNull unknown_opts) (unknownFlagsErr unknown_opts)
285
286      -- Verify that output files point somewhere sensible.
287    verifyOutputFiles
288
289
290 -- -----------------------------------------------------------------------------
291 -- Compile files in one-shot mode.
292
293 compileFiles :: GhcMode 
294              -> [String]        -- Source files
295              -> IO [String]     -- Object files
296 compileFiles mode srcs = do
297    stop_flag <- readIORef v_GhcModeFlag
298    mapM (compileFile mode stop_flag) srcs
299
300
301 compileFile mode stop_flag src = do
302    restoreDynFlags
303    
304    exists <- doesFileExist src
305    when (not exists) $ 
306         throwDyn (CmdLineError ("file `" ++ src ++ "' does not exist"))
307    
308    o_file   <- readIORef v_Output_file
309         -- when linking, the -o argument refers to the linker's output. 
310         -- otherwise, we use it as the name for the pipeline's output.
311    let maybe_o_file
312           | mode==DoLink || mode==DoMkDLL  = Nothing
313           | otherwise                      = o_file
314
315    runPipeline mode stop_flag True maybe_o_file src
316
317
318 -- ----------------------------------------------------------------------------
319 -- Run --make mode
320
321 doMake :: [String] -> IO ()
322 doMake []    = throwDyn (UsageError "no input files")
323 doMake srcs  = do 
324     dflags <- getDynFlags 
325     state  <- cmInit Batch
326     graph  <- cmDepAnal state dflags srcs
327     (_, ok_flag, _) <- cmLoadModules state dflags graph
328     when (failed ok_flag) (exitWith (ExitFailure 1))
329     return ()
330
331 -- ---------------------------------------------------------------------------
332 -- Various banners and verbosity output.
333
334 showBanners :: GhcMode -> FilePath -> [String] -> IO ()
335 showBanners mode conf_file static_opts = do
336    verb <- dynFlag verbosity
337
338         -- Show the GHCi banner
339 #  ifdef GHCI
340    when (mode == DoInteractive && verb >= 1) $
341       hPutStrLn stdout ghciWelcomeMsg
342 #  endif
343
344         -- Display details of the configuration in verbose mode
345    when (verb >= 2) 
346         (do hPutStr stderr "Glasgow Haskell Compiler, Version "
347             hPutStr stderr cProjectVersion
348             hPutStr stderr ", for Haskell 98, compiled by GHC version "
349             hPutStrLn stderr cBooterVersion)
350
351    when (verb >= 2) 
352         (hPutStrLn stderr ("Using package config file: " ++ conf_file))
353
354    pkg_details <- getPackageConfigMap
355    showPackages pkg_details
356
357    when (verb >= 3) 
358         (hPutStrLn stderr ("Hsc static flags: " ++ unwords static_opts))