[project @ 2005-05-16 13:47:57 by simonmar]
[ghc-hetmet.git] / ghc / compiler / main / Main.hs
1 {-# OPTIONS -fno-warn-incomplete-patterns -optc-DNON_POSIX_SOURCE #-}
2 -----------------------------------------------------------------------------
3 --
4 -- GHC Driver program
5 --
6 -- (c) The University of Glasgow 2005
7 --
8 -----------------------------------------------------------------------------
9
10 module Main (main) where
11
12 #include "HsVersions.h"
13
14 -- The official GHC API
15 import qualified GHC
16 import GHC              ( Session, DynFlags(..), GhcMode(..), HscTarget(..),
17                           LoadHowMuch(..) )
18 import CmdLineParser
19
20 -- Implementations of the various modes (--show-iface, mkdependHS. etc.)
21 import MkIface          ( showIface )
22 import DriverPipeline   ( oneShot, compileFile )
23 import DriverMkDepend   ( doMkDependHS )
24 import SysTools         ( getTopDir, getUsageMsgPaths )
25 #ifdef GHCI
26 import InteractiveUI    ( ghciWelcomeMsg, interactiveUI )
27 #endif
28
29 -- Various other random stuff that we need
30 import Config           ( cProjectVersion, cBooterVersion, cProjectName )
31 import Packages         ( dumpPackages, initPackages )
32 import DriverPhases     ( Phase(..), isSourceSuffix, isSourceFilename, anyHsc,
33                           startPhase, isHaskellSrcFilename )
34 import StaticFlags      ( staticFlags, v_Ld_inputs )
35 import BasicTypes       ( failed )
36 import Util
37 import Panic
38
39 -- Standard Haskell libraries
40 import EXCEPTION        ( throwDyn )
41 import IO
42 import Directory        ( doesFileExist, doesDirectoryExist )
43 import System           ( getArgs, exitWith, ExitCode(..) )
44 import Monad
45 import List
46 import Maybe
47
48 -----------------------------------------------------------------------------
49 -- ToDo:
50
51 -- time commands when run with -v
52 -- user ways
53 -- Win32 support: proper signal handling
54 -- reading the package configuration file is too slow
55 -- -K<size>
56
57 -----------------------------------------------------------------------------
58 -- GHC's command-line interface
59
60 main =
61   GHC.defaultErrorHandler $ do
62   
63   argv0 <- getArgs
64   argv1 <- GHC.init argv0
65
66   -- 2. Parse the "mode" flags (--make, --interactive etc.)
67   (cli_mode, argv2) <- parseModeFlags argv1
68
69   let mode = case cli_mode of
70                 DoInteractive   -> Interactive
71                 DoEval _        -> Interactive
72                 DoMake          -> BatchCompile
73                 DoMkDependHS    -> MkDepend
74                 _               -> OneShot
75
76   -- start our GHC session
77   session <- GHC.newSession mode
78
79   dflags0 <- GHC.getSessionDynFlags session
80
81   -- set the default HscTarget.  The HscTarget can be further
82   -- adjusted on a module by module basis, using only the -fvia-C and
83   -- -fasm flags.  If the default HscTarget is not HscC or HscAsm,
84   -- -fvia-C and -fasm have no effect.
85   let lang = case cli_mode of 
86                  DoInteractive  -> HscInterpreted
87                  DoEval _       -> HscInterpreted
88                  _other         -> hscTarget dflags0
89
90   let dflags1 = dflags0{ ghcMode = mode,
91                          hscTarget  = lang,
92                          -- leave out hscOutName for now
93                          hscOutName = panic "Main.main:hscOutName not set",
94                          verbosity = case cli_mode of
95                                          DoEval _ -> 0
96                                          _other   -> 1
97                         }
98
99         -- The rest of the arguments are "dynamic"
100         -- Leftover ones are presumably files
101   (dflags2, fileish_args) <- GHC.parseDynamicFlags dflags1 argv2
102
103         -- make sure we clean up after ourselves
104   GHC.defaultCleanupHandler dflags2 $ do
105
106         -- Display banner
107   showBanner cli_mode dflags2
108
109         -- Read the package config(s), and process the package-related
110         -- command-line flags
111   dflags <- initPackages dflags2
112
113   -- we've finished manipulating the DynFlags, update the session
114   GHC.setSessionDynFlags session dflags
115
116   let
117      -- To simplify the handling of filepaths, we normalise all filepaths right 
118      -- away - e.g., for win32 platforms, backslashes are converted
119      -- into forward slashes.
120     normal_fileish_paths = map normalisePath fileish_args
121     (srcs, objs)         = partition_args normal_fileish_paths [] []
122
123   -- Note: have v_Ld_inputs maintain the order in which 'objs' occurred on 
124   --       the command-line.
125   mapM_ (consIORef v_Ld_inputs) (reverse objs)
126
127         ---------------- Display configuration -----------
128   when (verbosity dflags >= 4) $
129         dumpPackages dflags
130
131   when (verbosity dflags >= 3) $ do
132         hPutStrLn stderr ("Hsc static flags: " ++ unwords staticFlags)
133
134         ---------------- Final sanity checking -----------
135   checkOptions cli_mode dflags srcs objs
136
137         ---------------- Do the business -----------
138   case cli_mode of
139         ShowUsage       -> showGhcUsage cli_mode
140         PrintLibdir     -> do d <- getTopDir; putStrLn d
141         ShowVersion     -> showVersion
142         ShowNumVersion  -> putStrLn cProjectVersion
143         ShowInterface f -> showIface f
144         DoMake          -> doMake session srcs
145         DoMkDependHS    -> doMkDependHS session (map fst srcs)
146         StopBefore p    -> oneShot dflags p srcs
147         DoInteractive   -> interactiveUI session srcs Nothing
148         DoEval expr     -> interactiveUI session srcs (Just expr)
149
150   exitWith ExitSuccess
151
152 #ifndef GHCI
153 interactiveUI _ _ _ = 
154   throwDyn (CmdLineError "not built for interactive use")
155 #endif
156
157 -- -----------------------------------------------------------------------------
158 -- Splitting arguments into source files and object files.  This is where we
159 -- interpret the -x <suffix> option, and attach a (Maybe Phase) to each source
160 -- file indicating the phase specified by the -x option in force, if any.
161
162 partition_args [] srcs objs = (reverse srcs, reverse objs)
163 partition_args ("-x":suff:args) srcs objs
164   | "none" <- suff      = partition_args args srcs objs
165   | StopLn <- phase     = partition_args args srcs (slurp ++ objs)
166   | otherwise           = partition_args rest (these_srcs ++ srcs) objs
167         where phase = startPhase suff
168               (slurp,rest) = break (== "-x") args 
169               these_srcs = zip slurp (repeat (Just phase))
170 partition_args (arg:args) srcs objs
171   | looks_like_an_input arg = partition_args args ((arg,Nothing):srcs) objs
172   | otherwise               = partition_args args srcs (arg:objs)
173
174     {-
175       We split out the object files (.o, .dll) and add them
176       to v_Ld_inputs for use by the linker.
177
178       The following things should be considered compilation manager inputs:
179
180        - haskell source files (strings ending in .hs, .lhs or other 
181          haskellish extension),
182
183        - module names (not forgetting hierarchical module names),
184
185        - and finally we consider everything not containing a '.' to be
186          a comp manager input, as shorthand for a .hs or .lhs filename.
187
188       Everything else is considered to be a linker object, and passed
189       straight through to the linker.
190     -}
191 looks_like_an_input m =  isSourceFilename m 
192                       || looksLikeModuleName m
193                       || '.' `notElem` m
194
195 -- -----------------------------------------------------------------------------
196 -- Option sanity checks
197
198 checkOptions :: CmdLineMode -> DynFlags -> [(String,Maybe Phase)] -> [String] -> IO ()
199      -- Final sanity checking before kicking off a compilation (pipeline).
200 checkOptions cli_mode dflags srcs objs = do
201      -- Complain about any unknown flags
202    let unknown_opts = [ f | (f@('-':_), _) <- srcs ]
203    when (notNull unknown_opts) (unknownFlagsErr unknown_opts)
204
205         -- -prof and --interactive are not a good combination
206    when (notNull (wayNames dflags)  && isInterpretiveMode cli_mode) $
207       do throwDyn (UsageError 
208                    "--interactive can't be used with -prof, -ticky, -unreg or -smp.")
209         -- -ohi sanity check
210    if (isJust (outputHi dflags) && 
211       (isCompManagerMode cli_mode || srcs `lengthExceeds` 1))
212         then throwDyn (UsageError "-ohi can only be used when compiling a single source file")
213         else do
214
215         -- -o sanity checking
216    if (srcs `lengthExceeds` 1 && isJust (outputFile dflags)
217          && not (isLinkMode cli_mode))
218         then throwDyn (UsageError "can't apply -o to multiple source files")
219         else do
220
221         -- Check that there are some input files
222         -- (except in the interactive case)
223    if null srcs && null objs && needsInputsMode cli_mode
224         then throwDyn (UsageError "no input files")
225         else do
226
227      -- Verify that output files point somewhere sensible.
228    verifyOutputFiles dflags
229
230
231 -- Compiler output options
232
233 -- called to verify that the output files & directories
234 -- point somewhere valid. 
235 --
236 -- The assumption is that the directory portion of these output
237 -- options will have to exist by the time 'verifyOutputFiles'
238 -- is invoked.
239 -- 
240 verifyOutputFiles :: DynFlags -> IO ()
241 verifyOutputFiles dflags = do
242   let odir = outputDir dflags
243   when (isJust odir) $ do
244      let dir = fromJust odir
245      flg <- doesDirectoryExist dir
246      when (not flg) (nonExistentDir "-odir" dir)
247   let ofile = outputFile dflags
248   when (isJust ofile) $ do
249      let fn = fromJust ofile
250      flg <- doesDirNameExist fn
251      when (not flg) (nonExistentDir "-o" fn)
252   let ohi = outputHi dflags
253   when (isJust ohi) $ do
254      let hi = fromJust ohi
255      flg <- doesDirNameExist hi
256      when (not flg) (nonExistentDir "-ohi" hi)
257  where
258    nonExistentDir flg dir = 
259      throwDyn (CmdLineError ("error: directory portion of " ++ 
260                              show dir ++ " does not exist (used with " ++ 
261                              show flg ++ " option.)"))
262
263 -----------------------------------------------------------------------------
264 -- GHC modes of operation
265
266 data CmdLineMode
267   = ShowUsage                   -- ghc -?
268   | PrintLibdir                 -- ghc --print-libdir
269   | ShowVersion                 -- ghc -V/--version
270   | ShowNumVersion              -- ghc --numeric-version
271   | ShowInterface String        -- ghc --show-iface
272   | DoMkDependHS                -- ghc -M
273   | StopBefore Phase            -- ghc -E | -C | -S
274                                 -- StopBefore StopLn is the default
275   | DoMake                      -- ghc --make
276   | DoInteractive               -- ghc --interactive
277   | DoEval String               -- ghc -e
278   deriving (Show)
279
280 isInteractiveMode, isInterpretiveMode     :: CmdLineMode -> Bool
281 isLinkMode, isCompManagerMode :: CmdLineMode -> Bool
282
283 isInteractiveMode DoInteractive = True
284 isInteractiveMode _             = False
285
286 -- isInterpretiveMode: byte-code compiler involved
287 isInterpretiveMode DoInteractive = True
288 isInterpretiveMode (DoEval _)    = True
289 isInterpretiveMode _             = False
290
291 needsInputsMode DoMkDependHS    = True
292 needsInputsMode (StopBefore _)  = True
293 needsInputsMode DoMake          = True
294 needsInputsMode _               = False
295
296 -- True if we are going to attempt to link in this mode.
297 -- (we might not actually link, depending on the GhcLink flag)
298 isLinkMode (StopBefore StopLn) = True
299 isLinkMode DoMake              = True
300 isLinkMode _                   = False
301
302 isCompManagerMode DoMake        = True
303 isCompManagerMode DoInteractive = True
304 isCompManagerMode (DoEval _)    = True
305 isCompManagerMode _             = False
306
307
308 -- -----------------------------------------------------------------------------
309 -- Parsing the mode flag
310
311 parseModeFlags :: [String] -> IO (CmdLineMode, [String])
312 parseModeFlags args = do
313   let ((leftover, errs), (mode, _, flags)) = 
314          runCmdLine (processArgs mode_flags args) (StopBefore StopLn, "", []) 
315   when (not (null errs)) $ do
316     throwDyn (UsageError (unlines errs))
317   return (mode, flags ++ leftover)
318
319 type ModeM a = CmdLineP (CmdLineMode, String, [String]) a
320   -- mode flags sometimes give rise to new DynFlags (eg. -C, see below)
321   -- so we collect the new ones and return them.
322
323 mode_flags :: [(String, OptKind (CmdLineP (CmdLineMode, String, [String])))]
324 mode_flags =
325   [  ------- help / version ----------------------------------------------
326      ( "?"               , PassFlag (setMode ShowUsage))
327   ,  ( "-help"           , PassFlag (setMode ShowUsage))
328   ,  ( "-print-libdir"   , PassFlag (setMode PrintLibdir))
329   ,  ( "V"               , PassFlag (setMode ShowVersion))
330   ,  ( "-version"        , PassFlag (setMode ShowVersion))
331   ,  ( "-numeric-version", PassFlag (setMode ShowNumVersion))
332
333       ------- interfaces ----------------------------------------------------
334   ,  ( "-show-iface"     , HasArg (\f -> setMode (ShowInterface f)
335                                           "--show-iface"))
336
337       ------- primary modes ------------------------------------------------
338   ,  ( "M"              , PassFlag (setMode DoMkDependHS))
339   ,  ( "E"              , PassFlag (setMode (StopBefore anyHsc)))
340   ,  ( "C"              , PassFlag (\f -> do setMode (StopBefore HCc) f
341                                              addFlag "-fvia-C"))
342   ,  ( "S"              , PassFlag (setMode (StopBefore As)))
343   ,  ( "-make"          , PassFlag (setMode DoMake))
344   ,  ( "-interactive"   , PassFlag (setMode DoInteractive))
345   ,  ( "e"              , HasArg   (\s -> setMode (DoEval s) "-e"))
346
347         -- -fno-code says to stop after Hsc but don't generate any code.
348   ,  ( "fno-code"       , PassFlag (\f -> do setMode (StopBefore HCc) f
349                                              addFlag "-fno-code"
350                                              addFlag "-no-recomp"))
351   ]
352
353 setMode :: CmdLineMode -> String -> ModeM ()
354 setMode m flag = do
355   (old_mode, old_flag, flags) <- getCmdLineState
356   when (notNull old_flag && flag /= old_flag) $
357       throwDyn (UsageError 
358           ("cannot use `" ++ old_flag ++ "' with `" ++ flag ++ "'"))
359   putCmdLineState (m, flag, flags)
360
361 addFlag :: String -> ModeM ()
362 addFlag s = do
363   (m, f, flags) <- getCmdLineState
364   putCmdLineState (m, f, s:flags)
365
366
367 -- ----------------------------------------------------------------------------
368 -- Run --make mode
369
370 doMake :: Session -> [(String,Maybe Phase)] -> IO ()
371 doMake sess []    = throwDyn (UsageError "no input files")
372 doMake sess srcs  = do 
373     let (hs_srcs, non_hs_srcs) = partition haskellish srcs
374
375         haskellish (f,Nothing) = looksLikeModuleName f || isHaskellSrcFilename f
376         haskellish (f,Just phase) = 
377           phase `notElem` [As, Cc, CmmCpp, Cmm, StopLn]
378
379     dflags <- GHC.getSessionDynFlags sess
380     o_files <- mapM (compileFile dflags StopLn) non_hs_srcs
381     mapM_ (consIORef v_Ld_inputs) (reverse o_files)
382
383     targets <- mapM (uncurry GHC.guessTarget) hs_srcs
384     GHC.setTargets sess targets
385     ok_flag <- GHC.load sess LoadAllTargets
386     when (failed ok_flag) (exitWith (ExitFailure 1))
387     return ()
388
389 -- ---------------------------------------------------------------------------
390 -- Various banners and verbosity output.
391
392 showBanner :: CmdLineMode -> DynFlags -> IO ()
393 showBanner cli_mode dflags = do
394    let verb = verbosity dflags
395         -- Show the GHCi banner
396 #  ifdef GHCI
397    when (isInteractiveMode cli_mode && verb >= 1) $
398       hPutStrLn stdout ghciWelcomeMsg
399 #  endif
400
401         -- Display details of the configuration in verbose mode
402    when (not (isInteractiveMode cli_mode) && verb >= 2) $
403         do hPutStr stderr "Glasgow Haskell Compiler, Version "
404            hPutStr stderr cProjectVersion
405            hPutStr stderr ", for Haskell 98, compiled by GHC version "
406            hPutStrLn stderr cBooterVersion
407
408 showVersion :: IO ()
409 showVersion = do
410   putStrLn (cProjectName ++ ", version " ++ cProjectVersion)
411   exitWith ExitSuccess
412
413 showGhcUsage cli_mode = do 
414   (ghc_usage_path,ghci_usage_path) <- getUsageMsgPaths
415   let usage_path 
416         | DoInteractive <- cli_mode = ghci_usage_path
417         | otherwise                 = ghc_usage_path
418   usage <- readFile usage_path
419   dump usage
420   exitWith ExitSuccess
421   where
422      dump ""          = return ()
423      dump ('$':'$':s) = hPutStr stderr progName >> dump s
424      dump (c:s)       = hPutChar stderr c >> dump s
425
426 -- -----------------------------------------------------------------------------
427 -- Util
428
429 unknownFlagsErr :: [String] -> a
430 unknownFlagsErr fs = throwDyn (UsageError ("unrecognised flags: " ++ unwords fs))