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