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