Add a --supported-languages flag
[ghc-hetmet.git] / 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(..), HscTarget(..), 
17                           GhcMode(..), GhcLink(..),
18                           LoadHowMuch(..), dopt, DynFlag(..) )
19 import CmdLineParser
20
21 -- Implementations of the various modes (--show-iface, mkdependHS. etc.)
22 import LoadIface        ( showIface )
23 import HscMain          ( newHscEnv )
24 import DriverPipeline   ( oneShot, compileFile )
25 import DriverMkDepend   ( doMkDependHS )
26 #ifdef GHCI
27 import InteractiveUI    ( interactiveUI, ghciWelcomeMsg )
28 #endif
29
30 -- Various other random stuff that we need
31 import Config
32 import Packages         ( dumpPackages )
33 import DriverPhases     ( Phase(..), isSourceFilename, anyHsc,
34                           startPhase, isHaskellSrcFilename )
35 import StaticFlags
36 import DynFlags
37 import BasicTypes       ( failed )
38 import ErrUtils         ( putMsg )
39 import FastString       ( getFastStringTable, isZEncoded, hasZEncoding )
40 import Outputable
41 import Util
42 import Panic
43
44 -- Standard Haskell libraries
45 import Control.Exception ( throwDyn )
46 import System.IO
47 import System.Directory ( doesDirectoryExist )
48 import System.Environment
49 import System.Exit
50 import Control.Monad
51 import Data.List
52 import Data.Maybe
53
54 -----------------------------------------------------------------------------
55 -- ToDo:
56
57 -- time commands when run with -v
58 -- user ways
59 -- Win32 support: proper signal handling
60 -- reading the package configuration file is too slow
61 -- -K<size>
62
63 -----------------------------------------------------------------------------
64 -- GHC's command-line interface
65
66 main =
67   GHC.defaultErrorHandler defaultDynFlags $ do
68   
69   -- 1. extract the -B flag from the args
70   argv0 <- getArgs
71
72   let
73         (minusB_args, argv1) = partition ("-B" `isPrefixOf`) argv0
74         mbMinusB | null minusB_args = Nothing
75                  | otherwise = Just (drop 2 (last minusB_args))
76
77   argv2 <- parseStaticFlags argv1
78
79   -- 2. Parse the "mode" flags (--make, --interactive etc.)
80   (cli_mode, argv3) <- parseModeFlags argv2
81
82   -- If all we want to do is to show the version number then do it
83   -- now, before we start a GHC session etc.
84   -- If we do it later then bootstrapping gets confused as it tries
85   -- to find out what version of GHC it's using before package.conf
86   -- exists, so starting the session fails.
87   case cli_mode of
88     ShowSupportedLanguages  -> do showSupportedLanguages
89                                   exitWith ExitSuccess
90     ShowVersion             -> do showVersion
91                                   exitWith ExitSuccess
92     ShowNumVersion          -> do putStrLn cProjectVersion
93                                   exitWith ExitSuccess
94     _                       -> return ()
95
96   -- start our GHC session
97   session <- GHC.newSession mbMinusB
98
99   dflags0 <- GHC.getSessionDynFlags session
100
101   -- set the default GhcMode, HscTarget and GhcLink.  The HscTarget
102   -- can be further adjusted on a module by module basis, using only
103   -- the -fvia-C and -fasm flags.  If the default HscTarget is not
104   -- HscC or HscAsm, -fvia-C and -fasm have no effect.
105   let dflt_target = hscTarget dflags0
106       (mode, lang, link)
107          = case cli_mode of
108                 DoInteractive   -> (CompManager, HscInterpreted, LinkInMemory)
109                 DoEval _        -> (CompManager, HscInterpreted, LinkInMemory)
110                 DoMake          -> (CompManager, dflt_target,    LinkBinary)
111                 DoMkDependHS    -> (MkDepend,    dflt_target,    LinkBinary)
112                 _               -> (OneShot,     dflt_target,    LinkBinary)
113
114   let dflags1 = dflags0{ ghcMode   = mode,
115                          hscTarget = lang,
116                          ghcLink   = link,
117                          -- leave out hscOutName for now
118                          hscOutName = panic "Main.main:hscOutName not set",
119                          verbosity = case cli_mode of
120                                          DoEval _ -> 0
121                                          _other   -> 1
122                         }
123
124         -- The rest of the arguments are "dynamic"
125         -- Leftover ones are presumably files
126   (dflags, fileish_args) <- GHC.parseDynamicFlags dflags1 argv3
127
128         -- make sure we clean up after ourselves
129   GHC.defaultCleanupHandler dflags $ do
130
131   showBanner cli_mode dflags
132
133   -- we've finished manipulating the DynFlags, update the session
134   GHC.setSessionDynFlags session dflags
135   dflags <- GHC.getSessionDynFlags session
136
137   let
138      -- To simplify the handling of filepaths, we normalise all filepaths right 
139      -- away - e.g., for win32 platforms, backslashes are converted
140      -- into forward slashes.
141     normal_fileish_paths = map normalisePath fileish_args
142     (srcs, objs)         = partition_args normal_fileish_paths [] []
143
144   -- Note: have v_Ld_inputs maintain the order in which 'objs' occurred on 
145   --       the command-line.
146   mapM_ (consIORef v_Ld_inputs) (reverse objs)
147
148         ---------------- Display configuration -----------
149   when (verbosity dflags >= 4) $
150         dumpPackages dflags
151
152   when (verbosity dflags >= 3) $ do
153         hPutStrLn stderr ("Hsc static flags: " ++ unwords staticFlags)
154
155         ---------------- Final sanity checking -----------
156   checkOptions cli_mode dflags srcs objs
157
158   ---------------- Do the business -----------
159   let alreadyHandled = panic (show cli_mode ++
160                               " should already have been handled")
161   case cli_mode of
162     ShowUsage              -> showGhcUsage dflags cli_mode
163     PrintLibdir            -> putStrLn (topDir dflags)
164     ShowSupportedLanguages -> alreadyHandled
165     ShowVersion            -> alreadyHandled
166     ShowNumVersion         -> alreadyHandled
167     ShowInterface f        -> doShowIface dflags f
168     DoMake                 -> doMake session srcs
169     DoMkDependHS           -> doMkDependHS session (map fst srcs)
170     StopBefore p           -> oneShot dflags p srcs
171     DoInteractive          -> interactiveUI session srcs Nothing
172     DoEval expr            -> interactiveUI session srcs (Just expr)
173
174   dumpFinalStats dflags
175   exitWith ExitSuccess
176
177 #ifndef GHCI
178 interactiveUI _ _ _ = 
179   throwDyn (CmdLineError "not built for interactive use")
180 #endif
181
182 -- -----------------------------------------------------------------------------
183 -- Splitting arguments into source files and object files.  This is where we
184 -- interpret the -x <suffix> option, and attach a (Maybe Phase) to each source
185 -- file indicating the phase specified by the -x option in force, if any.
186
187 partition_args [] srcs objs = (reverse srcs, reverse objs)
188 partition_args ("-x":suff:args) srcs objs
189   | "none" <- suff      = partition_args args srcs objs
190   | StopLn <- phase     = partition_args args srcs (slurp ++ objs)
191   | otherwise           = partition_args rest (these_srcs ++ srcs) objs
192         where phase = startPhase suff
193               (slurp,rest) = break (== "-x") args 
194               these_srcs = zip slurp (repeat (Just phase))
195 partition_args (arg:args) srcs objs
196   | looks_like_an_input arg = partition_args args ((arg,Nothing):srcs) objs
197   | otherwise               = partition_args args srcs (arg:objs)
198
199     {-
200       We split out the object files (.o, .dll) and add them
201       to v_Ld_inputs for use by the linker.
202
203       The following things should be considered compilation manager inputs:
204
205        - haskell source files (strings ending in .hs, .lhs or other 
206          haskellish extension),
207
208        - module names (not forgetting hierarchical module names),
209
210        - and finally we consider everything not containing a '.' to be
211          a comp manager input, as shorthand for a .hs or .lhs filename.
212
213       Everything else is considered to be a linker object, and passed
214       straight through to the linker.
215     -}
216 looks_like_an_input m =  isSourceFilename m 
217                       || looksLikeModuleName m
218                       || '.' `notElem` m
219
220 -- -----------------------------------------------------------------------------
221 -- Option sanity checks
222
223 checkOptions :: CmdLineMode -> DynFlags -> [(String,Maybe Phase)] -> [String] -> IO ()
224      -- Final sanity checking before kicking off a compilation (pipeline).
225 checkOptions cli_mode dflags srcs objs = do
226      -- Complain about any unknown flags
227    let unknown_opts = [ f | (f@('-':_), _) <- srcs ]
228    when (notNull unknown_opts) (unknownFlagsErr unknown_opts)
229
230    when (notNull (filter isRTSWay (wayNames dflags))
231          && isInterpretiveMode cli_mode) $
232         putStrLn ("Warning: -debug, -threaded and -ticky are ignored by GHCi")
233
234         -- -prof and --interactive are not a good combination
235    when (notNull (filter (not . isRTSWay) (wayNames dflags))
236          && isInterpretiveMode cli_mode) $
237       do throwDyn (UsageError 
238                    "--interactive can't be used with -prof or -unreg.")
239         -- -ohi sanity check
240    if (isJust (outputHi dflags) && 
241       (isCompManagerMode cli_mode || srcs `lengthExceeds` 1))
242         then throwDyn (UsageError "-ohi can only be used when compiling a single source file")
243         else do
244
245         -- -o sanity checking
246    if (srcs `lengthExceeds` 1 && isJust (outputFile dflags)
247          && not (isLinkMode cli_mode))
248         then throwDyn (UsageError "can't apply -o to multiple source files")
249         else do
250
251         -- Check that there are some input files
252         -- (except in the interactive case)
253    if null srcs && null objs && needsInputsMode cli_mode
254         then throwDyn (UsageError "no input files")
255         else do
256
257      -- Verify that output files point somewhere sensible.
258    verifyOutputFiles dflags
259
260
261 -- Compiler output options
262
263 -- called to verify that the output files & directories
264 -- point somewhere valid. 
265 --
266 -- The assumption is that the directory portion of these output
267 -- options will have to exist by the time 'verifyOutputFiles'
268 -- is invoked.
269 -- 
270 verifyOutputFiles :: DynFlags -> IO ()
271 verifyOutputFiles dflags = do
272   let odir = objectDir dflags
273   when (isJust odir) $ do
274      let dir = fromJust odir
275      flg <- doesDirectoryExist dir
276      when (not flg) (nonExistentDir "-odir" dir)
277   let ofile = outputFile dflags
278   when (isJust ofile) $ do
279      let fn = fromJust ofile
280      flg <- doesDirNameExist fn
281      when (not flg) (nonExistentDir "-o" fn)
282   let ohi = outputHi dflags
283   when (isJust ohi) $ do
284      let hi = fromJust ohi
285      flg <- doesDirNameExist hi
286      when (not flg) (nonExistentDir "-ohi" hi)
287  where
288    nonExistentDir flg dir = 
289      throwDyn (CmdLineError ("error: directory portion of " ++ 
290                              show dir ++ " does not exist (used with " ++ 
291                              show flg ++ " option.)"))
292
293 -----------------------------------------------------------------------------
294 -- GHC modes of operation
295
296 data CmdLineMode
297   = ShowUsage               -- ghc -?
298   | PrintLibdir             -- ghc --print-libdir
299   | ShowSupportedLanguages  -- ghc --supported-languages
300   | ShowVersion             -- ghc -V/--version
301   | ShowNumVersion          -- ghc --numeric-version
302   | ShowInterface String    -- ghc --show-iface
303   | DoMkDependHS            -- ghc -M
304   | StopBefore Phase        -- ghc -E | -C | -S
305                             -- StopBefore StopLn is the default
306   | DoMake                  -- ghc --make
307   | DoInteractive           -- ghc --interactive
308   | DoEval String           -- ghc -e
309   deriving (Show)
310
311 isInteractiveMode, isInterpretiveMode     :: CmdLineMode -> Bool
312 isLinkMode, isCompManagerMode :: CmdLineMode -> Bool
313
314 isInteractiveMode DoInteractive = True
315 isInteractiveMode _             = False
316
317 -- isInterpretiveMode: byte-code compiler involved
318 isInterpretiveMode DoInteractive = True
319 isInterpretiveMode (DoEval _)    = True
320 isInterpretiveMode _             = False
321
322 needsInputsMode DoMkDependHS    = True
323 needsInputsMode (StopBefore _)  = True
324 needsInputsMode DoMake          = True
325 needsInputsMode _               = False
326
327 -- True if we are going to attempt to link in this mode.
328 -- (we might not actually link, depending on the GhcLink flag)
329 isLinkMode (StopBefore StopLn) = True
330 isLinkMode DoMake              = True
331 isLinkMode _                   = False
332
333 isCompManagerMode DoMake        = True
334 isCompManagerMode DoInteractive = True
335 isCompManagerMode (DoEval _)    = True
336 isCompManagerMode _             = False
337
338
339 -- -----------------------------------------------------------------------------
340 -- Parsing the mode flag
341
342 parseModeFlags :: [String] -> IO (CmdLineMode, [String])
343 parseModeFlags args = do
344   let ((leftover, errs), (mode, _, flags)) = 
345          runCmdLine (processArgs mode_flags args) (StopBefore StopLn, "", []) 
346   when (not (null errs)) $ do
347     throwDyn (UsageError (unlines errs))
348   return (mode, flags ++ leftover)
349
350 type ModeM a = CmdLineP (CmdLineMode, String, [String]) a
351   -- mode flags sometimes give rise to new DynFlags (eg. -C, see below)
352   -- so we collect the new ones and return them.
353
354 mode_flags :: [(String, OptKind (CmdLineP (CmdLineMode, String, [String])))]
355 mode_flags =
356   [  ------- help / version ----------------------------------------------
357      ( "?"               , PassFlag (setMode ShowUsage))
358   ,  ( "-help"           , PassFlag (setMode ShowUsage))
359   ,  ( "-print-libdir"   , PassFlag (setMode PrintLibdir))
360   ,  ( "V"               , PassFlag (setMode ShowVersion))
361   ,  ( "-version"        , PassFlag (setMode ShowVersion))
362   ,  ( "-numeric-version", PassFlag (setMode ShowNumVersion))
363   ,  ( "-supported-languages", PassFlag (setMode ShowSupportedLanguages))
364
365       ------- interfaces ----------------------------------------------------
366   ,  ( "-show-iface"     , HasArg (\f -> setMode (ShowInterface f)
367                                           "--show-iface"))
368
369       ------- primary modes ------------------------------------------------
370   ,  ( "M"              , PassFlag (setMode DoMkDependHS))
371   ,  ( "E"              , PassFlag (setMode (StopBefore anyHsc)))
372   ,  ( "C"              , PassFlag (\f -> do setMode (StopBefore HCc) f
373                                              addFlag "-fvia-C"))
374   ,  ( "S"              , PassFlag (setMode (StopBefore As)))
375   ,  ( "-make"          , PassFlag (setMode DoMake))
376   ,  ( "-interactive"   , PassFlag (setMode DoInteractive))
377   ,  ( "e"              , HasArg   (\s -> setMode (DoEval s) "-e"))
378
379         -- -fno-code says to stop after Hsc but don't generate any code.
380   ,  ( "fno-code"       , PassFlag (\f -> do setMode (StopBefore HCc) f
381                                              addFlag "-fno-code"
382                                              addFlag "-no-recomp"))
383   ]
384
385 setMode :: CmdLineMode -> String -> ModeM ()
386 setMode m flag = do
387   (old_mode, old_flag, flags) <- getCmdLineState
388   when (notNull old_flag && flag /= old_flag) $
389       throwDyn (UsageError 
390           ("cannot use `" ++ old_flag ++ "' with `" ++ flag ++ "'"))
391   putCmdLineState (m, flag, flags)
392
393 addFlag :: String -> ModeM ()
394 addFlag s = do
395   (m, f, flags) <- getCmdLineState
396   putCmdLineState (m, f, s:flags)
397
398
399 -- ----------------------------------------------------------------------------
400 -- Run --make mode
401
402 doMake :: Session -> [(String,Maybe Phase)] -> IO ()
403 doMake sess []    = throwDyn (UsageError "no input files")
404 doMake sess srcs  = do 
405     let (hs_srcs, non_hs_srcs) = partition haskellish srcs
406
407         haskellish (f,Nothing) = 
408           looksLikeModuleName f || isHaskellSrcFilename f || '.' `notElem` f
409         haskellish (f,Just phase) = 
410           phase `notElem` [As, Cc, CmmCpp, Cmm, StopLn]
411
412     dflags <- GHC.getSessionDynFlags sess
413     o_files <- mapM (compileFile dflags StopLn) non_hs_srcs
414     mapM_ (consIORef v_Ld_inputs) (reverse o_files)
415
416     targets <- mapM (uncurry GHC.guessTarget) hs_srcs
417     GHC.setTargets sess targets
418     ok_flag <- GHC.load sess LoadAllTargets
419     when (failed ok_flag) (exitWith (ExitFailure 1))
420     return ()
421
422
423 -- ---------------------------------------------------------------------------
424 -- --show-iface mode
425
426 doShowIface :: DynFlags -> FilePath -> IO ()
427 doShowIface dflags file = do
428   hsc_env <- newHscEnv dflags
429   showIface hsc_env file
430
431 -- ---------------------------------------------------------------------------
432 -- Various banners and verbosity output.
433
434 showBanner :: CmdLineMode -> DynFlags -> IO ()
435 showBanner cli_mode dflags = do
436    let verb = verbosity dflags
437
438 #ifdef GHCI
439    -- Show the GHCi banner
440    when (isInteractiveMode cli_mode && verb >= 1) $ putStrLn ghciWelcomeMsg
441 #endif
442
443    -- Display details of the configuration in verbose mode
444    when (verb >= 2) $
445     do hPutStr stderr "Glasgow Haskell Compiler, Version "
446        hPutStr stderr cProjectVersion
447        hPutStr stderr ", for Haskell 98, stage "
448        hPutStr stderr cStage
449        hPutStr stderr " booted by GHC version "
450        hPutStrLn stderr cBooterVersion
451
452 showSupportedLanguages :: IO ()
453 showSupportedLanguages = do mapM_ putStrLn supportedLanguages
454                             exitWith ExitSuccess
455
456 showVersion :: IO ()
457 showVersion = do
458   putStrLn (cProjectName ++ ", version " ++ cProjectVersion)
459   exitWith ExitSuccess
460
461 showGhcUsage dflags cli_mode = do 
462   let usage_path 
463         | DoInteractive <- cli_mode = ghciUsagePath dflags
464         | otherwise                 = ghcUsagePath dflags
465   usage <- readFile usage_path
466   dump usage
467   exitWith ExitSuccess
468   where
469      dump ""          = return ()
470      dump ('$':'$':s) = putStr progName >> dump s
471      dump (c:s)       = putChar c >> dump s
472
473 dumpFinalStats :: DynFlags -> IO ()
474 dumpFinalStats dflags = 
475   when (dopt Opt_D_faststring_stats dflags) $ dumpFastStringStats dflags
476
477 dumpFastStringStats :: DynFlags -> IO ()
478 dumpFastStringStats dflags = do
479   buckets <- getFastStringTable
480   let (entries, longest, is_z, has_z) = countFS 0 0 0 0 buckets
481       msg = text "FastString stats:" $$
482             nest 4 (vcat [text "size:           " <+> int (length buckets),
483                           text "entries:        " <+> int entries,
484                           text "longest chain:  " <+> int longest,
485                           text "z-encoded:      " <+> (is_z `pcntOf` entries),
486                           text "has z-encoding: " <+> (has_z `pcntOf` entries)
487                          ])
488         -- we usually get more "has z-encoding" than "z-encoded", because
489         -- when we z-encode a string it might hash to the exact same string,
490         -- which will is not counted as "z-encoded".  Only strings whose
491         -- Z-encoding is different from the original string are counted in
492         -- the "z-encoded" total.
493   putMsg dflags msg
494   where
495    x `pcntOf` y = int ((x * 100) `quot` y) <> char '%'
496   
497 countFS entries longest is_z has_z [] = (entries, longest, is_z, has_z)
498 countFS entries longest is_z has_z (b:bs) = 
499   let
500         len = length b
501         longest' = max len longest
502         entries' = entries + len
503         is_zs = length (filter isZEncoded b)
504         has_zs = length (filter hasZEncoding b)
505   in
506         countFS entries' longest' (is_z + is_zs) (has_z + has_zs) bs
507
508 -- -----------------------------------------------------------------------------
509 -- Util
510
511 unknownFlagsErr :: [String] -> a
512 unknownFlagsErr fs = throwDyn (UsageError ("unrecognised flags: " ++ unwords fs))