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