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