[project @ 2005-01-28 12:55:17 by simonmar]
[ghc-hetmet.git] / ghc / compiler / main / DriverFlags.hs
1 -----------------------------------------------------------------------------
2 --
3 -- Driver flags
4 --
5 -- (c) The University of Glasgow 2000-2003
6 --
7 -----------------------------------------------------------------------------
8
9 module DriverFlags ( 
10         processDynamicFlags,
11         processStaticFlags,
12
13         addCmdlineHCInclude,
14         buildStaticHscOpts, 
15         machdepCCOpts,
16
17         processArgs, OptKind(..), -- for DriverMkDepend only
18   ) where
19
20 #include "HsVersions.h"
21
22 import MkIface          ( showIface )
23 import DriverState
24 import DriverPhases
25 import DriverUtil
26 import SysTools
27 import CmdLineOpts
28 import Config
29 import Util
30 import Panic
31 import FastString       ( mkFastString )
32
33 import EXCEPTION
34 import DATA_IOREF       ( IORef, readIORef, writeIORef )
35
36 import System           ( exitWith, ExitCode(..) )
37 import IO
38 import Maybe
39 import Monad
40 import Char
41
42 -----------------------------------------------------------------------------
43 -- Flags
44
45 -- Flag parsing is now done in stages:
46 --
47 --     * parse the initial list of flags and remove any flags understood
48 --       by the driver only.  Determine whether we're in multi-compilation
49 --       or single-compilation mode (done in Main.main).
50 --
51 --     * gather the list of "static" hsc flags, and assign them to the global
52 --       static hsc flags variable.
53 --
54 --     * build the inital DynFlags from the remaining flags.
55 --
56 --     * complain if we've got any flags left over.
57 --
58 --     * for each source file: grab the OPTIONS, and build a new DynFlags
59 --       to pass to the compiler.
60
61 -----------------------------------------------------------------------------
62 -- Process command-line  
63
64 processStaticFlags :: [String] -> IO [String]
65 processStaticFlags opts = processArgs static_flags opts []
66
67 data OptKind
68         = NoArg (IO ())                     -- flag with no argument
69         | HasArg (String -> IO ())          -- flag has an argument (maybe prefix)
70         | SepArg (String -> IO ())          -- flag has a separate argument
71         | Prefix (String -> IO ())          -- flag is a prefix only
72         | OptPrefix (String -> IO ())       -- flag may be a prefix
73         | AnySuffix (String -> IO ())       -- flag is a prefix, pass whole arg to fn
74         | PassFlag  (String -> IO ())       -- flag with no arg, pass flag to fn
75         | PrefixPred (String -> Bool) (String -> IO ())
76         | AnySuffixPred (String -> Bool) (String -> IO ())
77
78 processArgs :: [(String,OptKind)] -> [String] -> [String]
79             -> IO [String]  -- returns spare args
80 processArgs _spec [] spare = return (reverse spare)
81
82 processArgs spec args@(('-':arg):args') spare = do
83   case findArg spec arg of
84     Just (rest,action) -> do args' <- processOneArg action rest args
85                              processArgs spec args' spare
86     Nothing            -> processArgs spec args' (('-':arg):spare)
87
88 processArgs spec (arg:args) spare = 
89   processArgs spec args (arg:spare)
90
91 processOneArg :: OptKind -> String -> [String] -> IO [String]
92 processOneArg action rest (dash_arg@('-':arg):args) =
93   case action of
94         NoArg  io -> 
95                 if rest == ""
96                         then io >> return args
97                         else unknownFlagErr dash_arg
98
99         HasArg fio -> 
100                 if rest /= "" 
101                         then fio rest >> return args
102                         else case args of
103                                 [] -> missingArgErr dash_arg
104                                 (arg1:args1) -> fio arg1 >> return args1
105
106         SepArg fio -> 
107                 case args of
108                         [] -> unknownFlagErr dash_arg
109                         (arg1:args1) -> fio arg1 >> return args1
110
111         Prefix fio -> 
112                 if rest /= ""
113                         then fio rest >> return args
114                         else unknownFlagErr dash_arg
115         
116         PrefixPred p fio -> 
117                 if rest /= ""
118                         then fio rest >> return args
119                         else unknownFlagErr dash_arg
120         
121         OptPrefix fio       -> fio rest >> return args
122
123         AnySuffix fio       -> fio dash_arg >> return args
124
125         AnySuffixPred p fio -> fio dash_arg >> return args
126
127         PassFlag fio  -> 
128                 if rest /= ""
129                         then unknownFlagErr dash_arg
130                         else fio dash_arg >> return args
131
132 findArg :: [(String,OptKind)] -> String -> Maybe (String,OptKind)
133 findArg spec arg
134   = case [ (remove_spaces rest, k) 
135          | (pat,k)   <- spec, 
136            Just rest <- [maybePrefixMatch pat arg],
137            arg_ok k rest arg ] 
138     of
139         []      -> Nothing
140         (one:_) -> Just one
141
142 arg_ok (NoArg _)            rest arg = null rest
143 arg_ok (HasArg _)           rest arg = True
144 arg_ok (SepArg _)           rest arg = null rest
145 arg_ok (Prefix _)           rest arg = notNull rest
146 arg_ok (PrefixPred p _)     rest arg = notNull rest && p rest
147 arg_ok (OptPrefix _)        rest arg = True
148 arg_ok (PassFlag _)         rest arg = null rest 
149 arg_ok (AnySuffix _)        rest arg = True
150 arg_ok (AnySuffixPred p _)  rest arg = p arg
151
152 -----------------------------------------------------------------------------
153 -- Static flags
154
155 -- note that ordering is important in the following list: any flag which
156 -- is a prefix flag (i.e. HasArg, Prefix, OptPrefix, AnySuffix) will override
157 -- flags further down the list with the same prefix.
158
159 static_flags = 
160   [  ------- help / version ----------------------------------------------
161      ( "?"               , NoArg showGhcUsage)
162   ,  ( "-help"           , NoArg showGhcUsage)
163   ,  ( "-print-libdir"   , NoArg (do getTopDir >>= putStrLn
164                                      exitWith ExitSuccess))  
165   ,  ( "V"               , NoArg showVersion)
166   ,  ( "-version"        , NoArg showVersion)
167   ,  ( "-numeric-version", NoArg (do putStrLn cProjectVersion
168                                      exitWith ExitSuccess))
169
170       ------- interfaces ----------------------------------------------------
171   ,  ( "-show-iface"     , HasArg (\f -> do showIface f
172                                             exitWith ExitSuccess))
173
174       ------- verbosity ----------------------------------------------------
175   ,  ( "n"              , NoArg setDryRun )
176
177       ------- primary modes ------------------------------------------------
178   ,  ( "M"              , PassFlag (setMode DoMkDependHS))
179   ,  ( "E"              , PassFlag (setMode (StopBefore anyHsc)))
180   ,  ( "C"              , PassFlag (\f -> do setMode (StopBefore HCc) f
181                                              setTarget HscC))
182   ,  ( "S"              , PassFlag (setMode (StopBefore As)))
183   ,  ( "-make"          , PassFlag (setMode DoMake))
184   ,  ( "-interactive"   , PassFlag (setMode DoInteractive))
185   ,  ( "-mk-dll"        , PassFlag (setMode DoMkDLL))
186   ,  ( "e"              , HasArg   (\s -> setMode (DoEval s) "-e"))
187
188         -- -fno-code says to stop after Hsc but don't generate any code.
189   ,  ( "fno-code"       , PassFlag (\f -> do setMode (StopBefore HCc) f
190                                              setTarget HscNothing
191                                              setRecompFlag False))
192
193         ------- GHCi -------------------------------------------------------
194   ,  ( "ignore-dot-ghci", NoArg (writeIORef v_Read_DotGHCi False) )
195   ,  ( "read-dot-ghci"  , NoArg (writeIORef v_Read_DotGHCi True) )
196
197         ------- recompilation checker --------------------------------------
198   ,  ( "recomp"         , NoArg (setRecompFlag True) )
199   ,  ( "no-recomp"      , NoArg (setRecompFlag False) )
200
201         ------- ways --------------------------------------------------------
202   ,  ( "prof"           , NoArg (addNoDups v_Ways       WayProf) )
203   ,  ( "unreg"          , NoArg (addNoDups v_Ways       WayUnreg) )
204   ,  ( "ticky"          , NoArg (addNoDups v_Ways       WayTicky) )
205   ,  ( "parallel"       , NoArg (addNoDups v_Ways       WayPar) )
206   ,  ( "gransim"        , NoArg (addNoDups v_Ways       WayGran) )
207   ,  ( "smp"            , NoArg (addNoDups v_Ways       WaySMP) )
208   ,  ( "debug"          , NoArg (addNoDups v_Ways       WayDebug) )
209   ,  ( "ndp"            , NoArg (addNoDups v_Ways       WayNDP) )
210   ,  ( "threaded"       , NoArg (addNoDups v_Ways       WayThreaded) )
211         -- ToDo: user ways
212
213         ------ RTS ways -----------------------------------------------------
214
215         ------ Debugging ----------------------------------------------------
216   ,  ( "dppr-noprags",     PassFlag (add v_Opt_C) )
217   ,  ( "dppr-debug",       PassFlag (add v_Opt_C) )
218   ,  ( "dppr-user-length", AnySuffix (add v_Opt_C) )
219       -- rest of the debugging flags are dynamic
220
221         --------- Profiling --------------------------------------------------
222   ,  ( "auto-dicts"     , NoArg (add v_Opt_C "-fauto-sccs-on-dicts") )
223   ,  ( "auto-all"       , NoArg (add v_Opt_C "-fauto-sccs-on-all-toplevs") )
224   ,  ( "auto"           , NoArg (add v_Opt_C "-fauto-sccs-on-exported-toplevs") )
225   ,  ( "caf-all"        , NoArg (add v_Opt_C "-fauto-sccs-on-individual-cafs") )
226          -- "ignore-sccs"  doesn't work  (ToDo)
227
228   ,  ( "no-auto-dicts"  , NoArg (add v_Anti_opt_C "-fauto-sccs-on-dicts") )
229   ,  ( "no-auto-all"    , NoArg (add v_Anti_opt_C "-fauto-sccs-on-all-toplevs") )
230   ,  ( "no-auto"        , NoArg (add v_Anti_opt_C "-fauto-sccs-on-exported-toplevs") )
231   ,  ( "no-caf-all"     , NoArg (add v_Anti_opt_C "-fauto-sccs-on-individual-cafs") )
232
233         ------- Miscellaneous -----------------------------------------------
234   ,  ( "no-link-chk"    , NoArg (return ()) ) -- ignored for backwards compat
235   ,  ( "no-hs-main"     , NoArg (writeIORef v_NoHsMain True) )
236   ,  ( "main-is"        , SepArg setMainIs )
237
238         ------- Output Redirection ------------------------------------------
239   ,  ( "odir"           , HasArg (writeIORef v_Output_dir  . Just) )
240   ,  ( "o"              , SepArg (writeIORef v_Output_file . Just) )
241   ,  ( "osuf"           , HasArg (writeIORef v_Object_suf) )
242   ,  ( "hcsuf"          , HasArg (writeIORef v_HC_suf    ) )
243   ,  ( "hisuf"          , HasArg (writeIORef v_Hi_suf    ) )
244   ,  ( "hidir"          , HasArg (writeIORef v_Hi_dir . Just) )
245   ,  ( "buildtag"       , HasArg (writeIORef v_Build_tag) )
246   ,  ( "tmpdir"         , HasArg setTmpDir)
247   ,  ( "ohi"            , HasArg (writeIORef v_Output_hi   . Just) )
248         -- -odump?
249
250   ,  ( "keep-hc-file"   , AnySuffix (\_ -> writeIORef v_Keep_hc_files True) )
251   ,  ( "keep-s-file"    , AnySuffix (\_ -> writeIORef v_Keep_s_files  True) )
252   ,  ( "keep-raw-s-file", AnySuffix (\_ -> writeIORef v_Keep_raw_s_files  True) )
253 #ifdef ILX
254   ,  ( "keep-il-file"   , AnySuffix (\_ -> writeIORef v_Keep_il_files True) )
255   ,  ( "keep-ilx-file"  , AnySuffix (\_ -> writeIORef v_Keep_ilx_files True) )
256 #endif
257   ,  ( "keep-tmp-files" , AnySuffix (\_ -> writeIORef v_Keep_tmp_files True) )
258
259   ,  ( "split-objs"     , NoArg (if can_split
260                                     then do writeIORef v_Split_object_files True
261                                             add v_Opt_C "-fglobalise-toplev-names"
262                                     else hPutStrLn stderr
263                                             "warning: don't know how to split object files on this architecture"
264                                 ) )
265
266         ------- Include/Import Paths ----------------------------------------
267   ,  ( "I"              , Prefix    (addToDirList v_Include_paths) )
268
269         ------- Libraries ---------------------------------------------------
270   ,  ( "L"              , Prefix (addToDirList v_Library_paths) )
271   ,  ( "l"              , AnySuffix (\s -> add v_Opt_l s >> add v_Opt_dll s) )
272
273 #ifdef darwin_TARGET_OS
274         ------- Frameworks --------------------------------------------------
275         -- -framework-path should really be -F ...
276   ,  ( "framework-path" , HasArg (addToDirList v_Framework_paths) )
277   ,  ( "framework"      , HasArg (add v_Cmdline_frameworks) )
278 #endif
279         ------- Specific phases  --------------------------------------------
280   ,  ( "pgmL"           , HasArg setPgmL )
281   ,  ( "pgmP"           , HasArg setPgmP )
282   ,  ( "pgmF"           , HasArg setPgmF )
283   ,  ( "pgmc"           , HasArg setPgmc )
284   ,  ( "pgmm"           , HasArg setPgmm )
285   ,  ( "pgms"           , HasArg setPgms )
286   ,  ( "pgma"           , HasArg setPgma )
287   ,  ( "pgml"           , HasArg setPgml )
288   ,  ( "pgmdll"         , HasArg setPgmDLL )
289 #ifdef ILX
290   ,  ( "pgmI"           , HasArg setPgmI )
291   ,  ( "pgmi"           , HasArg setPgmi )
292 #endif
293
294   ,  ( "optdep"         , HasArg (add v_Opt_dep) )
295   ,  ( "optl"           , HasArg (add v_Opt_l) )
296   ,  ( "optdll"         , HasArg (add v_Opt_dll) )
297
298         ----- Linker --------------------------------------------------------
299   ,  ( "c"              , NoArg (writeIORef v_NoLink True) )
300   ,  ( "no-link"        , NoArg (writeIORef v_NoLink True) )    -- Deprecated
301   ,  ( "static"         , NoArg (writeIORef v_Static True) )
302   ,  ( "dynamic"        , NoArg (writeIORef v_Static False) )
303   ,  ( "rdynamic"       , NoArg (return ()) ) -- ignored for compat w/ gcc
304
305         ----- RTS opts ------------------------------------------------------
306   ,  ( "H"                 , HasArg (setHeapSize . fromIntegral . decodeSize) )
307   ,  ( "Rghc-timing"       , NoArg  (enableTimingStats) )
308
309         ------ Compiler flags -----------------------------------------------
310   ,  ( "fno-asm-mangling"  , NoArg (writeIORef v_Do_asm_mangling False) )
311
312   ,  ( "fexcess-precision" , NoArg (do writeIORef v_Excess_precision True
313                                        add v_Opt_C "-fexcess-precision"))
314
315         -- All other "-fno-<blah>" options cancel out "-f<blah>" on the hsc cmdline
316   ,  ( "fno-",                  PrefixPred (\s -> isStaticHscFlag ("f"++s))
317                                     (\s -> add v_Anti_opt_C ("-f"++s)) )
318
319         -- Pass all remaining "-f<blah>" options to hsc
320   ,  ( "f",                     AnySuffixPred (isStaticHscFlag) (add v_Opt_C) )
321   ]
322
323 dynamic_flags = [
324
325      ( "cpp",           NoArg  (updDynFlags (\s -> s{ cppFlag = True })) )
326   ,  ( "F",             NoArg  (updDynFlags (\s -> s{ ppFlag = True })) )
327   ,  ( "#include",      HasArg (addCmdlineHCInclude) )
328
329   ,  ( "v",             OptPrefix (setVerbosity) )
330
331   ,  ( "optL",          HasArg (addOpt_L) )
332   ,  ( "optP",          HasArg (addOpt_P) )
333   ,  ( "optF",          HasArg (addOpt_F) )
334   ,  ( "optc",          HasArg (addOpt_c) )
335   ,  ( "optm",          HasArg (addOpt_m) )
336   ,  ( "opta",          HasArg (addOpt_a) )
337 #ifdef ILX
338   ,  ( "optI",          HasArg (addOpt_I) )
339   ,  ( "opti",          HasArg (addOpt_i) )
340 #endif
341
342         ------- Packages ----------------------------------------------------
343   ,  ( "package-conf"   , HasArg extraPkgConf_ )
344   ,  ( "no-user-package-conf", NoArg noUserPkgConf_ )
345   ,  ( "package-name"   , HasArg ignorePackage ) -- for compatibility
346   ,  ( "package"        , HasArg exposePackage )
347   ,  ( "hide-package"   , HasArg hidePackage )
348   ,  ( "ignore-package" , HasArg ignorePackage )
349   ,  ( "syslib"         , HasArg exposePackage )  -- for compatibility
350
351         ------ HsCpp opts ---------------------------------------------------
352   ,  ( "D",             AnySuffix addOpt_P )
353   ,  ( "U",             AnySuffix addOpt_P )
354
355         ------- Paths & stuff -----------------------------------------------
356   ,  ( "i"              , OptPrefix addImportPath )
357
358         ------ Debugging ----------------------------------------------------
359   ,  ( "dstg-stats",    NoArg (writeIORef v_StgStats True) )
360
361   ,  ( "ddump-cmm",              setDumpFlag Opt_D_dump_cmm)
362   ,  ( "ddump-asm",              setDumpFlag Opt_D_dump_asm)
363   ,  ( "ddump-cpranal",          setDumpFlag Opt_D_dump_cpranal)
364   ,  ( "ddump-deriv",            setDumpFlag Opt_D_dump_deriv)
365   ,  ( "ddump-ds",               setDumpFlag Opt_D_dump_ds)
366   ,  ( "ddump-flatC",            setDumpFlag Opt_D_dump_flatC)
367   ,  ( "ddump-foreign",          setDumpFlag Opt_D_dump_foreign)
368   ,  ( "ddump-inlinings",        setDumpFlag Opt_D_dump_inlinings)
369   ,  ( "ddump-occur-anal",       setDumpFlag Opt_D_dump_occur_anal)
370   ,  ( "ddump-parsed",           setDumpFlag Opt_D_dump_parsed)
371   ,  ( "ddump-rn",               setDumpFlag Opt_D_dump_rn)
372   ,  ( "ddump-simpl",            setDumpFlag Opt_D_dump_simpl)
373   ,  ( "ddump-simpl-iterations", setDumpFlag Opt_D_dump_simpl_iterations)
374   ,  ( "ddump-spec",             setDumpFlag Opt_D_dump_spec)
375   ,  ( "ddump-prep",             setDumpFlag Opt_D_dump_prep)
376   ,  ( "ddump-stg",              setDumpFlag Opt_D_dump_stg)
377   ,  ( "ddump-stranal",          setDumpFlag Opt_D_dump_stranal)
378   ,  ( "ddump-tc",               setDumpFlag Opt_D_dump_tc)
379   ,  ( "ddump-types",            setDumpFlag Opt_D_dump_types)
380   ,  ( "ddump-rules",            setDumpFlag Opt_D_dump_rules)
381   ,  ( "ddump-cse",              setDumpFlag Opt_D_dump_cse)
382   ,  ( "ddump-worker-wrapper",   setDumpFlag Opt_D_dump_worker_wrapper)
383   ,  ( "ddump-rn-trace",         setDumpFlag Opt_D_dump_rn_trace)
384   ,  ( "ddump-if-trace",         setDumpFlag Opt_D_dump_if_trace)
385   ,  ( "ddump-tc-trace",         setDumpFlag Opt_D_dump_tc_trace)
386   ,  ( "ddump-splices",          setDumpFlag Opt_D_dump_splices)
387   ,  ( "ddump-rn-stats",         setDumpFlag Opt_D_dump_rn_stats)
388   ,  ( "ddump-opt-cmm",          setDumpFlag Opt_D_dump_opt_cmm)
389   ,  ( "ddump-simpl-stats",      setDumpFlag Opt_D_dump_simpl_stats)
390   ,  ( "ddump-bcos",             setDumpFlag Opt_D_dump_BCOs)
391   ,  ( "dsource-stats",          setDumpFlag Opt_D_source_stats)
392   ,  ( "dverbose-core2core",     setDumpFlag Opt_D_verbose_core2core)
393   ,  ( "dverbose-stg2stg",       setDumpFlag Opt_D_verbose_stg2stg)
394   ,  ( "ddump-hi-diffs",         setDumpFlag Opt_D_dump_hi_diffs)
395   ,  ( "ddump-hi",               setDumpFlag Opt_D_dump_hi)
396   ,  ( "ddump-minimal-imports",  setDumpFlag Opt_D_dump_minimal_imports)
397   ,  ( "ddump-vect",             setDumpFlag Opt_D_dump_vect)
398   ,  ( "dcore-lint",             setDumpFlag Opt_DoCoreLinting)
399   ,  ( "dstg-lint",              setDumpFlag Opt_DoStgLinting)
400   ,  ( "dcmm-lint",              setDumpFlag Opt_DoCmmLinting)
401   ,  ( "dshow-passes",           NoArg (setRecompFlag False >> setVerbosity "2") )
402
403         ------ Machine dependant (-m<blah>) stuff ---------------------------
404
405   ,  ( "monly-2-regs",  NoArg (updDynFlags (\s -> s{stolen_x86_regs = 2}) ))
406   ,  ( "monly-3-regs",  NoArg (updDynFlags (\s -> s{stolen_x86_regs = 3}) ))
407   ,  ( "monly-4-regs",  NoArg (updDynFlags (\s -> s{stolen_x86_regs = 4}) ))
408
409         ------ Warning opts -------------------------------------------------
410   ,  ( "W"              , NoArg (mapM_ setDynFlag   minusWOpts)    )
411   ,  ( "Werror"         , NoArg (setDynFlag         Opt_WarnIsError) )
412   ,  ( "Wall"           , NoArg (mapM_ setDynFlag   minusWallOpts) )
413   ,  ( "Wnot"           , NoArg (mapM_ unSetDynFlag minusWallOpts) ) /* DEPREC */
414   ,  ( "w"              , NoArg (mapM_ unSetDynFlag minusWallOpts) )
415
416         ------ Optimisation flags ------------------------------------------
417   ,  ( "O"                 , NoArg (setOptLevel 1))
418   ,  ( "Onot"              , NoArg (setOptLevel 0))
419   ,  ( "O"                 , PrefixPred (all isDigit) (setOptLevel . read))
420
421   ,  ( "fmax-simplifier-iterations", 
422                 PrefixPred (all isDigit) 
423                   (\n -> updDynFlags (\dfs -> 
424                         dfs{ maxSimplIterations = read n })) )
425
426   ,  ( "frule-check", 
427                 SepArg (\s -> updDynFlags (\dfs -> dfs{ ruleCheck = Just s })))
428
429         ------ Compiler flags -----------------------------------------------
430
431   ,  ( "fasm",          AnySuffix (\_ -> setTarget HscAsm) )
432   ,  ( "fvia-c",        NoArg (setTarget HscC) )
433   ,  ( "fvia-C",        NoArg (setTarget HscC) )
434   ,  ( "filx",          NoArg (setTarget HscILX) )
435
436   ,  ( "fglasgow-exts",    NoArg (mapM_ setDynFlag   glasgowExtsFlags) )
437   ,  ( "fno-glasgow-exts", NoArg (mapM_ unSetDynFlag glasgowExtsFlags) )
438
439         -- the rest of the -f* and -fno-* flags
440   ,  ( "fno-",          PrefixPred (\f -> isFFlag f) (\f -> unSetDynFlag (getFFlag f)) )
441   ,  ( "f",             PrefixPred (\f -> isFFlag f) (\f -> setDynFlag (getFFlag f)) )
442  ]
443
444 -- these -f<blah> flags can all be reversed with -fno-<blah>
445
446 fFlags = [
447   ( "warn-duplicate-exports",           Opt_WarnDuplicateExports ),
448   ( "warn-hi-shadowing",                Opt_WarnHiShadows ),
449   ( "warn-incomplete-patterns",         Opt_WarnIncompletePatterns ),
450   ( "warn-incomplete-record-updates",   Opt_WarnIncompletePatternsRecUpd ),
451   ( "warn-missing-fields",              Opt_WarnMissingFields ),
452   ( "warn-missing-methods",             Opt_WarnMissingMethods ),
453   ( "warn-missing-signatures",          Opt_WarnMissingSigs ),
454   ( "warn-name-shadowing",              Opt_WarnNameShadowing ),
455   ( "warn-overlapping-patterns",        Opt_WarnOverlappingPatterns ),
456   ( "warn-simple-patterns",             Opt_WarnSimplePatterns ),
457   ( "warn-type-defaults",               Opt_WarnTypeDefaults ),
458   ( "warn-unused-binds",                Opt_WarnUnusedBinds ),
459   ( "warn-unused-imports",              Opt_WarnUnusedImports ),
460   ( "warn-unused-matches",              Opt_WarnUnusedMatches ),
461   ( "warn-deprecations",                Opt_WarnDeprecations ),
462   ( "warn-orphans",                     Opt_WarnOrphans ),
463   ( "fi",                               Opt_FFI ),  -- support `-ffi'...
464   ( "ffi",                              Opt_FFI ),  -- ...and also `-fffi'
465   ( "arrows",                           Opt_Arrows ), -- arrow syntax
466   ( "parr",                             Opt_PArr ),
467   ( "th",                               Opt_TH ),
468   ( "implicit-prelude",                 Opt_ImplicitPrelude ),
469   ( "scoped-type-variables",            Opt_ScopedTypeVariables ),
470   ( "monomorphism-restriction",         Opt_MonomorphismRestriction ),
471   ( "implicit-params",                  Opt_ImplicitParams ),
472   ( "allow-overlapping-instances",      Opt_AllowOverlappingInstances ),
473   ( "allow-undecidable-instances",      Opt_AllowUndecidableInstances ),
474   ( "allow-incoherent-instances",       Opt_AllowIncoherentInstances ),
475   ( "generics",                         Opt_Generics ),
476   ( "strictness",                       Opt_Strictness ),
477   ( "full-laziness",                    Opt_FullLaziness ),
478   ( "cse",                              Opt_CSE ),
479   ( "ignore-interface-pragmas",         Opt_IgnoreInterfacePragmas ),
480   ( "omit-interface-pragmas",           Opt_OmitInterfacePragmas ),
481   ( "do-lambda-eta-expansion",          Opt_DoLambdaEtaExpansion ),
482   ( "ignore-asserts",                   Opt_IgnoreAsserts ),
483   ( "do-eta-reduction",                 Opt_DoEtaReduction ),
484   ( "case-merge",                       Opt_CaseMerge ),
485   ( "unbox-strict-fields",              Opt_UnboxStrictFields )
486   ]
487
488 glasgowExtsFlags = [ Opt_GlasgowExts, Opt_FFI, Opt_TH, Opt_ImplicitParams, Opt_ScopedTypeVariables ]
489
490 isFFlag f = f `elem` (map fst fFlags)
491 getFFlag f = fromJust (lookup f fFlags)
492
493 -- -----------------------------------------------------------------------------
494 -- Parsing the dynamic flags.
495
496 -- we use a temporary global variable, for convenience
497
498 GLOBAL_VAR(v_DynFlags, defaultDynFlags, DynFlags)
499
500 processDynamicFlags :: [String] -> DynFlags -> IO (DynFlags,[String])
501 processDynamicFlags args dflags = do
502   writeIORef v_DynFlags dflags
503   spare <- processArgs dynamic_flags args []
504   dflags <- readIORef v_DynFlags
505   return (dflags,spare)
506
507 updDynFlags :: (DynFlags -> DynFlags) -> IO ()
508 updDynFlags f = do dfs <- readIORef v_DynFlags
509                    writeIORef v_DynFlags (f dfs)
510
511 setDynFlag, unSetDynFlag :: DynFlag -> IO ()
512 setDynFlag f   = updDynFlags (\dfs -> dopt_set dfs f)
513 unSetDynFlag f = updDynFlags (\dfs -> dopt_unset dfs f)
514
515 setDumpFlag :: DynFlag -> OptKind
516 setDumpFlag dump_flag 
517   = NoArg (setRecompFlag False >> setDynFlag dump_flag)
518         -- Whenver we -ddump, switch off the recompilation checker,
519         -- else you don't see the dump!
520
521 addOpt_L a = updDynFlags (\s -> s{opt_L = a : opt_L s})
522 addOpt_P a = updDynFlags (\s -> s{opt_P = a : opt_P s})
523 addOpt_F a = updDynFlags (\s -> s{opt_F = a : opt_F s})
524 addOpt_c a = updDynFlags (\s -> s{opt_c = a : opt_c s})
525 addOpt_a a = updDynFlags (\s -> s{opt_a = a : opt_a s})
526 addOpt_m a = updDynFlags (\s -> s{opt_m = a : opt_m s})
527 #ifdef ILX
528 addOpt_I a = updDynFlags (\s -> s{opt_I = a : opt_I s})
529 addOpt_i a = updDynFlags (\s -> s{opt_i = a : opt_i s})
530 #endif
531
532 setRecompFlag :: Bool -> IO ()
533 setRecompFlag recomp = updDynFlags (\dfs -> dfs{ recompFlag = recomp })
534
535 setVerbosity "" = updDynFlags (\dfs -> dfs{ verbosity = 3 })
536 setVerbosity n 
537   | all isDigit n = updDynFlags (\dfs -> dfs{ verbosity = read n })
538   | otherwise     = throwDyn (UsageError "can't parse verbosity flag (-v<n>)")
539
540 addCmdlineHCInclude a = updDynFlags (\s -> s{cmdlineHcIncludes =  a : cmdlineHcIncludes s})
541
542 extraPkgConf_  p = updDynFlags (\s -> s{ extraPkgConfs = p : extraPkgConfs s })
543 noUserPkgConf_   = updDynFlags (\s -> s{ readUserPkgConf = False })
544
545 exposePackage p = 
546   updDynFlags (\s -> s{ packageFlags = ExposePackage p : packageFlags s })
547 hidePackage p = 
548   updDynFlags (\s -> s{ packageFlags = HidePackage p : packageFlags s })
549 ignorePackage p = 
550   updDynFlags (\s -> s{ packageFlags = IgnorePackage p : packageFlags s })
551
552 -- -i on its own deletes the import paths
553 addImportPath "" = updDynFlags (\s -> s{importPaths = []})
554 addImportPath p  = do
555   paths <- splitPathList p
556   updDynFlags (\s -> s{importPaths = importPaths s ++ paths})
557
558 -- we can only switch between HscC, HscAsmm, and HscILX with dynamic flags 
559 -- (-fvia-C, -fasm, -filx respectively).
560 setTarget l = updDynFlags (\dfs -> case hscTarget dfs of
561                                         HscC   -> dfs{ hscTarget = l }
562                                         HscAsm -> dfs{ hscTarget = l }
563                                         HscILX -> dfs{ hscTarget = l }
564                                         _      -> dfs)
565
566 setOptLevel :: Int -> IO ()
567 setOptLevel n 
568    = do dflags <- readIORef v_DynFlags
569         if hscTarget dflags == HscInterpreted && n > 0
570           then putStr "warning: -O conflicts with --interactive; -O ignored.\n"
571           else writeIORef v_DynFlags (updOptLevel n dflags)
572
573 -----------------------------------------------------------------------------
574 -- convert sizes like "3.5M" into integers
575
576 decodeSize :: String -> Integer
577 decodeSize str
578   | c == ""              = truncate n
579   | c == "K" || c == "k" = truncate (n * 1000)
580   | c == "M" || c == "m" = truncate (n * 1000 * 1000)
581   | c == "G" || c == "g" = truncate (n * 1000 * 1000 * 1000)
582   | otherwise            = throwDyn (CmdLineError ("can't decode size: " ++ str))
583   where (m, c) = span pred str
584         n      = read m  :: Double
585         pred c = isDigit c || c == '.'
586
587
588 -----------------------------------------------------------------------------
589 -- RTS Hooks
590
591 #if __GLASGOW_HASKELL__ >= 504
592 foreign import ccall unsafe "setHeapSize"       setHeapSize       :: Int -> IO ()
593 foreign import ccall unsafe "enableTimingStats" enableTimingStats :: IO ()
594 #else
595 foreign import "setHeapSize"       unsafe setHeapSize       :: Int -> IO ()
596 foreign import "enableTimingStats" unsafe enableTimingStats :: IO ()
597 #endif
598
599 -----------------------------------------------------------------------------
600 -- Build the Hsc static command line opts
601
602 buildStaticHscOpts :: IO [String]
603 buildStaticHscOpts = do
604
605   opt_C_ <- getStaticOpts v_Opt_C       -- misc hsc opts from the command line
606
607         -- take into account -fno-* flags by removing the equivalent -f*
608         -- flag from our list.
609   anti_flags <- getStaticOpts v_Anti_opt_C
610   let basic_opts = opt_C_
611       filtered_opts = filter (`notElem` anti_flags) basic_opts
612
613   static <- (do s <- readIORef v_Static; if s then return "-static" 
614                                               else return "")
615
616   return ( static : filtered_opts )
617
618 setMainIs :: String -> IO ()
619 setMainIs arg
620   | not (null main_mod)         -- The arg looked like "Foo.baz"
621   = do { writeIORef v_MainFunIs (Just main_fn) ;
622          writeIORef v_MainModIs (Just main_mod) }
623
624   | isUpper (head main_fn)      -- The arg looked like "Foo"
625   = writeIORef v_MainModIs (Just main_fn)
626   
627   | otherwise                   -- The arg looked like "baz"
628   = writeIORef v_MainFunIs (Just main_fn)
629   where
630     (main_mod, main_fn) = split_longest_prefix arg (== '.')
631   
632
633 -----------------------------------------------------------------------------
634 -- Via-C compilation stuff
635
636 -- flags returned are: ( all C compilations
637 --                     , registerised HC compilations
638 --                     )
639
640 machdepCCOpts dflags
641 #if alpha_TARGET_ARCH
642         = return ( ["-w", "-mieee"
643 #ifdef HAVE_THREADED_RTS_SUPPORT
644                     , "-D_REENTRANT"
645 #endif
646                    ], [] )
647         -- For now, to suppress the gcc warning "call-clobbered
648         -- register used for global register variable", we simply
649         -- disable all warnings altogether using the -w flag. Oh well.
650
651 #elif hppa_TARGET_ARCH
652         -- ___HPUX_SOURCE, not _HPUX_SOURCE, is #defined if -ansi!
653         -- (very nice, but too bad the HP /usr/include files don't agree.)
654         = return ( ["-D_HPUX_SOURCE"], [] )
655
656 #elif m68k_TARGET_ARCH
657       -- -fno-defer-pop : for the .hc files, we want all the pushing/
658       --    popping of args to routines to be explicit; if we let things
659       --    be deferred 'til after an STGJUMP, imminent death is certain!
660       --
661       -- -fomit-frame-pointer : *don't*
662       --     It's better to have a6 completely tied up being a frame pointer
663       --     rather than let GCC pick random things to do with it.
664       --     (If we want to steal a6, then we would try to do things
665       --     as on iX86, where we *do* steal the frame pointer [%ebp].)
666         = return ( [], ["-fno-defer-pop", "-fno-omit-frame-pointer"] )
667
668 #elif i386_TARGET_ARCH
669       -- -fno-defer-pop : basically the same game as for m68k
670       --
671       -- -fomit-frame-pointer : *must* in .hc files; because we're stealing
672       --   the fp (%ebp) for our register maps.
673         = do let n_regs = stolen_x86_regs dflags
674              sta    <- readIORef v_Static
675              return ( [ if sta then "-DDONT_WANT_WIN32_DLL_SUPPORT" else ""
676 --                    , if suffixMatch "mingw32" cTARGETPLATFORM then "-mno-cygwin" else "" 
677                       ],
678                       [ "-fno-defer-pop",
679 #ifdef HAVE_GCC_MNO_OMIT_LFPTR
680                         -- Some gccs are configured with
681                         -- -momit-leaf-frame-pointer on by default, and it
682                         -- apparently takes precedence over 
683                         -- -fomit-frame-pointer, so we disable it first here.
684                         "-mno-omit-leaf-frame-pointer",
685 #endif
686                         "-fomit-frame-pointer",
687                         -- we want -fno-builtin, because when gcc inlines
688                         -- built-in functions like memcpy() it tends to
689                         -- run out of registers, requiring -monly-n-regs
690                         "-fno-builtin",
691                         "-DSTOLEN_X86_REGS="++show n_regs ]
692                     )
693
694 #elif ia64_TARGET_ARCH
695         = return ( [], ["-fomit-frame-pointer", "-G0"] )
696
697 #elif x86_64_TARGET_ARCH
698         = return ( [], ["-fomit-frame-pointer"] )
699
700 #elif mips_TARGET_ARCH
701         = return ( ["-static"], [] )
702
703 #elif sparc_TARGET_ARCH
704         = return ( [], ["-w"] )
705         -- For now, to suppress the gcc warning "call-clobbered
706         -- register used for global register variable", we simply
707         -- disable all warnings altogether using the -w flag. Oh well.
708
709 #elif powerpc_apple_darwin_TARGET
710       -- -no-cpp-precomp:
711       --     Disable Apple's precompiling preprocessor. It's a great thing
712       --     for "normal" programs, but it doesn't support register variable
713       --     declarations.
714       -- -mdynamic-no-pic:
715       --     Turn off PIC code generation to save space and time.
716       -- -fno-common:
717       --     Don't generate "common" symbols - these are unwanted
718       --     in dynamic libraries.
719
720         = if opt_PIC
721             then return ( ["-no-cpp-precomp", "-fno-common"],
722                           ["-fno-common"] )
723             else return ( ["-no-cpp-precomp", "-mdynamic-no-pic"],
724                           ["-mdynamic-no-pic"] )
725
726 #elif powerpc_TARGET_ARCH
727    | opt_PIC
728         = return ( ["-fPIC"], ["-fPIC"] )
729    | otherwise
730         = return ( [], [] )
731 #endif
732
733 -----------------------------------------------------------------------------
734 -- local utils
735
736 -- -----------------------------------------------------------------------------
737 -- Version and usage messages
738
739 showVersion :: IO ()
740 showVersion = do
741   putStrLn (cProjectName ++ ", version " ++ cProjectVersion)
742   exitWith ExitSuccess
743
744 showGhcUsage = do 
745   (ghc_usage_path,ghci_usage_path) <- getUsageMsgPaths
746   mode <- readIORef v_GhcMode
747   let usage_path 
748         | DoInteractive <- mode = ghci_usage_path
749         | otherwise             = ghc_usage_path
750   usage <- readFile usage_path
751   dump usage
752   exitWith ExitSuccess
753   where
754      dump ""          = return ()
755      dump ('$':'$':s) = hPutStr stderr progName >> dump s
756      dump (c:s)       = hPutChar stderr c >> dump s