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