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