Add -XImpredicativeTypes, and tighten up type-validity checking (cf Trac 2019)
[ghc-hetmet.git] / compiler / main / DynFlags.hs
1
2 {-# OPTIONS -fno-warn-missing-fields #-}
3 {-# OPTIONS -w #-}
4 -- The above warning supression flag is a temporary kludge.
5 -- While working on this module you are encouraged to remove it and fix
6 -- any warnings in the module. See
7 --     http://hackage.haskell.org/trac/ghc/wiki/Commentary/CodingStyle#Warnings
8 -- for details
9
10 -----------------------------------------------------------------------------
11 --
12 -- Dynamic flags
13 --
14 -- Most flags are dynamic flags, which means they can change from
15 -- compilation to compilation using OPTIONS_GHC pragmas, and in a
16 -- multi-session GHC each session can be using different dynamic
17 -- flags.  Dynamic flags can also be set at the prompt in GHCi.
18 --
19 -- (c) The University of Glasgow 2005
20 --
21 -----------------------------------------------------------------------------
22
23 module DynFlags (
24         -- Dynamic flags
25         DynFlag(..),
26         DynFlags(..),
27         HscTarget(..), isObjectTarget, defaultObjectTarget,
28         GhcMode(..), isOneShot,
29         GhcLink(..), isNoLink,
30         PackageFlag(..),
31         Option(..),
32         fFlags, xFlags,
33
34         -- Configuration of the core-to-core and stg-to-stg phases
35         CoreToDo(..),
36         StgToDo(..),
37         SimplifierSwitch(..), 
38         SimplifierMode(..), FloatOutSwitches(..),
39         getCoreToDo, getStgToDo,
40         
41         -- Manipulating DynFlags
42         defaultDynFlags,                -- DynFlags
43         initDynFlags,                   -- DynFlags -> IO DynFlags
44
45         dopt,                           -- DynFlag -> DynFlags -> Bool
46         dopt_set, dopt_unset,           -- DynFlags -> DynFlag -> DynFlags
47         getOpts,                        -- (DynFlags -> [a]) -> IO [a]
48         getVerbFlag,
49         updOptLevel,
50         setTmpDir,
51         setPackageName,
52         
53         -- parsing DynFlags
54         parseDynamicFlags,
55         allFlags,
56
57         -- misc stuff
58         machdepCCOpts, picCCOpts,
59     supportedLanguages,
60     compilerInfo,
61   ) where
62
63 #include "HsVersions.h"
64
65 import Module
66 import PackageConfig
67 import PrelNames        ( mAIN )
68 #ifdef i386_TARGET_ARCH
69 import StaticFlags      ( opt_Static )
70 #endif
71 import StaticFlags      ( opt_PIC, WayName(..), v_Ways, v_Build_tag,
72                           v_RTS_Build_tag )
73 import {-# SOURCE #-} Packages (PackageState)
74 import DriverPhases     ( Phase(..), phaseInputExt )
75 import Config
76 import CmdLineParser
77 import Constants        ( mAX_CONTEXT_REDUCTION_DEPTH )
78 import Panic            ( panic, GhcException(..) )
79 import UniqFM           ( UniqFM )
80 import Util
81 import Maybes           ( orElse, fromJust )
82 import SrcLoc           ( SrcSpan )
83 import Outputable
84 import {-# SOURCE #-} ErrUtils ( Severity(..), Message, mkLocMessage )
85
86 import Data.IORef       ( readIORef )
87 import Control.Exception ( throwDyn )
88 import Control.Monad    ( when )
89 #ifdef mingw32_TARGET_OS
90 import Data.List        ( isPrefixOf )
91 #else
92 import Util             ( split )
93 #endif
94
95 import Data.Char
96 import System.IO        ( hPutStrLn, stderr )
97
98 -- -----------------------------------------------------------------------------
99 -- DynFlags
100
101 data DynFlag
102
103    -- debugging flags
104    = Opt_D_dump_cmm
105    | Opt_D_dump_cmmz
106    | Opt_D_dump_cmmz_pretty
107    | Opt_D_dump_cps_cmm
108    | Opt_D_dump_cvt_cmm
109    | Opt_D_dump_asm
110    | Opt_D_dump_asm_native
111    | Opt_D_dump_asm_liveness
112    | Opt_D_dump_asm_coalesce
113    | Opt_D_dump_asm_regalloc
114    | Opt_D_dump_asm_regalloc_stages
115    | Opt_D_dump_asm_conflicts
116    | Opt_D_dump_asm_stats
117    | Opt_D_dump_cpranal
118    | Opt_D_dump_deriv
119    | Opt_D_dump_ds
120    | Opt_D_dump_flatC
121    | Opt_D_dump_foreign
122    | Opt_D_dump_inlinings
123    | Opt_D_dump_rule_firings
124    | Opt_D_dump_occur_anal
125    | Opt_D_dump_parsed
126    | Opt_D_dump_rn
127    | Opt_D_dump_simpl
128    | Opt_D_dump_simpl_iterations
129    | Opt_D_dump_simpl_phases
130    | Opt_D_dump_spec
131    | Opt_D_dump_prep
132    | Opt_D_dump_stg
133    | Opt_D_dump_stranal
134    | Opt_D_dump_tc
135    | Opt_D_dump_types
136    | Opt_D_dump_rules
137    | Opt_D_dump_cse
138    | Opt_D_dump_worker_wrapper
139    | Opt_D_dump_rn_trace
140    | Opt_D_dump_rn_stats
141    | Opt_D_dump_opt_cmm
142    | Opt_D_dump_simpl_stats
143    | Opt_D_dump_tc_trace
144    | Opt_D_dump_if_trace
145    | Opt_D_dump_splices
146    | Opt_D_dump_BCOs
147    | Opt_D_dump_vect
148    | Opt_D_dump_hpc
149    | Opt_D_source_stats
150    | Opt_D_verbose_core2core
151    | Opt_D_verbose_stg2stg
152    | Opt_D_dump_hi
153    | Opt_D_dump_hi_diffs
154    | Opt_D_dump_minimal_imports
155    | Opt_D_dump_mod_cycles
156    | Opt_D_dump_view_pattern_commoning
157    | Opt_D_faststring_stats
158    | Opt_DumpToFile                     -- ^ Append dump output to files instead of stdout.
159    | Opt_DoCoreLinting
160    | Opt_DoStgLinting
161    | Opt_DoCmmLinting
162    | Opt_DoAsmLinting
163
164    | Opt_WarnIsError                    -- -Werror; makes warnings fatal
165    | Opt_WarnDuplicateExports
166    | Opt_WarnHiShadows
167    | Opt_WarnImplicitPrelude
168    | Opt_WarnIncompletePatterns
169    | Opt_WarnIncompletePatternsRecUpd
170    | Opt_WarnMissingFields
171    | Opt_WarnMissingMethods
172    | Opt_WarnMissingSigs
173    | Opt_WarnNameShadowing
174    | Opt_WarnOverlappingPatterns
175    | Opt_WarnSimplePatterns
176    | Opt_WarnTypeDefaults
177    | Opt_WarnMonomorphism
178    | Opt_WarnUnusedBinds
179    | Opt_WarnUnusedImports
180    | Opt_WarnUnusedMatches
181    | Opt_WarnDeprecations
182    | Opt_WarnDodgyImports
183    | Opt_WarnOrphans
184    | Opt_WarnTabs
185
186    -- language opts
187    | Opt_OverlappingInstances
188    | Opt_UndecidableInstances
189    | Opt_IncoherentInstances
190    | Opt_MonomorphismRestriction
191    | Opt_MonoPatBinds
192    | Opt_ExtendedDefaultRules           -- Use GHC's extended rules for defaulting
193    | Opt_ForeignFunctionInterface
194    | Opt_UnliftedFFITypes
195    | Opt_PArr                           -- Syntactic support for parallel arrays
196    | Opt_Arrows                         -- Arrow-notation syntax
197    | Opt_TemplateHaskell
198    | Opt_ImplicitParams
199    | Opt_Generics
200    | Opt_ImplicitPrelude 
201    | Opt_ScopedTypeVariables
202    | Opt_UnboxedTuples
203    | Opt_BangPatterns
204    | Opt_TypeFamilies
205    | Opt_OverloadedStrings
206    | Opt_DisambiguateRecordFields
207    | Opt_RecordWildCards
208    | Opt_RecordPuns
209    | Opt_ViewPatterns
210    | Opt_GADTs
211    | Opt_RelaxedPolyRec
212    | Opt_StandaloneDeriving
213    | Opt_DeriveDataTypeable
214    | Opt_TypeSynonymInstances
215    | Opt_FlexibleContexts
216    | Opt_FlexibleInstances
217    | Opt_ConstrainedClassMethods
218    | Opt_MultiParamTypeClasses
219    | Opt_FunctionalDependencies
220    | Opt_UnicodeSyntax
221    | Opt_PolymorphicComponents
222    | Opt_ExistentialQuantification
223    | Opt_MagicHash
224    | Opt_EmptyDataDecls
225    | Opt_KindSignatures
226    | Opt_PatternSignatures
227    | Opt_ParallelListComp
228    | Opt_TransformListComp
229    | Opt_GeneralizedNewtypeDeriving
230    | Opt_RecursiveDo
231    | Opt_PatternGuards
232    | Opt_LiberalTypeSynonyms
233    | Opt_Rank2Types
234    | Opt_RankNTypes
235    | Opt_ImpredicativeTypes
236    | Opt_TypeOperators
237
238    | Opt_PrintExplicitForalls
239
240    -- optimisation opts
241    | Opt_Strictness
242    | Opt_FullLaziness
243    | Opt_CSE
244    | Opt_LiberateCase
245    | Opt_SpecConstr
246    | Opt_IgnoreInterfacePragmas
247    | Opt_OmitInterfacePragmas
248    | Opt_DoLambdaEtaExpansion
249    | Opt_IgnoreAsserts
250    | Opt_DoEtaReduction
251    | Opt_CaseMerge
252    | Opt_UnboxStrictFields
253    | Opt_DictsCheap
254    | Opt_RewriteRules
255    | Opt_Vectorise
256    | Opt_RegsGraph                      -- do graph coloring register allocation
257    | Opt_RegsIterative                  -- do iterative coalescing graph coloring register allocation
258
259    -- misc opts
260    | Opt_Cpp
261    | Opt_Pp
262    | Opt_ForceRecomp
263    | Opt_DryRun
264    | Opt_DoAsmMangling
265    | Opt_ExcessPrecision
266    | Opt_ReadUserPackageConf
267    | Opt_NoHsMain
268    | Opt_SplitObjs
269    | Opt_StgStats
270    | Opt_HideAllPackages
271    | Opt_PrintBindResult
272    | Opt_Haddock
273    | Opt_HaddockOptions
274    | Opt_Hpc_No_Auto
275    | Opt_BreakOnException
276    | Opt_BreakOnError
277    | Opt_PrintEvldWithShow
278    | Opt_PrintBindContents
279    | Opt_GenManifest
280    | Opt_EmbedManifest
281    | Opt_RunCPSZ
282    | Opt_ConvertToZipCfgAndBack
283
284    -- keeping stuff
285    | Opt_KeepHiDiffs
286    | Opt_KeepHcFiles
287    | Opt_KeepSFiles
288    | Opt_KeepRawSFiles
289    | Opt_KeepTmpFiles
290
291    deriving (Eq, Show)
292  
293 data DynFlags = DynFlags {
294   ghcMode               :: GhcMode,
295   ghcLink               :: GhcLink,
296   coreToDo              :: Maybe [CoreToDo], -- reserved for -Ofile
297   stgToDo               :: Maybe [StgToDo],  -- similarly
298   hscTarget             :: HscTarget,
299   hscOutName            :: String,      -- name of the output file
300   extCoreName           :: String,      -- name of the .core output file
301   verbosity             :: Int,         -- verbosity level
302   optLevel              :: Int,         -- optimisation level
303   maxSimplIterations    :: Int,         -- max simplifier iterations
304   ruleCheck             :: Maybe String,
305
306   specConstrThreshold   :: Maybe Int,   -- Threshold for SpecConstr
307   liberateCaseThreshold :: Maybe Int,   -- Threshold for LiberateCase 
308
309   stolen_x86_regs       :: Int,         
310   cmdlineHcIncludes     :: [String],    -- -#includes
311   importPaths           :: [FilePath],
312   mainModIs             :: Module,
313   mainFunIs             :: Maybe String,
314   ctxtStkDepth          :: Int,         -- Typechecker context stack depth
315
316   thisPackage           :: PackageId,
317
318   -- ways
319   wayNames              :: [WayName],   -- way flags from the cmd line
320   buildTag              :: String,      -- the global "way" (eg. "p" for prof)
321   rtsBuildTag           :: String,      -- the RTS "way"
322   
323   -- paths etc.
324   objectDir             :: Maybe String,
325   hiDir                 :: Maybe String,
326   stubDir               :: Maybe String,
327
328   objectSuf             :: String,
329   hcSuf                 :: String,
330   hiSuf                 :: String,
331
332   outputFile            :: Maybe String,
333   outputHi              :: Maybe String,
334
335   -- | This is set by DriverPipeline.runPipeline based on where
336   --    its output is going.
337   dumpPrefix            :: Maybe FilePath,
338
339   -- | Override the dumpPrefix set by runPipeline.
340   --    Set by -ddump-file-prefix
341   dumpPrefixForce       :: Maybe FilePath,
342
343   includePaths          :: [String],
344   libraryPaths          :: [String],
345   frameworkPaths        :: [String],    -- used on darwin only
346   cmdlineFrameworks     :: [String],    -- ditto
347   tmpDir                :: String,      -- no trailing '/'
348   
349   ghcUsagePath          :: FilePath,    -- Filled in by SysTools
350   ghciUsagePath         :: FilePath,    -- ditto
351
352   hpcDir                :: String,      -- ^ path to store the .mix files
353
354   -- options for particular phases
355   opt_L                 :: [String],
356   opt_P                 :: [String],
357   opt_F                 :: [String],
358   opt_c                 :: [String],
359   opt_m                 :: [String],
360   opt_a                 :: [String],
361   opt_l                 :: [String],
362   opt_dep               :: [String],
363   opt_windres           :: [String],
364
365   -- commands for particular phases
366   pgm_L                 :: String,
367   pgm_P                 :: (String,[Option]),
368   pgm_F                 :: String,
369   pgm_c                 :: (String,[Option]),
370   pgm_m                 :: (String,[Option]),
371   pgm_s                 :: (String,[Option]),
372   pgm_a                 :: (String,[Option]),
373   pgm_l                 :: (String,[Option]),
374   pgm_dll               :: (String,[Option]),
375   pgm_T                 :: String,
376   pgm_sysman            :: String,
377   pgm_windres           :: String,
378
379   --  Package flags
380   extraPkgConfs         :: [FilePath],
381   topDir                :: FilePath,    -- filled in by SysTools
382   systemPackageConfig   :: FilePath,    -- ditto
383         -- The -package-conf flags given on the command line, in the order
384         -- they appeared.
385
386   packageFlags          :: [PackageFlag],
387         -- The -package and -hide-package flags from the command-line
388
389   -- Package state
390   -- NB. do not modify this field, it is calculated by 
391   -- Packages.initPackages and Packages.updatePackages.
392   pkgDatabase           :: Maybe (UniqFM PackageConfig),
393   pkgState              :: PackageState,
394
395   -- hsc dynamic flags
396   flags                 :: [DynFlag],
397   
398   -- message output
399   log_action            :: Severity -> SrcSpan -> PprStyle -> Message -> IO (),
400
401   haddockOptions :: Maybe String
402  }
403
404 data HscTarget
405   = HscC
406   | HscAsm
407   | HscJava
408   | HscInterpreted
409   | HscNothing
410   deriving (Eq, Show)
411
412 -- | will this target result in an object file on the disk?
413 isObjectTarget :: HscTarget -> Bool
414 isObjectTarget HscC     = True
415 isObjectTarget HscAsm   = True
416 isObjectTarget _        = False
417
418 -- | The 'GhcMode' tells us whether we're doing multi-module
419 -- compilation (controlled via the "GHC" API) or one-shot
420 -- (single-module) compilation.  This makes a difference primarily to
421 -- the "Finder": in one-shot mode we look for interface files for
422 -- imported modules, but in multi-module mode we look for source files
423 -- in order to check whether they need to be recompiled.
424 data GhcMode
425   = CompManager         -- ^ --make, GHCi, etc.
426   | OneShot             -- ^ ghc -c Foo.hs
427   | MkDepend            -- ^ ghc -M, see Finder for why we need this
428   deriving Eq
429
430 isOneShot :: GhcMode -> Bool
431 isOneShot OneShot = True
432 isOneShot _other  = False
433
434 -- | What kind of linking to do.
435 data GhcLink    -- What to do in the link step, if there is one
436   = NoLink              -- Don't link at all
437   | LinkBinary          -- Link object code into a binary
438   | LinkInMemory        -- Use the in-memory dynamic linker
439   | LinkDynLib          -- Link objects into a dynamic lib (DLL on Windows, DSO on ELF platforms)
440   deriving (Eq, Show)
441
442 isNoLink :: GhcLink -> Bool
443 isNoLink NoLink = True
444 isNoLink other  = False
445
446 data PackageFlag
447   = ExposePackage  String
448   | HidePackage    String
449   | IgnorePackage  String
450   deriving Eq
451
452 defaultHscTarget = defaultObjectTarget
453
454 -- | the 'HscTarget' value corresponding to the default way to create
455 -- object files on the current platform.
456 defaultObjectTarget
457   | cGhcWithNativeCodeGen == "YES"      =  HscAsm
458   | otherwise                           =  HscC
459
460 initDynFlags dflags = do
461  -- someday these will be dynamic flags
462  ways <- readIORef v_Ways
463  build_tag <- readIORef v_Build_tag
464  rts_build_tag <- readIORef v_RTS_Build_tag
465  return dflags{
466         wayNames        = ways,
467         buildTag        = build_tag,
468         rtsBuildTag     = rts_build_tag
469         }
470
471 defaultDynFlags =
472      DynFlags {
473         ghcMode                 = CompManager,
474         ghcLink                 = LinkBinary,
475         coreToDo                = Nothing,
476         stgToDo                 = Nothing, 
477         hscTarget               = defaultHscTarget, 
478         hscOutName              = "", 
479         extCoreName             = "",
480         verbosity               = 0, 
481         optLevel                = 0,
482         maxSimplIterations      = 4,
483         ruleCheck               = Nothing,
484         specConstrThreshold     = Just 200,
485         liberateCaseThreshold   = Just 200,
486         stolen_x86_regs         = 4,
487         cmdlineHcIncludes       = [],
488         importPaths             = ["."],
489         mainModIs               = mAIN,
490         mainFunIs               = Nothing,
491         ctxtStkDepth            = mAX_CONTEXT_REDUCTION_DEPTH,
492
493         thisPackage             = mainPackageId,
494
495         objectDir               = Nothing,
496         hiDir                   = Nothing,
497         stubDir                 = Nothing,
498
499         objectSuf               = phaseInputExt StopLn,
500         hcSuf                   = phaseInputExt HCc,
501         hiSuf                   = "hi",
502
503         outputFile              = Nothing,
504         outputHi                = Nothing,
505         dumpPrefix              = Nothing,
506         dumpPrefixForce         = Nothing,
507         includePaths            = [],
508         libraryPaths            = [],
509         frameworkPaths          = [],
510         cmdlineFrameworks       = [],
511         tmpDir                  = cDEFAULT_TMPDIR,
512         
513         hpcDir                  = ".hpc",
514
515         opt_L                   = [],
516         opt_P                   = (if opt_PIC
517                                    then ["-D__PIC__"]
518                                    else []),
519         opt_F                   = [],
520         opt_c                   = [],
521         opt_a                   = [],
522         opt_m                   = [],
523         opt_l                   = [],
524         opt_dep                 = [],
525         opt_windres             = [],
526         
527         extraPkgConfs           = [],
528         packageFlags            = [],
529         pkgDatabase             = Nothing,
530         pkgState                = panic "no package state yet: call GHC.setSessionDynFlags",
531   haddockOptions = Nothing,
532         flags = [
533             Opt_ReadUserPackageConf,
534
535             Opt_MonoPatBinds,   -- Experimentally, I'm making this non-standard
536                                 -- behaviour the default, to see if anyone notices
537                                 -- SLPJ July 06
538
539             Opt_ImplicitPrelude,
540             Opt_MonomorphismRestriction,
541
542             Opt_DoAsmMangling,
543
544             Opt_GenManifest,
545             Opt_EmbedManifest,
546             Opt_PrintBindContents
547             ]
548             ++ [f | (ns,f) <- optLevelFlags, 0 `elem` ns]
549                     -- The default -O0 options
550             ++ standardWarnings,
551
552         log_action = \severity srcSpan style msg -> 
553                         case severity of
554                           SevInfo  -> hPutStrLn stderr (show (msg style))
555                           SevFatal -> hPutStrLn stderr (show (msg style))
556                           _        -> hPutStrLn stderr ('\n':show ((mkLocMessage srcSpan msg) style))
557       }
558
559 {- 
560     Verbosity levels:
561         
562     0   |   print errors & warnings only
563     1   |   minimal verbosity: print "compiling M ... done." for each module.
564     2   |   equivalent to -dshow-passes
565     3   |   equivalent to existing "ghc -v"
566     4   |   "ghc -v -ddump-most"
567     5   |   "ghc -v -ddump-all"
568 -}
569
570 dopt :: DynFlag -> DynFlags -> Bool
571 dopt f dflags  = f `elem` (flags dflags)
572
573 dopt_set :: DynFlags -> DynFlag -> DynFlags
574 dopt_set dfs f = dfs{ flags = f : flags dfs }
575
576 dopt_unset :: DynFlags -> DynFlag -> DynFlags
577 dopt_unset dfs f = dfs{ flags = filter (/= f) (flags dfs) }
578
579 getOpts :: DynFlags -> (DynFlags -> [a]) -> [a]
580 getOpts dflags opts = reverse (opts dflags)
581         -- We add to the options from the front, so we need to reverse the list
582
583 getVerbFlag :: DynFlags -> String
584 getVerbFlag dflags 
585   | verbosity dflags >= 3  = "-v" 
586   | otherwise =  ""
587
588 setObjectDir  f d = d{ objectDir  = Just f}
589 setHiDir      f d = d{ hiDir      = Just f}
590 setStubDir    f d = d{ stubDir    = Just f, includePaths = f : includePaths d }
591   -- -stubdir D adds an implicit -I D, so that gcc can find the _stub.h file
592   -- #included from the .hc file when compiling with -fvia-C.
593
594 setObjectSuf  f d = d{ objectSuf  = f}
595 setHiSuf      f d = d{ hiSuf      = f}
596 setHcSuf      f d = d{ hcSuf      = f}
597
598 setOutputFile f d = d{ outputFile = f}
599 setOutputHi   f d = d{ outputHi   = f}
600
601 setDumpPrefixForce f d = d { dumpPrefixForce = f}
602
603 -- XXX HACK: Prelude> words "'does not' work" ===> ["'does","not'","work"]
604 -- Config.hs should really use Option.
605 setPgmP   f d = let (pgm:args) = words f in d{ pgm_P   = (pgm, map Option args)}
606
607 setPgmL   f d = d{ pgm_L   = f}
608 setPgmF   f d = d{ pgm_F   = f}
609 setPgmc   f d = d{ pgm_c   = (f,[])}
610 setPgmm   f d = d{ pgm_m   = (f,[])}
611 setPgms   f d = d{ pgm_s   = (f,[])}
612 setPgma   f d = d{ pgm_a   = (f,[])}
613 setPgml   f d = d{ pgm_l   = (f,[])}
614 setPgmdll f d = d{ pgm_dll = (f,[])}
615 setPgmwindres f d = d{ pgm_windres = f}
616
617 addOptL   f d = d{ opt_L   = f : opt_L d}
618 addOptP   f d = d{ opt_P   = f : opt_P d}
619 addOptF   f d = d{ opt_F   = f : opt_F d}
620 addOptc   f d = d{ opt_c   = f : opt_c d}
621 addOptm   f d = d{ opt_m   = f : opt_m d}
622 addOpta   f d = d{ opt_a   = f : opt_a d}
623 addOptl   f d = d{ opt_l   = f : opt_l d}
624 addOptdep f d = d{ opt_dep = f : opt_dep d}
625 addOptwindres f d = d{ opt_windres = f : opt_windres d}
626
627 addCmdlineFramework f d = d{ cmdlineFrameworks = f : cmdlineFrameworks d}
628
629 addHaddockOpts f d = d{ haddockOptions = Just f}
630
631 -- -----------------------------------------------------------------------------
632 -- Command-line options
633
634 -- When invoking external tools as part of the compilation pipeline, we
635 -- pass these a sequence of options on the command-line. Rather than
636 -- just using a list of Strings, we use a type that allows us to distinguish
637 -- between filepaths and 'other stuff'. [The reason being, of course, that
638 -- this type gives us a handle on transforming filenames, and filenames only,
639 -- to whatever format they're expected to be on a particular platform.]
640
641 data Option
642  = FileOption -- an entry that _contains_ filename(s) / filepaths.
643               String  -- a non-filepath prefix that shouldn't be 
644                       -- transformed (e.g., "/out=")
645               String  -- the filepath/filename portion
646  | Option     String
647  
648 -----------------------------------------------------------------------------
649 -- Setting the optimisation level
650
651 updOptLevel :: Int -> DynFlags -> DynFlags
652 -- Set dynflags appropriate to the optimisation level
653 updOptLevel n dfs
654   = dfs2{ optLevel = final_n }
655   where
656    final_n = max 0 (min 2 n)    -- Clamp to 0 <= n <= 2
657    dfs1 = foldr (flip dopt_unset) dfs  remove_dopts
658    dfs2 = foldr (flip dopt_set)   dfs1 extra_dopts
659
660    extra_dopts  = [ f | (ns,f) <- optLevelFlags, final_n `elem` ns ]
661    remove_dopts = [ f | (ns,f) <- optLevelFlags, final_n `notElem` ns ]
662         
663 optLevelFlags :: [([Int], DynFlag)]
664 optLevelFlags
665   = [ ([0],     Opt_IgnoreInterfacePragmas)
666     , ([0],     Opt_OmitInterfacePragmas)
667
668     , ([1,2],   Opt_IgnoreAsserts)
669     , ([1,2],   Opt_RewriteRules)       -- Off for -O0; see Note [Scoping for Builtin rules]
670                                         --              in PrelRules
671     , ([1,2],   Opt_DoEtaReduction)
672     , ([1,2],   Opt_CaseMerge)
673     , ([1,2],   Opt_Strictness)
674     , ([1,2],   Opt_CSE)
675     , ([1,2],   Opt_FullLaziness)
676
677     , ([2],     Opt_LiberateCase)
678     , ([2],     Opt_SpecConstr)
679
680     , ([0,1,2], Opt_DoLambdaEtaExpansion)
681                 -- This one is important for a tiresome reason:
682                 -- we want to make sure that the bindings for data 
683                 -- constructors are eta-expanded.  This is probably
684                 -- a good thing anyway, but it seems fragile.
685     ]
686
687 -- -----------------------------------------------------------------------------
688 -- Standard sets of warning options
689
690 standardWarnings
691     = [ Opt_WarnDeprecations,
692         Opt_WarnOverlappingPatterns,
693         Opt_WarnMissingFields,
694         Opt_WarnMissingMethods,
695         Opt_WarnDuplicateExports
696       ]
697
698 minusWOpts
699     = standardWarnings ++ 
700       [ Opt_WarnUnusedBinds,
701         Opt_WarnUnusedMatches,
702         Opt_WarnUnusedImports,
703         Opt_WarnIncompletePatterns,
704         Opt_WarnDodgyImports
705       ]
706
707 minusWallOpts
708     = minusWOpts ++
709       [ Opt_WarnTypeDefaults,
710         Opt_WarnNameShadowing,
711         Opt_WarnMissingSigs,
712         Opt_WarnHiShadows,
713         Opt_WarnOrphans
714       ]
715
716 -- minuswRemovesOpts should be every warning option
717 minuswRemovesOpts
718     = minusWallOpts ++
719       [Opt_WarnImplicitPrelude,
720        Opt_WarnIncompletePatternsRecUpd,
721        Opt_WarnSimplePatterns,
722        Opt_WarnMonomorphism,
723        Opt_WarnTabs
724       ]
725
726 -- -----------------------------------------------------------------------------
727 -- CoreToDo:  abstraction of core-to-core passes to run.
728
729 data CoreToDo           -- These are diff core-to-core passes,
730                         -- which may be invoked in any order,
731                         -- as many times as you like.
732
733   = CoreDoSimplify      -- The core-to-core simplifier.
734         SimplifierMode
735         [SimplifierSwitch]
736                         -- Each run of the simplifier can take a different
737                         -- set of simplifier-specific flags.
738   | CoreDoFloatInwards
739   | CoreDoFloatOutwards FloatOutSwitches
740   | CoreLiberateCase
741   | CoreDoPrintCore
742   | CoreDoStaticArgs
743   | CoreDoStrictness
744   | CoreDoWorkerWrapper
745   | CoreDoSpecialising
746   | CoreDoSpecConstr
747   | CoreDoOldStrictness
748   | CoreDoGlomBinds
749   | CoreCSE
750   | CoreDoRuleCheck Int{-CompilerPhase-} String -- Check for non-application of rules 
751                                                 -- matching this string
752   | CoreDoVectorisation
753   | CoreDoNothing                -- Useful when building up 
754   | CoreDoPasses [CoreToDo]      -- lists of these things
755
756 data SimplifierMode             -- See comments in SimplMonad
757   = SimplGently
758   | SimplPhase Int
759
760 data SimplifierSwitch
761   = MaxSimplifierIterations Int
762   | NoCaseOfCase
763
764 data FloatOutSwitches
765   = FloatOutSw  Bool    -- True <=> float lambdas to top level
766                 Bool    -- True <=> float constants to top level,
767                         --          even if they do not escape a lambda
768
769
770 -- The core-to-core pass ordering is derived from the DynFlags:
771 runWhen :: Bool -> CoreToDo -> CoreToDo
772 runWhen True  do_this = do_this
773 runWhen False do_this = CoreDoNothing
774
775 getCoreToDo :: DynFlags -> [CoreToDo]
776 getCoreToDo dflags
777   | Just todo <- coreToDo dflags = todo -- set explicitly by user
778   | otherwise = core_todo
779   where
780     opt_level     = optLevel dflags
781     max_iter      = maxSimplIterations dflags
782     strictness    = dopt Opt_Strictness dflags
783     full_laziness = dopt Opt_FullLaziness dflags
784     cse           = dopt Opt_CSE dflags
785     spec_constr   = dopt Opt_SpecConstr dflags
786     liberate_case = dopt Opt_LiberateCase dflags
787     rule_check    = ruleCheck dflags
788     vectorisation = dopt Opt_Vectorise dflags
789
790     core_todo = 
791      if opt_level == 0 then
792       [
793         CoreDoSimplify (SimplPhase 0) [
794             MaxSimplifierIterations max_iter
795         ]
796       ]
797      else {- opt_level >= 1 -} [ 
798
799         -- initial simplify: mk specialiser happy: minimum effort please
800         CoreDoSimplify SimplGently [
801                         --      Simplify "gently"
802                         -- Don't inline anything till full laziness has bitten
803                         -- In particular, inlining wrappers inhibits floating
804                         -- e.g. ...(case f x of ...)...
805                         --  ==> ...(case (case x of I# x# -> fw x#) of ...)...
806                         --  ==> ...(case x of I# x# -> case fw x# of ...)...
807                         -- and now the redex (f x) isn't floatable any more
808                         -- Similarly, don't apply any rules until after full 
809                         -- laziness.  Notably, list fusion can prevent floating.
810
811             NoCaseOfCase,       -- Don't do case-of-case transformations.
812                                 -- This makes full laziness work better
813             MaxSimplifierIterations max_iter
814         ],
815
816
817         -- We run vectorisation here for now, but we might also try to run
818         -- it later
819         runWhen vectorisation (CoreDoPasses [
820                   CoreDoVectorisation,
821                   CoreDoSimplify SimplGently
822                                   [NoCaseOfCase,
823                                    MaxSimplifierIterations max_iter]]),
824
825         -- Specialisation is best done before full laziness
826         -- so that overloaded functions have all their dictionary lambdas manifest
827         CoreDoSpecialising,
828
829         runWhen full_laziness (CoreDoFloatOutwards (FloatOutSw False False)),
830
831         CoreDoFloatInwards,
832
833         CoreDoSimplify (SimplPhase 2) [
834                 -- Want to run with inline phase 2 after the specialiser to give
835                 -- maximum chance for fusion to work before we inline build/augment
836                 -- in phase 1.  This made a difference in 'ansi' where an 
837                 -- overloaded function wasn't inlined till too late.
838            MaxSimplifierIterations max_iter
839         ],
840         case rule_check of { Just pat -> CoreDoRuleCheck 2 pat; Nothing -> CoreDoNothing },
841
842         CoreDoSimplify (SimplPhase 1) [
843                 -- Need inline-phase2 here so that build/augment get 
844                 -- inlined.  I found that spectral/hartel/genfft lost some useful
845                 -- strictness in the function sumcode' if augment is not inlined
846                 -- before strictness analysis runs
847            MaxSimplifierIterations max_iter
848         ],
849         case rule_check of { Just pat -> CoreDoRuleCheck 1 pat; Nothing -> CoreDoNothing },
850
851         CoreDoSimplify (SimplPhase 0) [
852                 -- Phase 0: allow all Ids to be inlined now
853                 -- This gets foldr inlined before strictness analysis
854
855            MaxSimplifierIterations (max max_iter 3)
856                 -- At least 3 iterations because otherwise we land up with
857                 -- huge dead expressions because of an infelicity in the 
858                 -- simpifier.   
859                 --      let k = BIG in foldr k z xs
860                 -- ==>  let k = BIG in letrec go = \xs -> ...(k x).... in go xs
861                 -- ==>  let k = BIG in letrec go = \xs -> ...(BIG x).... in go xs
862                 -- Don't stop now!
863
864         ],
865         case rule_check of { Just pat -> CoreDoRuleCheck 0 pat; Nothing -> CoreDoNothing },
866
867 #ifdef OLD_STRICTNESS
868         CoreDoOldStrictness,
869 #endif
870         runWhen strictness (CoreDoPasses [
871                 CoreDoStrictness,
872                 CoreDoWorkerWrapper,
873                 CoreDoGlomBinds,
874                 CoreDoSimplify (SimplPhase 0) [
875                    MaxSimplifierIterations max_iter
876                 ]]),
877
878         runWhen full_laziness 
879           (CoreDoFloatOutwards (FloatOutSw False    -- Not lambdas
880                                            True)),  -- Float constants
881                 -- nofib/spectral/hartel/wang doubles in speed if you
882                 -- do full laziness late in the day.  It only happens
883                 -- after fusion and other stuff, so the early pass doesn't
884                 -- catch it.  For the record, the redex is 
885                 --        f_el22 (f_el21 r_midblock)
886
887
888         runWhen cse CoreCSE,
889                 -- We want CSE to follow the final full-laziness pass, because it may
890                 -- succeed in commoning up things floated out by full laziness.
891                 -- CSE used to rely on the no-shadowing invariant, but it doesn't any more
892
893         CoreDoFloatInwards,
894
895         case rule_check of { Just pat -> CoreDoRuleCheck 0 pat; Nothing -> CoreDoNothing },
896
897                 -- Case-liberation for -O2.  This should be after
898                 -- strictness analysis and the simplification which follows it.
899         runWhen liberate_case (CoreDoPasses [
900             CoreLiberateCase,
901             CoreDoSimplify (SimplPhase 0) [
902                   MaxSimplifierIterations max_iter
903             ] ]),       -- Run the simplifier after LiberateCase to vastly 
904                         -- reduce the possiblility of shadowing
905                         -- Reason: see Note [Shadowing] in SpecConstr.lhs
906
907         runWhen spec_constr CoreDoSpecConstr,
908
909         case rule_check of { Just pat -> CoreDoRuleCheck 0 pat; Nothing -> CoreDoNothing },
910
911         -- Final clean-up simplification:
912         CoreDoSimplify (SimplPhase 0) [
913           MaxSimplifierIterations max_iter
914         ],
915
916         case rule_check of { Just pat -> CoreDoRuleCheck 0 pat; Nothing -> CoreDoNothing }
917
918      ]
919
920 -- -----------------------------------------------------------------------------
921 -- StgToDo:  abstraction of stg-to-stg passes to run.
922
923 data StgToDo
924   = StgDoMassageForProfiling  -- should be (next to) last
925   -- There's also setStgVarInfo, but its absolute "lastness"
926   -- is so critical that it is hardwired in (no flag).
927   | D_stg_stats
928
929 getStgToDo :: DynFlags -> [StgToDo]
930 getStgToDo dflags
931   | Just todo <- stgToDo dflags = todo -- set explicitly by user
932   | otherwise = todo2
933   where
934         stg_stats = dopt Opt_StgStats dflags
935
936         todo1 = if stg_stats then [D_stg_stats] else []
937
938         todo2 | WayProf `elem` wayNames dflags
939               = StgDoMassageForProfiling : todo1
940               | otherwise
941               = todo1
942
943 -- -----------------------------------------------------------------------------
944 -- DynFlags parser
945
946 allFlags :: [String]
947 allFlags = map ('-':) $
948            [ name | (name, optkind) <- dynamic_flags, ok optkind ] ++
949            map ("fno-"++) flags ++
950            map ("f"++) flags ++
951            map ("X"++) xs ++
952            map ("XNo"++) xs
953     where ok (PrefixPred _ _) = False
954           ok _ = True
955           flags = map fst fFlags
956           xs = map fst xFlags
957
958 dynamic_flags :: [(String, OptKind DynP)]
959 dynamic_flags = [
960      ( "n"              , NoArg  (setDynFlag Opt_DryRun) )
961   ,  ( "cpp"            , NoArg  (setDynFlag Opt_Cpp))
962   ,  ( "F"              , NoArg  (setDynFlag Opt_Pp))
963   ,  ( "#include"       , HasArg (addCmdlineHCInclude) )
964   ,  ( "v"              , OptIntSuffix setVerbosity )
965
966         ------- Specific phases  --------------------------------------------
967   ,  ( "pgmL"           , HasArg (upd . setPgmL) )  
968   ,  ( "pgmP"           , HasArg (upd . setPgmP) )  
969   ,  ( "pgmF"           , HasArg (upd . setPgmF) )  
970   ,  ( "pgmc"           , HasArg (upd . setPgmc) )  
971   ,  ( "pgmm"           , HasArg (upd . setPgmm) )  
972   ,  ( "pgms"           , HasArg (upd . setPgms) )  
973   ,  ( "pgma"           , HasArg (upd . setPgma) )  
974   ,  ( "pgml"           , HasArg (upd . setPgml) )  
975   ,  ( "pgmdll"         , HasArg (upd . setPgmdll) )
976   ,  ( "pgmwindres"     , HasArg (upd . setPgmwindres) )
977
978   ,  ( "optL"           , HasArg (upd . addOptL) )  
979   ,  ( "optP"           , HasArg (upd . addOptP) )  
980   ,  ( "optF"           , HasArg (upd . addOptF) )  
981   ,  ( "optc"           , HasArg (upd . addOptc) )  
982   ,  ( "optm"           , HasArg (upd . addOptm) )  
983   ,  ( "opta"           , HasArg (upd . addOpta) )  
984   ,  ( "optl"           , HasArg (upd . addOptl) )  
985   ,  ( "optdep"         , HasArg (upd . addOptdep) )
986   ,  ( "optwindres"     , HasArg (upd . addOptwindres) )
987
988   ,  ( "split-objs"     , NoArg (if can_split
989                                     then setDynFlag Opt_SplitObjs
990                                     else return ()) )
991
992         -------- Linking ----------------------------------------------------
993   ,  ( "c"              , NoArg (upd $ \d -> d{ ghcLink=NoLink } ))
994   ,  ( "no-link"        , NoArg (upd $ \d -> d{ ghcLink=NoLink } )) -- Dep.
995   ,  ( "shared"         , NoArg (upd $ \d -> d{ ghcLink=LinkDynLib } ))
996
997         ------- Libraries ---------------------------------------------------
998   ,  ( "L"              , Prefix addLibraryPath )
999   ,  ( "l"              , AnySuffix (\s -> do upd (addOptl s)))
1000
1001         ------- Frameworks --------------------------------------------------
1002         -- -framework-path should really be -F ...
1003   ,  ( "framework-path" , HasArg addFrameworkPath )
1004   ,  ( "framework"      , HasArg (upd . addCmdlineFramework) )
1005
1006         ------- Output Redirection ------------------------------------------
1007   ,  ( "odir"           , HasArg (upd . setObjectDir))
1008   ,  ( "o"              , SepArg (upd . setOutputFile . Just))
1009   ,  ( "ohi"            , HasArg (upd . setOutputHi   . Just ))
1010   ,  ( "osuf"           , HasArg (upd . setObjectSuf))
1011   ,  ( "hcsuf"          , HasArg (upd . setHcSuf))
1012   ,  ( "hisuf"          , HasArg (upd . setHiSuf))
1013   ,  ( "hidir"          , HasArg (upd . setHiDir))
1014   ,  ( "tmpdir"         , HasArg (upd . setTmpDir))
1015   ,  ( "stubdir"        , HasArg (upd . setStubDir))
1016   ,  ( "ddump-file-prefix", HasArg (upd . setDumpPrefixForce . Just))
1017
1018         ------- Keeping temporary files -------------------------------------
1019      -- These can be singular (think ghc -c) or plural (think ghc --make)
1020   ,  ( "keep-hc-file"    , NoArg (setDynFlag Opt_KeepHcFiles))
1021   ,  ( "keep-hc-files"   , NoArg (setDynFlag Opt_KeepHcFiles))
1022   ,  ( "keep-s-file"     , NoArg (setDynFlag Opt_KeepSFiles))
1023   ,  ( "keep-s-files"    , NoArg (setDynFlag Opt_KeepSFiles))
1024   ,  ( "keep-raw-s-file" , NoArg (setDynFlag Opt_KeepRawSFiles))
1025   ,  ( "keep-raw-s-files", NoArg (setDynFlag Opt_KeepRawSFiles))
1026      -- This only makes sense as plural
1027   ,  ( "keep-tmp-files"  , NoArg (setDynFlag Opt_KeepTmpFiles))
1028
1029         ------- Miscellaneous ----------------------------------------------
1030   ,  ( "no-hs-main"     , NoArg (setDynFlag Opt_NoHsMain))
1031   ,  ( "main-is"        , SepArg setMainIs )
1032   ,  ( "haddock"        , NoArg (setDynFlag Opt_Haddock) )
1033   ,  ( "haddock-opts"   , HasArg (upd . addHaddockOpts))
1034   ,  ( "hpcdir"         , SepArg setOptHpcDir )
1035
1036         ------- recompilation checker (DEPRECATED, use -fforce-recomp) -----
1037   ,  ( "recomp"         , NoArg (unSetDynFlag Opt_ForceRecomp) )
1038   ,  ( "no-recomp"      , NoArg (setDynFlag   Opt_ForceRecomp) )
1039
1040         ------- Packages ----------------------------------------------------
1041   ,  ( "package-conf"   , HasArg extraPkgConf_ )
1042   ,  ( "no-user-package-conf", NoArg (unSetDynFlag Opt_ReadUserPackageConf) )
1043   ,  ( "package-name"   , HasArg (upd . setPackageName) )
1044   ,  ( "package"        , HasArg exposePackage )
1045   ,  ( "hide-package"   , HasArg hidePackage )
1046   ,  ( "hide-all-packages", NoArg (setDynFlag Opt_HideAllPackages) )
1047   ,  ( "ignore-package" , HasArg ignorePackage )
1048   ,  ( "syslib"         , HasArg exposePackage )  -- for compatibility
1049
1050         ------ HsCpp opts ---------------------------------------------------
1051   ,  ( "D",             AnySuffix (upd . addOptP) )
1052   ,  ( "U",             AnySuffix (upd . addOptP) )
1053
1054         ------- Include/Import Paths ----------------------------------------
1055   ,  ( "I"              , Prefix    addIncludePath)
1056   ,  ( "i"              , OptPrefix addImportPath )
1057
1058         ------ Debugging ----------------------------------------------------
1059   ,  ( "dstg-stats",    NoArg (setDynFlag Opt_StgStats))
1060
1061   ,  ( "ddump-cmm",              setDumpFlag Opt_D_dump_cmm)
1062   ,  ( "ddump-cmmz",             setDumpFlag Opt_D_dump_cmmz)
1063   ,  ( "ddump-cmmz-pretty",      setDumpFlag Opt_D_dump_cmmz_pretty)
1064   ,  ( "ddump-cps-cmm",          setDumpFlag Opt_D_dump_cps_cmm)
1065   ,  ( "ddump-cvt-cmm",          setDumpFlag Opt_D_dump_cvt_cmm)
1066   ,  ( "ddump-asm",              setDumpFlag Opt_D_dump_asm)
1067   ,  ( "ddump-asm-native",       setDumpFlag Opt_D_dump_asm_native)
1068   ,  ( "ddump-asm-liveness",     setDumpFlag Opt_D_dump_asm_liveness)
1069   ,  ( "ddump-asm-coalesce",     setDumpFlag Opt_D_dump_asm_coalesce)
1070   ,  ( "ddump-asm-regalloc",     setDumpFlag Opt_D_dump_asm_regalloc)
1071   ,  ( "ddump-asm-conflicts",    setDumpFlag Opt_D_dump_asm_conflicts)
1072   ,  ( "ddump-asm-regalloc-stages",
1073                                  setDumpFlag Opt_D_dump_asm_regalloc_stages)
1074   ,  ( "ddump-asm-stats",        setDumpFlag Opt_D_dump_asm_stats)
1075   ,  ( "ddump-cpranal",          setDumpFlag Opt_D_dump_cpranal)
1076   ,  ( "ddump-deriv",            setDumpFlag Opt_D_dump_deriv)
1077   ,  ( "ddump-ds",               setDumpFlag Opt_D_dump_ds)
1078   ,  ( "ddump-flatC",            setDumpFlag Opt_D_dump_flatC)
1079   ,  ( "ddump-foreign",          setDumpFlag Opt_D_dump_foreign)
1080   ,  ( "ddump-inlinings",        setDumpFlag Opt_D_dump_inlinings)
1081   ,  ( "ddump-rule-firings",     setDumpFlag Opt_D_dump_rule_firings)
1082   ,  ( "ddump-occur-anal",       setDumpFlag Opt_D_dump_occur_anal)
1083   ,  ( "ddump-parsed",           setDumpFlag Opt_D_dump_parsed)
1084   ,  ( "ddump-rn",               setDumpFlag Opt_D_dump_rn)
1085   ,  ( "ddump-simpl",            setDumpFlag Opt_D_dump_simpl)
1086   ,  ( "ddump-simpl-iterations", setDumpFlag Opt_D_dump_simpl_iterations)
1087   ,  ( "ddump-simpl-phases",     setDumpFlag Opt_D_dump_simpl_phases)
1088   ,  ( "ddump-spec",             setDumpFlag Opt_D_dump_spec)
1089   ,  ( "ddump-prep",             setDumpFlag Opt_D_dump_prep)
1090   ,  ( "ddump-stg",              setDumpFlag Opt_D_dump_stg)
1091   ,  ( "ddump-stranal",          setDumpFlag Opt_D_dump_stranal)
1092   ,  ( "ddump-tc",               setDumpFlag Opt_D_dump_tc)
1093   ,  ( "ddump-types",            setDumpFlag Opt_D_dump_types)
1094   ,  ( "ddump-rules",            setDumpFlag Opt_D_dump_rules)
1095   ,  ( "ddump-cse",              setDumpFlag Opt_D_dump_cse)
1096   ,  ( "ddump-worker-wrapper",   setDumpFlag Opt_D_dump_worker_wrapper)
1097   ,  ( "ddump-rn-trace",         setDumpFlag Opt_D_dump_rn_trace)
1098   ,  ( "ddump-if-trace",         setDumpFlag Opt_D_dump_if_trace)
1099   ,  ( "ddump-tc-trace",         setDumpFlag Opt_D_dump_tc_trace)
1100   ,  ( "ddump-splices",          setDumpFlag Opt_D_dump_splices)
1101   ,  ( "ddump-rn-stats",         setDumpFlag Opt_D_dump_rn_stats)
1102   ,  ( "ddump-opt-cmm",          setDumpFlag Opt_D_dump_opt_cmm)
1103   ,  ( "ddump-simpl-stats",      setDumpFlag Opt_D_dump_simpl_stats)
1104   ,  ( "ddump-bcos",             setDumpFlag Opt_D_dump_BCOs)
1105   ,  ( "dsource-stats",          setDumpFlag Opt_D_source_stats)
1106   ,  ( "dverbose-core2core",     setDumpFlag Opt_D_verbose_core2core)
1107   ,  ( "dverbose-stg2stg",       setDumpFlag Opt_D_verbose_stg2stg)
1108   ,  ( "ddump-hi",               setDumpFlag Opt_D_dump_hi)
1109   ,  ( "ddump-minimal-imports",  setDumpFlag Opt_D_dump_minimal_imports)
1110   ,  ( "ddump-vect",             setDumpFlag Opt_D_dump_vect)
1111   ,  ( "ddump-hpc",              setDumpFlag Opt_D_dump_hpc)
1112   ,  ( "ddump-mod-cycles",       setDumpFlag Opt_D_dump_mod_cycles)
1113   ,  ( "ddump-view-pattern-commoning", setDumpFlag Opt_D_dump_view_pattern_commoning)
1114   ,  ( "ddump-to-file",          setDumpFlag Opt_DumpToFile)
1115   ,  ( "ddump-hi-diffs",         NoArg (setDynFlag Opt_D_dump_hi_diffs))
1116   ,  ( "dcore-lint",             NoArg (setDynFlag Opt_DoCoreLinting))
1117   ,  ( "dstg-lint",              NoArg (setDynFlag Opt_DoStgLinting))
1118   ,  ( "dcmm-lint",              NoArg (setDynFlag Opt_DoCmmLinting))
1119   ,  ( "dasm-lint",              NoArg (setDynFlag Opt_DoAsmLinting))
1120   ,  ( "dshow-passes",           NoArg (do setDynFlag Opt_ForceRecomp
1121                                            setVerbosity (Just 2)) )
1122   ,  ( "dfaststring-stats",      NoArg (setDynFlag Opt_D_faststring_stats))
1123
1124         ------ Machine dependant (-m<blah>) stuff ---------------------------
1125
1126   ,  ( "monly-2-regs",  NoArg (upd (\s -> s{stolen_x86_regs = 2}) ))
1127   ,  ( "monly-3-regs",  NoArg (upd (\s -> s{stolen_x86_regs = 3}) ))
1128   ,  ( "monly-4-regs",  NoArg (upd (\s -> s{stolen_x86_regs = 4}) ))
1129
1130      ------ Warning opts -------------------------------------------------
1131   ,  ( "W"     , NoArg (mapM_ setDynFlag   minusWOpts)    )
1132   ,  ( "Werror", NoArg (setDynFlag         Opt_WarnIsError) )
1133   ,  ( "Wwarn" , NoArg (unSetDynFlag       Opt_WarnIsError) )
1134   ,  ( "Wall"  , NoArg (mapM_ setDynFlag   minusWallOpts) )
1135   ,  ( "Wnot"  , NoArg (mapM_ unSetDynFlag minusWallOpts) ) -- DEPRECATED
1136   ,  ( "w"     , NoArg (mapM_ unSetDynFlag minuswRemovesOpts) )
1137
1138         ------ Optimisation flags ------------------------------------------
1139   ,  ( "O"      , NoArg (upd (setOptLevel 1)))
1140   ,  ( "Onot"   , NoArg (upd (setOptLevel 0))) -- deprecated
1141   ,  ( "O"      , OptIntSuffix (\mb_n -> upd (setOptLevel (mb_n `orElse` 1))))
1142                 -- If the number is missing, use 1
1143
1144   ,  ( "fmax-simplifier-iterations", IntSuffix (\n -> 
1145                 upd (\dfs -> dfs{ maxSimplIterations = n })) )
1146
1147   ,  ( "fspec-constr-threshold",      IntSuffix (\n ->
1148                 upd (\dfs -> dfs{ specConstrThreshold = Just n })))
1149   ,  ( "fno-spec-constr-threshold",   NoArg (
1150                 upd (\dfs -> dfs{ specConstrThreshold = Nothing })))
1151   ,  ( "fliberate-case-threshold",    IntSuffix (\n ->
1152                 upd (\dfs -> dfs{ liberateCaseThreshold = Just n })))
1153   ,  ( "fno-liberate-case-threshold", NoArg (
1154                 upd (\dfs -> dfs{ liberateCaseThreshold = Nothing })))
1155
1156   ,  ( "frule-check",     SepArg (\s -> upd (\dfs -> dfs{ ruleCheck = Just s })))
1157   ,  ( "fcontext-stack" , IntSuffix $ \n -> upd $ \dfs -> dfs{ ctxtStkDepth = n })
1158
1159         ------ Compiler flags -----------------------------------------------
1160
1161   ,  ( "fasm",             NoArg (setObjTarget HscAsm) )
1162   ,  ( "fvia-c",           NoArg (setObjTarget HscC) )
1163   ,  ( "fvia-C",           NoArg (setObjTarget HscC) )
1164
1165   ,  ( "fno-code",         NoArg (setTarget HscNothing))
1166   ,  ( "fbyte-code",       NoArg (setTarget HscInterpreted) )
1167   ,  ( "fobject-code",     NoArg (setTarget defaultHscTarget) )
1168
1169   ,  ( "fglasgow-exts",    NoArg (mapM_ setDynFlag   glasgowExtsFlags) )
1170   ,  ( "fno-glasgow-exts", NoArg (mapM_ unSetDynFlag glasgowExtsFlags) )
1171
1172      -- the rest of the -f* and -fno-* flags
1173   ,  ( "f",                PrefixPred (isFlag   fFlags)
1174                            (\f -> setDynFlag   (getFlag   fFlags f)) )
1175   ,  ( "f",                PrefixPred (isPrefFlag "no-" fFlags)
1176                            (\f -> unSetDynFlag (getPrefFlag "no-" fFlags f)) )
1177
1178      -- the -X* and -XNo* flags
1179   ,  ( "X",                PrefixPred (isFlag   xFlags)
1180                            (\f -> setDynFlag   (getFlag   xFlags f)) )
1181   ,  ( "X",                PrefixPred (isPrefFlag "No" xFlags)
1182                            (\f -> unSetDynFlag (getPrefFlag "No" xFlags f)) )
1183  ]
1184
1185 -- these -f<blah> flags can all be reversed with -fno-<blah>
1186
1187 fFlags = [
1188   ( "warn-dodgy-imports",               Opt_WarnDodgyImports ),
1189   ( "warn-duplicate-exports",           Opt_WarnDuplicateExports ),
1190   ( "warn-hi-shadowing",                Opt_WarnHiShadows ),
1191   ( "warn-implicit-prelude",            Opt_WarnImplicitPrelude ),
1192   ( "warn-incomplete-patterns",         Opt_WarnIncompletePatterns ),
1193   ( "warn-incomplete-record-updates",   Opt_WarnIncompletePatternsRecUpd ),
1194   ( "warn-missing-fields",              Opt_WarnMissingFields ),
1195   ( "warn-missing-methods",             Opt_WarnMissingMethods ),
1196   ( "warn-missing-signatures",          Opt_WarnMissingSigs ),
1197   ( "warn-name-shadowing",              Opt_WarnNameShadowing ),
1198   ( "warn-overlapping-patterns",        Opt_WarnOverlappingPatterns ),
1199   ( "warn-simple-patterns",             Opt_WarnSimplePatterns ),
1200   ( "warn-type-defaults",               Opt_WarnTypeDefaults ),
1201   ( "warn-monomorphism-restriction",    Opt_WarnMonomorphism ),
1202   ( "warn-unused-binds",                Opt_WarnUnusedBinds ),
1203   ( "warn-unused-imports",              Opt_WarnUnusedImports ),
1204   ( "warn-unused-matches",              Opt_WarnUnusedMatches ),
1205   ( "warn-deprecations",                Opt_WarnDeprecations ),
1206   ( "warn-orphans",                     Opt_WarnOrphans ),
1207   ( "warn-tabs",                        Opt_WarnTabs ),
1208   ( "print-explicit-foralls",           Opt_PrintExplicitForalls ),
1209   ( "strictness",                       Opt_Strictness ),
1210   ( "full-laziness",                    Opt_FullLaziness ),
1211   ( "liberate-case",                    Opt_LiberateCase ),
1212   ( "spec-constr",                      Opt_SpecConstr ),
1213   ( "cse",                              Opt_CSE ),
1214   ( "ignore-interface-pragmas",         Opt_IgnoreInterfacePragmas ),
1215   ( "omit-interface-pragmas",           Opt_OmitInterfacePragmas ),
1216   ( "do-lambda-eta-expansion",          Opt_DoLambdaEtaExpansion ),
1217   ( "ignore-asserts",                   Opt_IgnoreAsserts ),
1218   ( "do-eta-reduction",                 Opt_DoEtaReduction ),
1219   ( "case-merge",                       Opt_CaseMerge ),
1220   ( "unbox-strict-fields",              Opt_UnboxStrictFields ),
1221   ( "dicts-cheap",                      Opt_DictsCheap ),
1222   ( "excess-precision",                 Opt_ExcessPrecision ),
1223   ( "asm-mangling",                     Opt_DoAsmMangling ),
1224   ( "print-bind-result",                Opt_PrintBindResult ),
1225   ( "force-recomp",                     Opt_ForceRecomp ),
1226   ( "hpc-no-auto",                      Opt_Hpc_No_Auto ),
1227   ( "rewrite-rules",                    Opt_RewriteRules ),
1228   ( "break-on-exception",               Opt_BreakOnException ),
1229   ( "break-on-error",                   Opt_BreakOnError ),
1230   ( "print-evld-with-show",             Opt_PrintEvldWithShow ),
1231   ( "print-bind-contents",              Opt_PrintBindContents ),
1232   ( "run-cps",                          Opt_RunCPSZ ),
1233   ( "convert-to-zipper-and-back",       Opt_ConvertToZipCfgAndBack),
1234   ( "vectorise",                        Opt_Vectorise ),
1235   ( "regs-graph",                       Opt_RegsGraph),
1236   ( "regs-iterative",                   Opt_RegsIterative),
1237   -- Deprecated in favour of -XTemplateHaskell:
1238   ( "th",                               Opt_TemplateHaskell ),
1239   -- Deprecated in favour of -XForeignFunctionInterface:
1240   ( "fi",                               Opt_ForeignFunctionInterface ),
1241   -- Deprecated in favour of -XForeignFunctionInterface:
1242   ( "ffi",                              Opt_ForeignFunctionInterface ),
1243   -- Deprecated in favour of -XArrows:
1244   ( "arrows",                           Opt_Arrows ),
1245   -- Deprecated in favour of -XGenerics:
1246   ( "generics",                         Opt_Generics ),
1247   -- Deprecated in favour of -XImplicitPrelude:
1248   ( "implicit-prelude",                 Opt_ImplicitPrelude ),
1249   -- Deprecated in favour of -XBangPatterns:
1250   ( "bang-patterns",                    Opt_BangPatterns ),
1251   -- Deprecated in favour of -XMonomorphismRestriction:
1252   ( "monomorphism-restriction",         Opt_MonomorphismRestriction ),
1253   -- Deprecated in favour of -XMonoPatBinds:
1254   ( "mono-pat-binds",                   Opt_MonoPatBinds ),
1255   -- Deprecated in favour of -XExtendedDefaultRules:
1256   ( "extended-default-rules",           Opt_ExtendedDefaultRules ),
1257   -- Deprecated in favour of -XImplicitParams:
1258   ( "implicit-params",                  Opt_ImplicitParams ),
1259   -- Deprecated in favour of -XScopedTypeVariables:
1260   ( "scoped-type-variables",            Opt_ScopedTypeVariables ),
1261   -- Deprecated in favour of -XPArr:
1262   ( "parr",                             Opt_PArr ),
1263   -- Deprecated in favour of -XOverlappingInstances:
1264   ( "allow-overlapping-instances",      Opt_OverlappingInstances ),
1265   -- Deprecated in favour of -XUndecidableInstances:
1266   ( "allow-undecidable-instances",      Opt_UndecidableInstances ),
1267   -- Deprecated in favour of -XIncoherentInstances:
1268   ( "allow-incoherent-instances",       Opt_IncoherentInstances ),
1269   ( "gen-manifest",                     Opt_GenManifest ),
1270   ( "embed-manifest",                   Opt_EmbedManifest )
1271   ]
1272
1273 supportedLanguages :: [String]
1274 supportedLanguages = map fst xFlags
1275
1276 -- These -X<blah> flags can all be reversed with -XNo<blah>
1277 xFlags :: [(String, DynFlag)]
1278 xFlags = [
1279   ( "CPP",                              Opt_Cpp ),
1280   ( "PatternGuards",                    Opt_PatternGuards ),
1281   ( "UnicodeSyntax",                    Opt_UnicodeSyntax ),
1282   ( "MagicHash",                        Opt_MagicHash ),
1283   ( "PolymorphicComponents",            Opt_PolymorphicComponents ),
1284   ( "ExistentialQuantification",        Opt_ExistentialQuantification ),
1285   ( "KindSignatures",                   Opt_KindSignatures ),
1286   ( "PatternSignatures",                Opt_PatternSignatures ),
1287   ( "EmptyDataDecls",                   Opt_EmptyDataDecls ),
1288   ( "ParallelListComp",                 Opt_ParallelListComp ),
1289   ( "TransformListComp",                Opt_TransformListComp ),
1290   ( "ForeignFunctionInterface",         Opt_ForeignFunctionInterface ),
1291   ( "UnliftedFFITypes",                 Opt_UnliftedFFITypes ),
1292   ( "LiberalTypeSynonyms",              Opt_LiberalTypeSynonyms ),
1293   ( "Rank2Types",                       Opt_Rank2Types ),
1294   ( "RankNTypes",                       Opt_RankNTypes ),
1295   ( "ImpredicativeTypes",               Opt_ImpredicativeTypes ),
1296   ( "TypeOperators",                    Opt_TypeOperators ),
1297   ( "RecursiveDo",                      Opt_RecursiveDo ),
1298   ( "Arrows",                           Opt_Arrows ),
1299   ( "PArr",                             Opt_PArr ),
1300   ( "TemplateHaskell",                  Opt_TemplateHaskell ),
1301   ( "Generics",                         Opt_Generics ),
1302   -- On by default:
1303   ( "ImplicitPrelude",                  Opt_ImplicitPrelude ),
1304   ( "RecordWildCards",                  Opt_RecordWildCards ),
1305   ( "RecordPuns",                       Opt_RecordPuns ),
1306   ( "DisambiguateRecordFields",         Opt_DisambiguateRecordFields ),
1307   ( "OverloadedStrings",                Opt_OverloadedStrings ),
1308   ( "GADTs",                            Opt_GADTs ),
1309   ( "ViewPatterns",                     Opt_ViewPatterns),
1310   ( "TypeFamilies",                     Opt_TypeFamilies ),
1311   ( "BangPatterns",                     Opt_BangPatterns ),
1312   -- On by default:
1313   ( "MonomorphismRestriction",          Opt_MonomorphismRestriction ),
1314   -- On by default (which is not strictly H98):
1315   ( "MonoPatBinds",                     Opt_MonoPatBinds ),
1316   ( "RelaxedPolyRec",                   Opt_RelaxedPolyRec),
1317   ( "ExtendedDefaultRules",             Opt_ExtendedDefaultRules ),
1318   ( "ImplicitParams",                   Opt_ImplicitParams ),
1319   ( "ScopedTypeVariables",              Opt_ScopedTypeVariables ),
1320   ( "UnboxedTuples",                    Opt_UnboxedTuples ),
1321   ( "StandaloneDeriving",               Opt_StandaloneDeriving ),
1322   ( "DeriveDataTypeable",               Opt_DeriveDataTypeable ),
1323   ( "TypeSynonymInstances",             Opt_TypeSynonymInstances ),
1324   ( "FlexibleContexts",                 Opt_FlexibleContexts ),
1325   ( "FlexibleInstances",                Opt_FlexibleInstances ),
1326   ( "ConstrainedClassMethods",          Opt_ConstrainedClassMethods ),
1327   ( "MultiParamTypeClasses",            Opt_MultiParamTypeClasses ),
1328   ( "FunctionalDependencies",           Opt_FunctionalDependencies ),
1329   ( "GeneralizedNewtypeDeriving",       Opt_GeneralizedNewtypeDeriving ),
1330   ( "OverlappingInstances",             Opt_OverlappingInstances ),
1331   ( "UndecidableInstances",             Opt_UndecidableInstances ),
1332   ( "IncoherentInstances",              Opt_IncoherentInstances )
1333   ]
1334
1335 impliedFlags :: [(DynFlag, [DynFlag])]
1336 impliedFlags = [
1337   ( Opt_GADTs, [Opt_RelaxedPolyRec] )   -- We want type-sig variables to be completely rigid for GADTs
1338   ]
1339
1340 glasgowExtsFlags = [
1341              Opt_PrintExplicitForalls
1342            , Opt_ForeignFunctionInterface
1343            , Opt_UnliftedFFITypes
1344            , Opt_GADTs
1345            , Opt_ImplicitParams 
1346            , Opt_ScopedTypeVariables
1347            , Opt_UnboxedTuples
1348            , Opt_TypeSynonymInstances
1349            , Opt_StandaloneDeriving
1350            , Opt_DeriveDataTypeable
1351            , Opt_FlexibleContexts
1352            , Opt_FlexibleInstances
1353            , Opt_ConstrainedClassMethods
1354            , Opt_MultiParamTypeClasses
1355            , Opt_FunctionalDependencies
1356            , Opt_MagicHash
1357            , Opt_PolymorphicComponents
1358            , Opt_ExistentialQuantification
1359            , Opt_UnicodeSyntax
1360            , Opt_PatternGuards
1361            , Opt_LiberalTypeSynonyms
1362            , Opt_RankNTypes
1363            , Opt_ImpredicativeTypes
1364            , Opt_TypeOperators
1365            , Opt_RecursiveDo
1366            , Opt_ParallelListComp
1367            , Opt_EmptyDataDecls
1368            , Opt_KindSignatures
1369            , Opt_PatternSignatures
1370            , Opt_GeneralizedNewtypeDeriving
1371            , Opt_TypeFamilies ]
1372
1373 ------------------
1374 isFlag :: [(String,a)] -> String -> Bool
1375 isFlag flags f = any (\(ff,_) -> ff == f) flags
1376
1377 isPrefFlag :: String -> [(String,a)] -> String -> Bool
1378 isPrefFlag pref flags no_f
1379   | Just f <- maybePrefixMatch pref no_f = isFlag flags f
1380   | otherwise                            = False
1381
1382 ------------------
1383 getFlag :: [(String,a)] -> String -> a
1384 getFlag flags f = case [ opt | (ff, opt) <- flags, ff == f] of
1385                       (o:os) -> o
1386                       []     -> panic ("get_flag " ++ f)
1387
1388 getPrefFlag :: String -> [(String,a)] -> String -> a
1389 getPrefFlag pref flags f = getFlag flags (fromJust (maybePrefixMatch pref f))
1390 -- We should only be passed flags which match the prefix
1391
1392 -- -----------------------------------------------------------------------------
1393 -- Parsing the dynamic flags.
1394
1395 parseDynamicFlags :: DynFlags -> [String] -> IO (DynFlags,[String])
1396 parseDynamicFlags dflags args = do
1397   let ((leftover,errs),dflags') 
1398           = runCmdLine (processArgs dynamic_flags args) dflags
1399   when (not (null errs)) $ do
1400     throwDyn (UsageError (unlines errs))
1401   return (dflags', leftover)
1402
1403
1404 type DynP = CmdLineP DynFlags
1405
1406 upd :: (DynFlags -> DynFlags) -> DynP ()
1407 upd f = do 
1408    dfs <- getCmdLineState
1409    putCmdLineState $! (f dfs)
1410
1411 --------------------------
1412 setDynFlag, unSetDynFlag :: DynFlag -> DynP ()
1413 setDynFlag f = upd (\dfs -> foldl dopt_set (dopt_set dfs f) deps)
1414   where
1415     deps = [ d | (f', ds) <- impliedFlags, f' == f, d <- ds ]
1416         -- When you set f, set the ones it implies
1417         -- When you un-set f, however, we don't un-set the things it implies
1418         --      (except for -fno-glasgow-exts, which is treated specially)
1419
1420 unSetDynFlag f = upd (\dfs -> dopt_unset dfs f)
1421
1422 --------------------------
1423 setDumpFlag :: DynFlag -> OptKind DynP
1424 setDumpFlag dump_flag 
1425   = NoArg (setDynFlag Opt_ForceRecomp >> setDynFlag dump_flag)
1426         -- Whenver we -ddump, switch off the recompilation checker,
1427         -- else you don't see the dump!
1428
1429 setVerbosity :: Maybe Int -> DynP ()
1430 setVerbosity mb_n = upd (\dfs -> dfs{ verbosity = mb_n `orElse` 3 })
1431
1432 addCmdlineHCInclude a = upd (\s -> s{cmdlineHcIncludes =  a : cmdlineHcIncludes s})
1433
1434 extraPkgConf_  p = upd (\s -> s{ extraPkgConfs = p : extraPkgConfs s })
1435
1436 exposePackage p = 
1437   upd (\s -> s{ packageFlags = ExposePackage p : packageFlags s })
1438 hidePackage p = 
1439   upd (\s -> s{ packageFlags = HidePackage p : packageFlags s })
1440 ignorePackage p = 
1441   upd (\s -> s{ packageFlags = IgnorePackage p : packageFlags s })
1442
1443 setPackageName p
1444   | Nothing <- unpackPackageId pid
1445   = throwDyn (CmdLineError ("cannot parse \'" ++ p ++ "\' as a package identifier"))
1446   | otherwise
1447   = \s -> s{ thisPackage = pid }
1448   where
1449         pid = stringToPackageId p
1450
1451 -- If we're linking a binary, then only targets that produce object
1452 -- code are allowed (requests for other target types are ignored).
1453 setTarget l = upd set
1454   where 
1455    set dfs 
1456      | ghcLink dfs /= LinkBinary || isObjectTarget l  = dfs{ hscTarget = l }
1457      | otherwise = dfs
1458
1459 -- Changes the target only if we're compiling object code.  This is
1460 -- used by -fasm and -fvia-C, which switch from one to the other, but
1461 -- not from bytecode to object-code.  The idea is that -fasm/-fvia-C
1462 -- can be safely used in an OPTIONS_GHC pragma.
1463 setObjTarget l = upd set
1464   where 
1465    set dfs 
1466      | isObjectTarget (hscTarget dfs) = dfs { hscTarget = l }
1467      | otherwise = dfs
1468
1469 setOptLevel :: Int -> DynFlags -> DynFlags
1470 setOptLevel n dflags
1471    | hscTarget dflags == HscInterpreted && n > 0
1472         = dflags
1473             -- not in IO any more, oh well:
1474             -- putStr "warning: -O conflicts with --interactive; -O ignored.\n"
1475    | otherwise
1476         = updOptLevel n dflags
1477
1478
1479 setMainIs :: String -> DynP ()
1480 setMainIs arg
1481   | not (null main_fn) && isLower (head main_fn)
1482      -- The arg looked like "Foo.Bar.baz"
1483   = upd $ \d -> d{ mainFunIs = Just main_fn,
1484                    mainModIs = mkModule mainPackageId (mkModuleName main_mod) }
1485
1486   | isUpper (head arg)  -- The arg looked like "Foo" or "Foo.Bar"
1487   = upd $ \d -> d{ mainModIs = mkModule mainPackageId (mkModuleName arg) }
1488   
1489   | otherwise                   -- The arg looked like "baz"
1490   = upd $ \d -> d{ mainFunIs = Just arg }
1491   where
1492     (main_mod, main_fn) = splitLongestPrefix arg (== '.')
1493
1494 -----------------------------------------------------------------------------
1495 -- Paths & Libraries
1496
1497 -- -i on its own deletes the import paths
1498 addImportPath "" = upd (\s -> s{importPaths = []})
1499 addImportPath p  = upd (\s -> s{importPaths = importPaths s ++ splitPathList p})
1500
1501
1502 addLibraryPath p = 
1503   upd (\s -> s{libraryPaths = libraryPaths s ++ splitPathList p})
1504
1505 addIncludePath p = 
1506   upd (\s -> s{includePaths = includePaths s ++ splitPathList p})
1507
1508 addFrameworkPath p = 
1509   upd (\s -> s{frameworkPaths = frameworkPaths s ++ splitPathList p})
1510
1511 split_marker = ':'   -- not configurable (ToDo)
1512
1513 splitPathList :: String -> [String]
1514 splitPathList s = filter notNull (splitUp s)
1515                 -- empty paths are ignored: there might be a trailing
1516                 -- ':' in the initial list, for example.  Empty paths can
1517                 -- cause confusion when they are translated into -I options
1518                 -- for passing to gcc.
1519   where
1520 #ifndef mingw32_TARGET_OS
1521     splitUp xs = split split_marker xs
1522 #else 
1523      -- Windows: 'hybrid' support for DOS-style paths in directory lists.
1524      -- 
1525      -- That is, if "foo:bar:baz" is used, this interpreted as
1526      -- consisting of three entries, 'foo', 'bar', 'baz'.
1527      -- However, with "c:/foo:c:\\foo;x:/bar", this is interpreted
1528      -- as 3 elts, "c:/foo", "c:\\foo", "x:/bar"
1529      --
1530      -- Notice that no attempt is made to fully replace the 'standard'
1531      -- split marker ':' with the Windows / DOS one, ';'. The reason being
1532      -- that this will cause too much breakage for users & ':' will
1533      -- work fine even with DOS paths, if you're not insisting on being silly.
1534      -- So, use either.
1535     splitUp []             = []
1536     splitUp (x:':':div:xs) | div `elem` dir_markers
1537                            = ((x:':':div:p): splitUp rs)
1538                            where
1539                               (p,rs) = findNextPath xs
1540           -- we used to check for existence of the path here, but that
1541           -- required the IO monad to be threaded through the command-line
1542           -- parser which is quite inconvenient.  The 
1543     splitUp xs = cons p (splitUp rs)
1544                where
1545                  (p,rs) = findNextPath xs
1546     
1547                  cons "" xs = xs
1548                  cons x  xs = x:xs
1549
1550     -- will be called either when we've consumed nought or the
1551     -- "<Drive>:/" part of a DOS path, so splitting is just a Q of
1552     -- finding the next split marker.
1553     findNextPath xs = 
1554         case break (`elem` split_markers) xs of
1555            (p, d:ds) -> (p, ds)
1556            (p, xs)   -> (p, xs)
1557
1558     split_markers :: [Char]
1559     split_markers = [':', ';']
1560
1561     dir_markers :: [Char]
1562     dir_markers = ['/', '\\']
1563 #endif
1564
1565 -- -----------------------------------------------------------------------------
1566 -- tmpDir, where we store temporary files.
1567
1568 setTmpDir :: FilePath -> DynFlags -> DynFlags
1569 setTmpDir dir dflags = dflags{ tmpDir = canonicalise dir }
1570   where
1571 #if !defined(mingw32_HOST_OS)
1572      canonicalise p = normalisePath p
1573 #else
1574         -- Canonicalisation of temp path under win32 is a bit more
1575         -- involved: (a) strip trailing slash, 
1576         --           (b) normalise slashes
1577         --           (c) just in case, if there is a prefix /cygdrive/x/, change to x:
1578         -- 
1579      canonicalise path = normalisePath (xltCygdrive (removeTrailingSlash path))
1580
1581         -- if we're operating under cygwin, and TMP/TEMP is of
1582         -- the form "/cygdrive/drive/path", translate this to
1583         -- "drive:/path" (as GHC isn't a cygwin app and doesn't
1584         -- understand /cygdrive paths.)
1585      xltCygdrive path
1586       | "/cygdrive/" `isPrefixOf` path = 
1587           case drop (length "/cygdrive/") path of
1588             drive:xs@('/':_) -> drive:':':xs
1589             _ -> path
1590       | otherwise = path
1591
1592         -- strip the trailing backslash (awful, but we only do this once).
1593      removeTrailingSlash path = 
1594        case last path of
1595          '/'  -> init path
1596          '\\' -> init path
1597          _    -> path
1598 #endif
1599
1600 -----------------------------------------------------------------------------
1601 -- Hpc stuff
1602
1603 setOptHpcDir :: String -> DynP ()
1604 setOptHpcDir arg  = upd $ \ d -> d{hpcDir = arg}
1605
1606 -----------------------------------------------------------------------------
1607 -- Via-C compilation stuff
1608
1609 -- There are some options that we need to pass to gcc when compiling
1610 -- Haskell code via C, but are only supported by recent versions of
1611 -- gcc.  The configure script decides which of these options we need,
1612 -- and puts them in the file "extra-gcc-opts" in $topdir, which is
1613 -- read before each via-C compilation.  The advantage of having these
1614 -- in a separate file is that the file can be created at install-time
1615 -- depending on the available gcc version, and even re-generated  later
1616 -- if gcc is upgraded.
1617 --
1618 -- The options below are not dependent on the version of gcc, only the
1619 -- platform.
1620
1621 machdepCCOpts :: DynFlags -> ([String], -- flags for all C compilations
1622                               [String]) -- for registerised HC compilations
1623 machdepCCOpts dflags
1624 #if alpha_TARGET_ARCH
1625         =       ( ["-w", "-mieee"
1626 #ifdef HAVE_THREADED_RTS_SUPPORT
1627                     , "-D_REENTRANT"
1628 #endif
1629                    ], [] )
1630         -- For now, to suppress the gcc warning "call-clobbered
1631         -- register used for global register variable", we simply
1632         -- disable all warnings altogether using the -w flag. Oh well.
1633
1634 #elif hppa_TARGET_ARCH
1635         -- ___HPUX_SOURCE, not _HPUX_SOURCE, is #defined if -ansi!
1636         -- (very nice, but too bad the HP /usr/include files don't agree.)
1637         = ( ["-D_HPUX_SOURCE"], [] )
1638
1639 #elif m68k_TARGET_ARCH
1640       -- -fno-defer-pop : for the .hc files, we want all the pushing/
1641       --    popping of args to routines to be explicit; if we let things
1642       --    be deferred 'til after an STGJUMP, imminent death is certain!
1643       --
1644       -- -fomit-frame-pointer : *don't*
1645       --     It's better to have a6 completely tied up being a frame pointer
1646       --     rather than let GCC pick random things to do with it.
1647       --     (If we want to steal a6, then we would try to do things
1648       --     as on iX86, where we *do* steal the frame pointer [%ebp].)
1649         = ( [], ["-fno-defer-pop", "-fno-omit-frame-pointer"] )
1650
1651 #elif i386_TARGET_ARCH
1652       -- -fno-defer-pop : basically the same game as for m68k
1653       --
1654       -- -fomit-frame-pointer : *must* in .hc files; because we're stealing
1655       --   the fp (%ebp) for our register maps.
1656         =  let n_regs = stolen_x86_regs dflags
1657                sta = opt_Static
1658            in
1659                     ( [ if sta then "-DDONT_WANT_WIN32_DLL_SUPPORT" else ""
1660 --                    , if "mingw32" `isSuffixOf` cTARGETPLATFORM then "-mno-cygwin" else "" 
1661                       ],
1662                       [ "-fno-defer-pop",
1663                         "-fomit-frame-pointer",
1664                         -- we want -fno-builtin, because when gcc inlines
1665                         -- built-in functions like memcpy() it tends to
1666                         -- run out of registers, requiring -monly-n-regs
1667                         "-fno-builtin",
1668                         "-DSTOLEN_X86_REGS="++show n_regs ]
1669                     )
1670
1671 #elif ia64_TARGET_ARCH
1672         = ( [], ["-fomit-frame-pointer", "-G0"] )
1673
1674 #elif x86_64_TARGET_ARCH
1675         = ( [], ["-fomit-frame-pointer",
1676                  "-fno-asynchronous-unwind-tables",
1677                         -- the unwind tables are unnecessary for HC code,
1678                         -- and get in the way of -split-objs.  Another option
1679                         -- would be to throw them away in the mangler, but this
1680                         -- is easier.
1681                  "-fno-builtin"
1682                         -- calling builtins like strlen() using the FFI can
1683                         -- cause gcc to run out of regs, so use the external
1684                         -- version.
1685                 ] )
1686
1687 #elif sparc_TARGET_ARCH
1688         = ( [], ["-w"] )
1689         -- For now, to suppress the gcc warning "call-clobbered
1690         -- register used for global register variable", we simply
1691         -- disable all warnings altogether using the -w flag. Oh well.
1692
1693 #elif powerpc_apple_darwin_TARGET
1694       -- -no-cpp-precomp:
1695       --     Disable Apple's precompiling preprocessor. It's a great thing
1696       --     for "normal" programs, but it doesn't support register variable
1697       --     declarations.
1698         = ( [], ["-no-cpp-precomp"] )
1699 #else
1700         = ( [], [] )
1701 #endif
1702
1703 picCCOpts :: DynFlags -> [String]
1704 picCCOpts dflags
1705 #if darwin_TARGET_OS
1706       -- Apple prefers to do things the other way round.
1707       -- PIC is on by default.
1708       -- -mdynamic-no-pic:
1709       --     Turn off PIC code generation.
1710       -- -fno-common:
1711       --     Don't generate "common" symbols - these are unwanted
1712       --     in dynamic libraries.
1713
1714     | opt_PIC
1715         = ["-fno-common", "-D__PIC__"]
1716     | otherwise
1717         = ["-mdynamic-no-pic"]
1718 #elif mingw32_TARGET_OS
1719       -- no -fPIC for Windows
1720     | opt_PIC
1721         = ["-D__PIC__"]
1722     | otherwise
1723         = []
1724 #else
1725     | opt_PIC
1726         = ["-fPIC", "-D__PIC__"]
1727     | otherwise
1728         = []
1729 #endif
1730
1731 -- -----------------------------------------------------------------------------
1732 -- Splitting
1733
1734 can_split :: Bool
1735 can_split = cSplitObjs == "YES"
1736
1737 -- -----------------------------------------------------------------------------
1738 -- Compiler Info
1739
1740 compilerInfo :: [(String, String)]
1741 compilerInfo = [("Project name",                cProjectName),
1742                 ("Project version",             cProjectVersion),
1743                 ("Booter version",              cBooterVersion),
1744                 ("Stage",                       cStage),
1745                 ("Interface file version",      cHscIfaceFileVersion),
1746                 ("Have interpreter",            cGhcWithInterpreter),
1747                 ("Object splitting",            cSplitObjs),
1748                 ("Have native code generator",  cGhcWithNativeCodeGen),
1749                 ("Support SMP",                 cGhcWithSMP),
1750                 ("Unregisterised",              cGhcUnregisterised),
1751                 ("Tables next to code",         cGhcEnableTablesNextToCode),
1752                 ("Win32 DLLs",                  cEnableWin32DLLs),
1753                 ("RTS ways",                    cGhcRTSWays),
1754                 ("Leading underscore",          cLeadingUnderscore)]
1755