[project @ 2003-10-09 11:58:39 by simonpj]
[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.134 2003/10/09 11:58:57 simonpj 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      ( buildStgToDo,
35                           findBuildTag, 
36                           getPackageExtraGhcOpts, unregFlags, 
37                           v_GhcMode, v_GhcModeFlag, GhcMode(..),
38                           v_Keep_tmp_files, v_Ld_inputs, v_Ways, 
39                           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_ways <- readIORef v_Ways
145    when (notNull orig_ways && isInteractive mode) $
146       do throwDyn (UsageError 
147                    "--interactive can't be used with -prof, -ticky, -unreg or -smp.")
148
149         -- Find the build tag, and re-process the build-specific options.
150         -- Also add in flags for unregisterised compilation, if 
151         -- GhcUnregisterised=YES.
152    way_opts <- findBuildTag
153    let unreg_opts | cGhcUnregisterised == "YES" = unregFlags
154                   | otherwise = []
155    pkg_extra_opts <- getPackageExtraGhcOpts
156    extra_non_static <- processArgs static_flags 
157                            (unreg_opts ++ way_opts ++ pkg_extra_opts) []
158
159         -- Give the static flags to hsc
160    static_opts <- buildStaticHscOpts
161    writeIORef v_Static_hsc_opts static_opts
162
163    -- build the default DynFlags (these may be adjusted on a per
164    -- module basis by OPTIONS pragmas and settings in the interpreter).
165
166    stg_todo  <- buildStgToDo
167
168    -- set the "global" HscLang.  The HscLang can be further adjusted on a module
169    -- by module basis, using only the -fvia-C and -fasm flags.  If the global
170    -- HscLang is not HscC or HscAsm, -fvia-C and -fasm have no effect.
171    dyn_flags <- getDynFlags
172    build_tag <- readIORef v_Build_tag
173    let lang = case mode of 
174                  DoInteractive  -> HscInterpreted
175                  DoEval _       -> HscInterpreted
176                  _other | build_tag /= "" -> HscC
177                         | otherwise       -> hscLang dyn_flags
178                 -- for ways other that the normal way, we must 
179                 -- compile via C.
180
181    setDynFlags (dyn_flags{ stgToDo  = stg_todo,
182                            hscLang  = lang,
183                            -- leave out hscOutName for now
184                            hscOutName = panic "Main.main:hscOutName not set",
185                            verbosity = case mode of
186                                          DoEval _ -> 0
187                                          _other   -> 1
188                         })
189
190         -- The rest of the arguments are "dynamic"
191         -- Leftover ones are presumably files
192    fileish_args <- processArgs dynamic_flags (extra_non_static ++ non_static) []
193
194         -- save the "initial DynFlags" away
195    saveDynFlags
196
197    let
198     {-
199       We split out the object files (.o, .dll) and add them
200       to v_Ld_inputs for use by the linker.
201
202       The following things should be considered compilation manager inputs:
203
204        - haskell source files (strings ending in .hs, .lhs or other 
205          haskellish extension),
206
207        - module names (not forgetting hierarchical module names),
208
209        - and finally we consider everything not containing a '.' to be
210          a comp manager input, as shorthand for a .hs or .lhs filename.
211
212       Everything else is considered to be a linker object, and passed
213       straight through to the linker.
214     -}
215     looks_like_an_input m =  isSourceFile m 
216                           || looksLikeModuleName m
217                           || '.' `notElem` m
218
219      -- To simplify the handling of filepaths, we normalise all filepaths right 
220      -- away - e.g., for win32 platforms, backslashes are converted
221      -- into forward slashes.
222     normal_fileish_paths = map normalisePath fileish_args
223     (srcs, objs)         = partition looks_like_an_input normal_fileish_paths
224
225    mapM_ (add v_Ld_inputs) objs
226
227         ---------------- Display banners and configuration -----------
228    showBanners mode conf_file static_opts
229
230         ---------------- Final sanity checking -----------
231    checkOptions mode srcs objs
232
233     -- We always link in the base package in
234     -- one-shot linking.  Any other packages
235     -- required must be given using -package
236     -- options on the command-line.
237    let def_hs_pkgs = [basePackage, haskell98Package]
238
239         ---------------- Do the business -----------
240    case mode of
241         DoMake         -> doMake srcs
242                                
243         DoMkDependHS   -> do { beginMkDependHS ; 
244                                compileFiles mode srcs; 
245                                endMkDependHS }
246         StopBefore p   -> do { compileFiles mode srcs; return () }
247         DoMkDLL        -> do { o_files <- compileFiles mode srcs; 
248                                doMkDLL o_files def_hs_pkgs }
249         DoLink         -> do { o_files <- compileFiles mode srcs; 
250                                omit_linking <- readIORef v_NoLink;
251                                when (not omit_linking)
252                                     (staticLink o_files def_hs_pkgs) }
253
254 #ifndef GHCI
255         DoInteractive -> noInteractiveError
256         DoEval _      -> noInteractiveError
257      where
258        noInteractiveError = throwDyn (CmdLineError "not built for interactive use")
259 #else
260         DoInteractive -> interactiveUI srcs Nothing
261         DoEval expr   -> interactiveUI srcs (Just expr)
262 #endif
263
264 -- -----------------------------------------------------------------------------
265 -- Option sanity checks
266
267 checkOptions :: GhcMode -> [String] -> [String] -> IO ()
268      -- Final sanity checking before kicking off a compilation (pipeline).
269 checkOptions mode srcs objs = do
270      -- Complain about any unknown flags
271    let unknown_opts = [ f | f@('-':_) <- srcs ]
272    when (notNull unknown_opts) (unknownFlagsErr unknown_opts)
273
274         -- -ohi sanity check
275    ohi <- readIORef v_Output_hi
276    if (isJust ohi && 
277       (mode == DoMake || isInteractive mode || srcs `lengthExceeds` 1))
278         then throwDyn (UsageError "-ohi can only be used when compiling a single source file")
279         else do
280
281         -- -o sanity checking
282    o_file <- readIORef v_Output_file
283    if (srcs `lengthExceeds` 1 && isJust o_file && mode /= DoLink && mode /= DoMkDLL)
284         then throwDyn (UsageError "can't apply -o to multiple source files")
285         else do
286
287         -- Check that there are some input files (except in the interactive 
288         -- case)
289    if null srcs && null objs && not (isInteractive mode)
290         then throwDyn (UsageError "no input files")
291         else do
292
293      -- Verify that output files point somewhere sensible.
294    verifyOutputFiles
295
296 isInteractive DoInteractive = True
297 isInteractive (DoEval _)    = True
298 isInteractive _             = False
299
300 -- -----------------------------------------------------------------------------
301 -- Compile files in one-shot mode.
302
303 compileFiles :: GhcMode 
304              -> [String]        -- Source files
305              -> IO [String]     -- Object files
306 compileFiles mode srcs = do
307    stop_flag <- readIORef v_GhcModeFlag
308    mapM (compileFile mode stop_flag) srcs
309
310
311 compileFile mode stop_flag src = do
312    restoreDynFlags
313    
314    exists <- doesFileExist src
315    when (not exists) $ 
316         throwDyn (CmdLineError ("file `" ++ src ++ "' does not exist"))
317    
318    o_file   <- readIORef v_Output_file
319         -- when linking, the -o argument refers to the linker's output. 
320         -- otherwise, we use it as the name for the pipeline's output.
321    let maybe_o_file
322           | mode==DoLink || mode==DoMkDLL  = Nothing
323           | otherwise                      = o_file
324
325    runPipeline mode stop_flag True maybe_o_file src Nothing{-no ModLocation-}
326
327
328 -- ----------------------------------------------------------------------------
329 -- Run --make mode
330
331 doMake :: [String] -> IO ()
332 doMake []    = throwDyn (UsageError "no input files")
333 doMake srcs  = do 
334     dflags <- getDynFlags 
335     state  <- cmInit Batch dflags
336     graph  <- cmDepAnal state srcs
337     (_, ok_flag, _) <- cmLoadModules state graph
338     when (failed ok_flag) (exitWith (ExitFailure 1))
339     return ()
340
341 -- ---------------------------------------------------------------------------
342 -- Various banners and verbosity output.
343
344 showBanners :: GhcMode -> FilePath -> [String] -> IO ()
345 showBanners mode conf_file static_opts = do
346    verb <- dynFlag verbosity
347
348         -- Show the GHCi banner
349 #  ifdef GHCI
350    when (mode == DoInteractive && verb >= 1) $
351       hPutStrLn stdout ghciWelcomeMsg
352 #  endif
353
354         -- Display details of the configuration in verbose mode
355    when (verb >= 2) 
356         (do hPutStr stderr "Glasgow Haskell Compiler, Version "
357             hPutStr stderr cProjectVersion
358             hPutStr stderr ", for Haskell 98, compiled by GHC version "
359             hPutStrLn stderr cBooterVersion)
360
361    when (verb >= 2) 
362         (hPutStrLn stderr ("Using package config file: " ++ conf_file))
363
364    pkg_details <- getPackageConfigMap
365    showPackages pkg_details
366
367    when (verb >= 3) 
368         (hPutStrLn stderr ("Hsc static flags: " ++ unwords static_opts))