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