[project @ 2004-08-12 13:06:51 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.136 2003/11/01 01:01:18 sof 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> \ 
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 =  isSourceFilename 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     -- Note: have v_Ld_inputs maintain the order in which 'objs' occurred on 
226     --       the command-line.
227    mapM_ (add v_Ld_inputs) (reverse objs)
228
229         ---------------- Display banners and configuration -----------
230    showBanners mode conf_file static_opts
231
232         ---------------- Final sanity checking -----------
233    checkOptions mode srcs objs
234
235     -- We always link in the base package in
236     -- one-shot linking.  Any other packages
237     -- required must be given using -package
238     -- options on the command-line.
239    let def_hs_pkgs = [basePackage, haskell98Package]
240
241         ---------------- Do the business -----------
242    case mode of
243         DoMake         -> doMake srcs
244                                
245         DoMkDependHS   -> do { beginMkDependHS ; 
246                                compileFiles mode srcs; 
247                                endMkDependHS }
248         StopBefore p   -> do { compileFiles mode srcs; return () }
249         DoMkDLL        -> do { o_files <- compileFiles mode srcs; 
250                                doMkDLL o_files def_hs_pkgs }
251         DoLink         -> do { o_files <- compileFiles mode srcs; 
252                                omit_linking <- readIORef v_NoLink;
253                                when (not omit_linking)
254                                     (staticLink o_files def_hs_pkgs) }
255
256 #ifndef GHCI
257         DoInteractive -> noInteractiveError
258         DoEval _      -> noInteractiveError
259      where
260        noInteractiveError = throwDyn (CmdLineError "not built for interactive use")
261 #else
262         DoInteractive -> interactiveUI srcs Nothing
263         DoEval expr   -> interactiveUI srcs (Just expr)
264 #endif
265
266 -- -----------------------------------------------------------------------------
267 -- Option sanity checks
268
269 checkOptions :: GhcMode -> [String] -> [String] -> IO ()
270      -- Final sanity checking before kicking off a compilation (pipeline).
271 checkOptions mode srcs objs = do
272      -- Complain about any unknown flags
273    let unknown_opts = [ f | f@('-':_) <- srcs ]
274    when (notNull unknown_opts) (unknownFlagsErr unknown_opts)
275
276         -- -ohi sanity check
277    ohi <- readIORef v_Output_hi
278    if (isJust ohi && 
279       (mode == DoMake || isInteractive mode || srcs `lengthExceeds` 1))
280         then throwDyn (UsageError "-ohi can only be used when compiling a single source file")
281         else do
282
283         -- -o sanity checking
284    o_file <- readIORef v_Output_file
285    if (srcs `lengthExceeds` 1 && isJust o_file && mode /= DoLink && mode /= DoMkDLL)
286         then throwDyn (UsageError "can't apply -o to multiple source files")
287         else do
288
289         -- Check that there are some input files (except in the interactive 
290         -- case)
291    if null srcs && null objs && not (isInteractive mode)
292         then throwDyn (UsageError "no input files")
293         else do
294
295      -- Verify that output files point somewhere sensible.
296    verifyOutputFiles
297
298 isInteractive DoInteractive = True
299 isInteractive (DoEval _)    = True
300 isInteractive _             = False
301
302 -- -----------------------------------------------------------------------------
303 -- Compile files in one-shot mode.
304
305 compileFiles :: GhcMode 
306              -> [String]        -- Source files
307              -> IO [String]     -- Object files
308 compileFiles mode srcs = do
309    stop_flag <- readIORef v_GhcModeFlag
310    mapM (compileFile mode stop_flag) srcs
311
312
313 compileFile mode stop_flag src = do
314    restoreDynFlags
315    
316    exists <- doesFileExist src
317    when (not exists) $ 
318         throwDyn (CmdLineError ("file `" ++ src ++ "' does not exist"))
319    
320    o_file   <- readIORef v_Output_file
321         -- when linking, the -o argument refers to the linker's output. 
322         -- otherwise, we use it as the name for the pipeline's output.
323    let maybe_o_file
324           | mode==DoLink || mode==DoMkDLL  = Nothing
325           | otherwise                      = o_file
326
327    runPipeline mode stop_flag True maybe_o_file src Nothing{-no ModLocation-}
328
329
330 -- ----------------------------------------------------------------------------
331 -- Run --make mode
332
333 doMake :: [String] -> IO ()
334 doMake []    = throwDyn (UsageError "no input files")
335 doMake srcs  = do 
336     dflags <- getDynFlags 
337     state  <- cmInit Batch dflags
338     graph  <- cmDepAnal state srcs
339     (_, ok_flag, _) <- cmLoadModules state graph
340     when (failed ok_flag) (exitWith (ExitFailure 1))
341     return ()
342
343 -- ---------------------------------------------------------------------------
344 -- Various banners and verbosity output.
345
346 showBanners :: GhcMode -> FilePath -> [String] -> IO ()
347 showBanners mode conf_file static_opts = do
348    verb <- dynFlag verbosity
349
350         -- Show the GHCi banner
351 #  ifdef GHCI
352    when (mode == DoInteractive && verb >= 1) $
353       hPutStrLn stdout ghciWelcomeMsg
354 #  endif
355
356         -- Display details of the configuration in verbose mode
357    when (verb >= 2) 
358         (do hPutStr stderr "Glasgow Haskell Compiler, Version "
359             hPutStr stderr cProjectVersion
360             hPutStr stderr ", for Haskell 98, compiled by GHC version "
361             hPutStrLn stderr cBooterVersion)
362
363    when (verb >= 2) 
364         (hPutStrLn stderr ("Using package config file: " ++ conf_file))
365
366    pkg_details <- getPackageConfigMap
367    showPackages pkg_details
368
369    when (verb >= 3) 
370         (hPutStrLn stderr ("Hsc static flags: " ++ unwords static_opts))