2 {-# OPTIONS -fno-warn-missing-fields #-}
3 -----------------------------------------------------------------------------
7 -- Most flags are dynamic flags, which means they can change from
8 -- compilation to compilation using OPTIONS_GHC pragmas, and in a
9 -- multi-session GHC each session can be using different dynamic
10 -- flags. Dynamic flags can also be set at the prompt in GHCi.
12 -- (c) The University of Glasgow 2005
14 -----------------------------------------------------------------------------
20 HscTarget(..), isObjectTarget, defaultObjectTarget,
21 GhcMode(..), isOneShot,
22 GhcLink(..), isNoLink,
26 -- Configuration of the core-to-core and stg-to-stg phases
30 SimplifierMode(..), FloatOutSwitches(..),
31 getCoreToDo, getStgToDo,
33 -- Manipulating DynFlags
34 defaultDynFlags, -- DynFlags
35 initDynFlags, -- DynFlags -> IO DynFlags
37 dopt, -- DynFlag -> DynFlags -> Bool
38 dopt_set, dopt_unset, -- DynFlags -> DynFlag -> DynFlags
39 getOpts, -- (DynFlags -> [a]) -> IO [a]
50 machdepCCOpts, picCCOpts
53 #include "HsVersions.h"
55 import Module ( Module, mkModuleName, mkModule )
57 import PrelNames ( mAIN )
58 #ifdef i386_TARGET_ARCH
59 import StaticFlags ( opt_Static )
61 import StaticFlags ( opt_PIC, WayName(..), v_Ways, v_Build_tag,
63 import {-# SOURCE #-} Packages (PackageState)
64 import DriverPhases ( Phase(..), phaseInputExt )
67 import Constants ( mAX_CONTEXT_REDUCTION_DEPTH )
68 import Panic ( panic, GhcException(..) )
69 import UniqFM ( UniqFM )
70 import Util ( notNull, splitLongestPrefix, normalisePath )
71 import Maybes ( orElse, fromJust )
72 import SrcLoc ( SrcSpan )
74 import {-# SOURCE #-} ErrUtils ( Severity(..), Message, mkLocMessage )
76 import Data.IORef ( readIORef )
77 import Control.Exception ( throwDyn )
78 import Control.Monad ( when )
79 #ifdef mingw32_TARGET_OS
80 import Data.List ( isPrefixOf )
85 import Data.Char ( isUpper, toLower )
86 import System.IO ( hPutStrLn, stderr )
88 -- -----------------------------------------------------------------------------
102 | Opt_D_dump_inlinings
103 | Opt_D_dump_rule_firings
104 | Opt_D_dump_occur_anal
108 | Opt_D_dump_simpl_iterations
117 | Opt_D_dump_worker_wrapper
118 | Opt_D_dump_rn_trace
119 | Opt_D_dump_rn_stats
121 | Opt_D_dump_simpl_stats
122 | Opt_D_dump_tc_trace
123 | Opt_D_dump_if_trace
129 | Opt_D_verbose_core2core
130 | Opt_D_verbose_stg2stg
132 | Opt_D_dump_hi_diffs
133 | Opt_D_dump_minimal_imports
134 | Opt_D_dump_mod_cycles
135 | Opt_D_faststring_stats
140 | Opt_WarnIsError -- -Werror; makes warnings fatal
141 | Opt_WarnDuplicateExports
143 | Opt_WarnImplicitPrelude
144 | Opt_WarnIncompletePatterns
145 | Opt_WarnIncompletePatternsRecUpd
146 | Opt_WarnMissingFields
147 | Opt_WarnMissingMethods
148 | Opt_WarnMissingSigs
149 | Opt_WarnNameShadowing
150 | Opt_WarnOverlappingPatterns
151 | Opt_WarnSimplePatterns
152 | Opt_WarnTypeDefaults
153 | Opt_WarnMonomorphism
154 | Opt_WarnUnusedBinds
155 | Opt_WarnUnusedImports
156 | Opt_WarnUnusedMatches
157 | Opt_WarnDeprecations
158 | Opt_WarnDodgyImports
163 | Opt_AllowOverlappingInstances
164 | Opt_AllowUndecidableInstances
165 | Opt_AllowIncoherentInstances
166 | Opt_MonomorphismRestriction
168 | Opt_ExtendedDefaultRules -- Use GHC's extended rules for defaulting
171 | Opt_UnliftedFFITypes
172 | Opt_PArr -- Syntactic support for parallel arrays
173 | Opt_Arrows -- Arrow-notation syntax
177 | Opt_ImplicitPrelude
178 | Opt_ScopedTypeVariables
180 | Opt_ExpressionSignaturesUnboxedTuples
181 | Opt_TypeSynonymUnboxedTuples
184 | Opt_OverloadedStrings
185 | Opt_DisambiguateRecordFields
186 | Opt_RecordWildCards
189 | Opt_RelaxedPolyRec -- -X=RelaxedPolyRec
190 | Opt_TypeSynonymInstances
191 | Opt_FlexibleContexts
192 | Opt_FlexibleInstances
193 | Opt_ConstrainedClassMethods
194 | Opt_MultiParamTypeClasses
195 | Opt_FunctionalDependencies
197 | Opt_PolymorphicComponents
198 | Opt_ExistentialQuantification
202 | Opt_PatternSignatures
203 | Opt_ParallelListComp
204 | Opt_GeneralizedNewtypeDeriving
207 | Opt_PartiallyAppliedClosedTypeSynonyms
212 | Opt_PrintExplicitForalls
220 | Opt_IgnoreInterfacePragmas
221 | Opt_OmitInterfacePragmas
222 | Opt_DoLambdaEtaExpansion
224 | Opt_IgnoreBreakpoints
227 | Opt_UnboxStrictFields
238 | Opt_ExcessPrecision
239 | Opt_ReadUserPackageConf
243 | Opt_HideAllPackages
244 | Opt_PrintBindResult
247 | Opt_BreakOnException
258 data DynFlags = DynFlags {
261 coreToDo :: Maybe [CoreToDo], -- reserved for -Ofile
262 stgToDo :: Maybe [StgToDo], -- similarly
263 hscTarget :: HscTarget,
264 hscOutName :: String, -- name of the output file
265 extCoreName :: String, -- name of the .core output file
266 verbosity :: Int, -- verbosity level
267 optLevel :: Int, -- optimisation level
268 maxSimplIterations :: Int, -- max simplifier iterations
269 ruleCheck :: Maybe String,
271 specThreshold :: Int, -- Threshold for function specialisation
273 stolen_x86_regs :: Int,
274 cmdlineHcIncludes :: [String], -- -#includes
275 importPaths :: [FilePath],
277 mainFunIs :: Maybe String,
278 ctxtStkDepth :: Int, -- Typechecker context stack depth
280 thisPackage :: PackageId,
283 wayNames :: [WayName], -- way flags from the cmd line
284 buildTag :: String, -- the global "way" (eg. "p" for prof)
285 rtsBuildTag :: String, -- the RTS "way"
288 objectDir :: Maybe String,
289 hiDir :: Maybe String,
290 stubDir :: Maybe String,
296 outputFile :: Maybe String,
297 outputHi :: Maybe String,
299 includePaths :: [String],
300 libraryPaths :: [String],
301 frameworkPaths :: [String], -- used on darwin only
302 cmdlineFrameworks :: [String], -- ditto
303 tmpDir :: String, -- no trailing '/'
305 ghcUsagePath :: FilePath, -- Filled in by SysTools
306 ghciUsagePath :: FilePath, -- ditto
308 hpcDir :: String, -- ^ path to store the .mix files
310 -- options for particular phases
321 -- commands for particular phases
323 pgm_P :: (String,[Option]),
325 pgm_c :: (String,[Option]),
326 pgm_m :: (String,[Option]),
327 pgm_s :: (String,[Option]),
328 pgm_a :: (String,[Option]),
329 pgm_l :: (String,[Option]),
330 pgm_dll :: (String,[Option]),
332 pgm_sysman :: String,
335 extraPkgConfs :: [FilePath],
336 topDir :: FilePath, -- filled in by SysTools
337 systemPackageConfig :: FilePath, -- ditto
338 -- The -package-conf flags given on the command line, in the order
341 packageFlags :: [PackageFlag],
342 -- The -package and -hide-package flags from the command-line
345 -- NB. do not modify this field, it is calculated by
346 -- Packages.initPackages and Packages.updatePackages.
347 pkgDatabase :: Maybe (UniqFM InstalledPackageInfo),
348 pkgState :: PackageState,
354 log_action :: Severity -> SrcSpan -> PprStyle -> Message -> IO ()
365 -- | will this target result in an object file on the disk?
366 isObjectTarget :: HscTarget -> Bool
367 isObjectTarget HscC = True
368 isObjectTarget HscAsm = True
369 isObjectTarget _ = False
371 -- | The 'GhcMode' tells us whether we're doing multi-module
372 -- compilation (controlled via the "GHC" API) or one-shot
373 -- (single-module) compilation. This makes a difference primarily to
374 -- the "Finder": in one-shot mode we look for interface files for
375 -- imported modules, but in multi-module mode we look for source files
376 -- in order to check whether they need to be recompiled.
378 = CompManager -- ^ --make, GHCi, etc.
379 | OneShot -- ^ ghc -c Foo.hs
380 | MkDepend -- ^ ghc -M, see Finder for why we need this
383 isOneShot :: GhcMode -> Bool
384 isOneShot OneShot = True
385 isOneShot _other = False
387 -- | What kind of linking to do.
388 data GhcLink -- What to do in the link step, if there is one
389 = NoLink -- Don't link at all
390 | LinkBinary -- Link object code into a binary
391 | LinkInMemory -- Use the in-memory dynamic linker
392 | LinkDynLib -- Link objects into a dynamic lib (DLL on Windows, DSO on ELF platforms)
395 isNoLink :: GhcLink -> Bool
396 isNoLink NoLink = True
397 isNoLink other = False
400 = ExposePackage String
402 | IgnorePackage String
405 defaultHscTarget = defaultObjectTarget
407 -- | the 'HscTarget' value corresponding to the default way to create
408 -- object files on the current platform.
410 | cGhcWithNativeCodeGen == "YES" = HscAsm
413 initDynFlags dflags = do
414 -- someday these will be dynamic flags
415 ways <- readIORef v_Ways
416 build_tag <- readIORef v_Build_tag
417 rts_build_tag <- readIORef v_RTS_Build_tag
420 buildTag = build_tag,
421 rtsBuildTag = rts_build_tag
426 ghcMode = CompManager,
427 ghcLink = LinkBinary,
430 hscTarget = defaultHscTarget,
435 maxSimplIterations = 4,
439 cmdlineHcIncludes = [],
443 ctxtStkDepth = mAX_CONTEXT_REDUCTION_DEPTH,
445 thisPackage = mainPackageId,
451 objectSuf = phaseInputExt StopLn,
452 hcSuf = phaseInputExt HCc,
455 outputFile = Nothing,
460 cmdlineFrameworks = [],
461 tmpDir = cDEFAULT_TMPDIR,
477 pkgDatabase = Nothing,
478 pkgState = panic "no package state yet: call GHC.setSessionDynFlags",
480 Opt_ReadUserPackageConf,
482 Opt_MonoPatBinds, -- Experimentally, I'm making this non-standard
483 -- behaviour the default, to see if anyone notices
487 Opt_MonomorphismRestriction,
492 Opt_PrintBindResult ]
493 ++ [f | (ns,f) <- optLevelFlags, 0 `elem` ns]
494 -- The default -O0 options
497 log_action = \severity srcSpan style msg ->
499 SevInfo -> hPutStrLn stderr (show (msg style))
500 SevFatal -> hPutStrLn stderr (show (msg style))
501 _ -> hPutStrLn stderr ('\n':show ((mkLocMessage srcSpan msg) style))
507 0 | print errors & warnings only
508 1 | minimal verbosity: print "compiling M ... done." for each module.
509 2 | equivalent to -dshow-passes
510 3 | equivalent to existing "ghc -v"
511 4 | "ghc -v -ddump-most"
512 5 | "ghc -v -ddump-all"
515 dopt :: DynFlag -> DynFlags -> Bool
516 dopt f dflags = f `elem` (flags dflags)
518 dopt_set :: DynFlags -> DynFlag -> DynFlags
519 dopt_set dfs f = dfs{ flags = f : flags dfs }
521 dopt_unset :: DynFlags -> DynFlag -> DynFlags
522 dopt_unset dfs f = dfs{ flags = filter (/= f) (flags dfs) }
524 getOpts :: DynFlags -> (DynFlags -> [a]) -> [a]
525 getOpts dflags opts = reverse (opts dflags)
526 -- We add to the options from the front, so we need to reverse the list
528 getVerbFlag :: DynFlags -> String
530 | verbosity dflags >= 3 = "-v"
533 setObjectDir f d = d{ objectDir = f}
534 setHiDir f d = d{ hiDir = f}
535 setStubDir f d = d{ stubDir = f}
537 setObjectSuf f d = d{ objectSuf = f}
538 setHiSuf f d = d{ hiSuf = f}
539 setHcSuf f d = d{ hcSuf = f}
541 setOutputFile f d = d{ outputFile = f}
542 setOutputHi f d = d{ outputHi = f}
544 -- XXX HACK: Prelude> words "'does not' work" ===> ["'does","not'","work"]
545 -- Config.hs should really use Option.
546 setPgmP f d = let (pgm:args) = words f in d{ pgm_P = (pgm, map Option args)}
548 setPgmL f d = d{ pgm_L = f}
549 setPgmF f d = d{ pgm_F = f}
550 setPgmc f d = d{ pgm_c = (f,[])}
551 setPgmm f d = d{ pgm_m = (f,[])}
552 setPgms f d = d{ pgm_s = (f,[])}
553 setPgma f d = d{ pgm_a = (f,[])}
554 setPgml f d = d{ pgm_l = (f,[])}
555 setPgmdll f d = d{ pgm_dll = (f,[])}
557 addOptL f d = d{ opt_L = f : opt_L d}
558 addOptP f d = d{ opt_P = f : opt_P d}
559 addOptF f d = d{ opt_F = f : opt_F d}
560 addOptc f d = d{ opt_c = f : opt_c d}
561 addOptm f d = d{ opt_m = f : opt_m d}
562 addOpta f d = d{ opt_a = f : opt_a d}
563 addOptl f d = d{ opt_l = f : opt_l d}
564 addOptdll f d = d{ opt_dll = f : opt_dll d}
565 addOptdep f d = d{ opt_dep = f : opt_dep d}
567 addCmdlineFramework f d = d{ cmdlineFrameworks = f : cmdlineFrameworks d}
569 -- -----------------------------------------------------------------------------
570 -- Command-line options
572 -- When invoking external tools as part of the compilation pipeline, we
573 -- pass these a sequence of options on the command-line. Rather than
574 -- just using a list of Strings, we use a type that allows us to distinguish
575 -- between filepaths and 'other stuff'. [The reason being, of course, that
576 -- this type gives us a handle on transforming filenames, and filenames only,
577 -- to whatever format they're expected to be on a particular platform.]
580 = FileOption -- an entry that _contains_ filename(s) / filepaths.
581 String -- a non-filepath prefix that shouldn't be
582 -- transformed (e.g., "/out=")
583 String -- the filepath/filename portion
586 -----------------------------------------------------------------------------
587 -- Setting the optimisation level
589 updOptLevel :: Int -> DynFlags -> DynFlags
590 -- Set dynflags appropriate to the optimisation level
592 = dfs2{ optLevel = final_n }
594 final_n = max 0 (min 2 n) -- Clamp to 0 <= n <= 2
595 dfs1 = foldr (flip dopt_unset) dfs remove_dopts
596 dfs2 = foldr (flip dopt_set) dfs1 extra_dopts
598 extra_dopts = [ f | (ns,f) <- optLevelFlags, final_n `elem` ns ]
599 remove_dopts = [ f | (ns,f) <- optLevelFlags, final_n `notElem` ns ]
601 optLevelFlags :: [([Int], DynFlag)]
603 = [ ([0], Opt_IgnoreInterfacePragmas)
604 , ([0], Opt_OmitInterfacePragmas)
606 , ([1,2], Opt_IgnoreAsserts)
607 , ([1,2], Opt_RewriteRules) -- Off for -O0; see Note [Scoping for Builtin rules]
609 , ([1,2], Opt_DoEtaReduction)
610 , ([1,2], Opt_CaseMerge)
611 , ([1,2], Opt_Strictness)
613 , ([1,2], Opt_FullLaziness)
615 , ([2], Opt_LiberateCase)
616 , ([2], Opt_SpecConstr)
618 , ([0,1,2], Opt_DoLambdaEtaExpansion)
619 -- This one is important for a tiresome reason:
620 -- we want to make sure that the bindings for data
621 -- constructors are eta-expanded. This is probably
622 -- a good thing anyway, but it seems fragile.
625 -- -----------------------------------------------------------------------------
626 -- Standard sets of warning options
629 = [ Opt_WarnDeprecations,
630 Opt_WarnOverlappingPatterns,
631 Opt_WarnMissingFields,
632 Opt_WarnMissingMethods,
633 Opt_WarnDuplicateExports
637 = standardWarnings ++
638 [ Opt_WarnUnusedBinds,
639 Opt_WarnUnusedMatches,
640 Opt_WarnUnusedImports,
641 Opt_WarnIncompletePatterns,
647 [ Opt_WarnTypeDefaults,
648 Opt_WarnNameShadowing,
654 -- -----------------------------------------------------------------------------
655 -- CoreToDo: abstraction of core-to-core passes to run.
657 data CoreToDo -- These are diff core-to-core passes,
658 -- which may be invoked in any order,
659 -- as many times as you like.
661 = CoreDoSimplify -- The core-to-core simplifier.
664 -- Each run of the simplifier can take a different
665 -- set of simplifier-specific flags.
667 | CoreDoFloatOutwards FloatOutSwitches
672 | CoreDoWorkerWrapper
675 | CoreDoOldStrictness
678 | CoreDoRuleCheck Int{-CompilerPhase-} String -- Check for non-application of rules
679 -- matching this string
680 | CoreDoNothing -- Useful when building up
681 | CoreDoPasses [CoreToDo] -- lists of these things
683 data SimplifierMode -- See comments in SimplMonad
687 data SimplifierSwitch
688 = MaxSimplifierIterations Int
691 data FloatOutSwitches
692 = FloatOutSw Bool -- True <=> float lambdas to top level
693 Bool -- True <=> float constants to top level,
694 -- even if they do not escape a lambda
697 -- The core-to-core pass ordering is derived from the DynFlags:
698 runWhen :: Bool -> CoreToDo -> CoreToDo
699 runWhen True do_this = do_this
700 runWhen False do_this = CoreDoNothing
702 getCoreToDo :: DynFlags -> [CoreToDo]
704 | Just todo <- coreToDo dflags = todo -- set explicitly by user
705 | otherwise = core_todo
707 opt_level = optLevel dflags
708 max_iter = maxSimplIterations dflags
709 strictness = dopt Opt_Strictness dflags
710 full_laziness = dopt Opt_FullLaziness dflags
711 cse = dopt Opt_CSE dflags
712 spec_constr = dopt Opt_SpecConstr dflags
713 liberate_case = dopt Opt_LiberateCase dflags
714 rule_check = ruleCheck dflags
717 if opt_level == 0 then
719 CoreDoSimplify (SimplPhase 0) [
720 MaxSimplifierIterations max_iter
723 else {- opt_level >= 1 -} [
725 -- initial simplify: mk specialiser happy: minimum effort please
726 CoreDoSimplify SimplGently [
728 -- Don't inline anything till full laziness has bitten
729 -- In particular, inlining wrappers inhibits floating
730 -- e.g. ...(case f x of ...)...
731 -- ==> ...(case (case x of I# x# -> fw x#) of ...)...
732 -- ==> ...(case x of I# x# -> case fw x# of ...)...
733 -- and now the redex (f x) isn't floatable any more
734 -- Similarly, don't apply any rules until after full
735 -- laziness. Notably, list fusion can prevent floating.
737 NoCaseOfCase, -- Don't do case-of-case transformations.
738 -- This makes full laziness work better
739 MaxSimplifierIterations max_iter
742 -- Specialisation is best done before full laziness
743 -- so that overloaded functions have all their dictionary lambdas manifest
746 runWhen full_laziness (CoreDoFloatOutwards (FloatOutSw False False)),
750 CoreDoSimplify (SimplPhase 2) [
751 -- Want to run with inline phase 2 after the specialiser to give
752 -- maximum chance for fusion to work before we inline build/augment
753 -- in phase 1. This made a difference in 'ansi' where an
754 -- overloaded function wasn't inlined till too late.
755 MaxSimplifierIterations max_iter
757 case rule_check of { Just pat -> CoreDoRuleCheck 2 pat; Nothing -> CoreDoNothing },
759 CoreDoSimplify (SimplPhase 1) [
760 -- Need inline-phase2 here so that build/augment get
761 -- inlined. I found that spectral/hartel/genfft lost some useful
762 -- strictness in the function sumcode' if augment is not inlined
763 -- before strictness analysis runs
764 MaxSimplifierIterations max_iter
766 case rule_check of { Just pat -> CoreDoRuleCheck 1 pat; Nothing -> CoreDoNothing },
768 CoreDoSimplify (SimplPhase 0) [
769 -- Phase 0: allow all Ids to be inlined now
770 -- This gets foldr inlined before strictness analysis
772 MaxSimplifierIterations 3
773 -- At least 3 iterations because otherwise we land up with
774 -- huge dead expressions because of an infelicity in the
776 -- let k = BIG in foldr k z xs
777 -- ==> let k = BIG in letrec go = \xs -> ...(k x).... in go xs
778 -- ==> let k = BIG in letrec go = \xs -> ...(BIG x).... in go xs
782 case rule_check of { Just pat -> CoreDoRuleCheck 0 pat; Nothing -> CoreDoNothing },
784 #ifdef OLD_STRICTNESS
787 runWhen strictness (CoreDoPasses [
791 CoreDoSimplify (SimplPhase 0) [
792 MaxSimplifierIterations max_iter
795 runWhen full_laziness
796 (CoreDoFloatOutwards (FloatOutSw False -- Not lambdas
797 True)), -- Float constants
798 -- nofib/spectral/hartel/wang doubles in speed if you
799 -- do full laziness late in the day. It only happens
800 -- after fusion and other stuff, so the early pass doesn't
801 -- catch it. For the record, the redex is
802 -- f_el22 (f_el21 r_midblock)
806 -- We want CSE to follow the final full-laziness pass, because it may
807 -- succeed in commoning up things floated out by full laziness.
808 -- CSE used to rely on the no-shadowing invariant, but it doesn't any more
812 case rule_check of { Just pat -> CoreDoRuleCheck 0 pat; Nothing -> CoreDoNothing },
814 -- Case-liberation for -O2. This should be after
815 -- strictness analysis and the simplification which follows it.
816 runWhen liberate_case (CoreDoPasses [
818 CoreDoSimplify (SimplPhase 0) [
819 MaxSimplifierIterations max_iter
820 ] ]), -- Run the simplifier after LiberateCase to vastly
821 -- reduce the possiblility of shadowing
822 -- Reason: see Note [Shadowing] in SpecConstr.lhs
824 runWhen spec_constr CoreDoSpecConstr,
826 -- Final clean-up simplification:
827 CoreDoSimplify (SimplPhase 0) [
828 MaxSimplifierIterations max_iter
832 -- -----------------------------------------------------------------------------
833 -- StgToDo: abstraction of stg-to-stg passes to run.
836 = StgDoMassageForProfiling -- should be (next to) last
837 -- There's also setStgVarInfo, but its absolute "lastness"
838 -- is so critical that it is hardwired in (no flag).
841 getStgToDo :: DynFlags -> [StgToDo]
843 | Just todo <- stgToDo dflags = todo -- set explicitly by user
846 stg_stats = dopt Opt_StgStats dflags
848 todo1 = if stg_stats then [D_stg_stats] else []
850 todo2 | WayProf `elem` wayNames dflags
851 = StgDoMassageForProfiling : todo1
855 -- -----------------------------------------------------------------------------
859 allFlags = map ('-':) $
860 [ name | (name, optkind) <- dynamic_flags, ok optkind ] ++
861 map ("fno-"++) flags ++
863 where ok (PrefixPred _ _) = False
865 flags = map fst fFlags
867 dynamic_flags :: [(String, OptKind DynP)]
869 ( "n" , NoArg (setDynFlag Opt_DryRun) )
870 , ( "cpp" , NoArg (setDynFlag Opt_Cpp))
871 , ( "F" , NoArg (setDynFlag Opt_Pp))
872 , ( "#include" , HasArg (addCmdlineHCInclude) )
873 , ( "v" , OptIntSuffix setVerbosity )
875 ------- Specific phases --------------------------------------------
876 , ( "pgmL" , HasArg (upd . setPgmL) )
877 , ( "pgmP" , HasArg (upd . setPgmP) )
878 , ( "pgmF" , HasArg (upd . setPgmF) )
879 , ( "pgmc" , HasArg (upd . setPgmc) )
880 , ( "pgmm" , HasArg (upd . setPgmm) )
881 , ( "pgms" , HasArg (upd . setPgms) )
882 , ( "pgma" , HasArg (upd . setPgma) )
883 , ( "pgml" , HasArg (upd . setPgml) )
884 , ( "pgmdll" , HasArg (upd . setPgmdll) )
886 , ( "optL" , HasArg (upd . addOptL) )
887 , ( "optP" , HasArg (upd . addOptP) )
888 , ( "optF" , HasArg (upd . addOptF) )
889 , ( "optc" , HasArg (upd . addOptc) )
890 , ( "optm" , HasArg (upd . addOptm) )
891 , ( "opta" , HasArg (upd . addOpta) )
892 , ( "optl" , HasArg (upd . addOptl) )
893 , ( "optdll" , HasArg (upd . addOptdll) )
894 , ( "optdep" , HasArg (upd . addOptdep) )
896 , ( "split-objs" , NoArg (if can_split
897 then setDynFlag Opt_SplitObjs
900 -------- Linking ----------------------------------------------------
901 , ( "c" , NoArg (upd $ \d -> d{ ghcLink=NoLink } ))
902 , ( "no-link" , NoArg (upd $ \d -> d{ ghcLink=NoLink } )) -- Dep.
903 , ( "shared" , NoArg (upd $ \d -> d{ ghcLink=LinkDynLib } ))
905 ------- Libraries ---------------------------------------------------
906 , ( "L" , Prefix addLibraryPath )
907 , ( "l" , AnySuffix (\s -> do upd (addOptl s)
910 ------- Frameworks --------------------------------------------------
911 -- -framework-path should really be -F ...
912 , ( "framework-path" , HasArg addFrameworkPath )
913 , ( "framework" , HasArg (upd . addCmdlineFramework) )
915 ------- Output Redirection ------------------------------------------
916 , ( "odir" , HasArg (upd . setObjectDir . Just))
917 , ( "o" , SepArg (upd . setOutputFile . Just))
918 , ( "ohi" , HasArg (upd . setOutputHi . Just ))
919 , ( "osuf" , HasArg (upd . setObjectSuf))
920 , ( "hcsuf" , HasArg (upd . setHcSuf))
921 , ( "hisuf" , HasArg (upd . setHiSuf))
922 , ( "hidir" , HasArg (upd . setHiDir . Just))
923 , ( "tmpdir" , HasArg (upd . setTmpDir))
924 , ( "stubdir" , HasArg (upd . setStubDir . Just))
926 ------- Keeping temporary files -------------------------------------
927 -- These can be singular (think ghc -c) or plural (think ghc --make)
928 , ( "keep-hc-file" , NoArg (setDynFlag Opt_KeepHcFiles))
929 , ( "keep-hc-files" , NoArg (setDynFlag Opt_KeepHcFiles))
930 , ( "keep-s-file" , NoArg (setDynFlag Opt_KeepSFiles))
931 , ( "keep-s-files" , NoArg (setDynFlag Opt_KeepSFiles))
932 , ( "keep-raw-s-file" , NoArg (setDynFlag Opt_KeepRawSFiles))
933 , ( "keep-raw-s-files", NoArg (setDynFlag Opt_KeepRawSFiles))
934 -- This only makes sense as plural
935 , ( "keep-tmp-files" , NoArg (setDynFlag Opt_KeepTmpFiles))
937 ------- Miscellaneous ----------------------------------------------
938 , ( "no-hs-main" , NoArg (setDynFlag Opt_NoHsMain))
939 , ( "main-is" , SepArg setMainIs )
940 , ( "haddock" , NoArg (setDynFlag Opt_Haddock) )
941 , ( "hpcdir" , SepArg setOptHpcDir )
943 ------- recompilation checker (DEPRECATED, use -fforce-recomp) -----
944 , ( "recomp" , NoArg (unSetDynFlag Opt_ForceRecomp) )
945 , ( "no-recomp" , NoArg (setDynFlag Opt_ForceRecomp) )
947 ------- Packages ----------------------------------------------------
948 , ( "package-conf" , HasArg extraPkgConf_ )
949 , ( "no-user-package-conf", NoArg (unSetDynFlag Opt_ReadUserPackageConf) )
950 , ( "package-name" , HasArg (upd . setPackageName) )
951 , ( "package" , HasArg exposePackage )
952 , ( "hide-package" , HasArg hidePackage )
953 , ( "hide-all-packages", NoArg (setDynFlag Opt_HideAllPackages) )
954 , ( "ignore-package" , HasArg ignorePackage )
955 , ( "syslib" , HasArg exposePackage ) -- for compatibility
957 ------ HsCpp opts ---------------------------------------------------
958 , ( "D", AnySuffix (upd . addOptP) )
959 , ( "U", AnySuffix (upd . addOptP) )
961 ------- Include/Import Paths ----------------------------------------
962 , ( "I" , Prefix addIncludePath)
963 , ( "i" , OptPrefix addImportPath )
965 ------ Debugging ----------------------------------------------------
966 , ( "dstg-stats", NoArg (setDynFlag Opt_StgStats))
968 , ( "ddump-cmm", setDumpFlag Opt_D_dump_cmm)
969 , ( "ddump-cps-cmm", setDumpFlag Opt_D_dump_cps_cmm)
970 , ( "ddump-asm", setDumpFlag Opt_D_dump_asm)
971 , ( "ddump-cpranal", setDumpFlag Opt_D_dump_cpranal)
972 , ( "ddump-deriv", setDumpFlag Opt_D_dump_deriv)
973 , ( "ddump-ds", setDumpFlag Opt_D_dump_ds)
974 , ( "ddump-flatC", setDumpFlag Opt_D_dump_flatC)
975 , ( "ddump-foreign", setDumpFlag Opt_D_dump_foreign)
976 , ( "ddump-inlinings", setDumpFlag Opt_D_dump_inlinings)
977 , ( "ddump-rule-firings", setDumpFlag Opt_D_dump_rule_firings)
978 , ( "ddump-occur-anal", setDumpFlag Opt_D_dump_occur_anal)
979 , ( "ddump-parsed", setDumpFlag Opt_D_dump_parsed)
980 , ( "ddump-rn", setDumpFlag Opt_D_dump_rn)
981 , ( "ddump-simpl", setDumpFlag Opt_D_dump_simpl)
982 , ( "ddump-simpl-iterations", setDumpFlag Opt_D_dump_simpl_iterations)
983 , ( "ddump-spec", setDumpFlag Opt_D_dump_spec)
984 , ( "ddump-prep", setDumpFlag Opt_D_dump_prep)
985 , ( "ddump-stg", setDumpFlag Opt_D_dump_stg)
986 , ( "ddump-stranal", setDumpFlag Opt_D_dump_stranal)
987 , ( "ddump-tc", setDumpFlag Opt_D_dump_tc)
988 , ( "ddump-types", setDumpFlag Opt_D_dump_types)
989 , ( "ddump-rules", setDumpFlag Opt_D_dump_rules)
990 , ( "ddump-cse", setDumpFlag Opt_D_dump_cse)
991 , ( "ddump-worker-wrapper", setDumpFlag Opt_D_dump_worker_wrapper)
992 , ( "ddump-rn-trace", setDumpFlag Opt_D_dump_rn_trace)
993 , ( "ddump-if-trace", setDumpFlag Opt_D_dump_if_trace)
994 , ( "ddump-tc-trace", setDumpFlag Opt_D_dump_tc_trace)
995 , ( "ddump-splices", setDumpFlag Opt_D_dump_splices)
996 , ( "ddump-rn-stats", setDumpFlag Opt_D_dump_rn_stats)
997 , ( "ddump-opt-cmm", setDumpFlag Opt_D_dump_opt_cmm)
998 , ( "ddump-simpl-stats", setDumpFlag Opt_D_dump_simpl_stats)
999 , ( "ddump-bcos", setDumpFlag Opt_D_dump_BCOs)
1000 , ( "dsource-stats", setDumpFlag Opt_D_source_stats)
1001 , ( "dverbose-core2core", setDumpFlag Opt_D_verbose_core2core)
1002 , ( "dverbose-stg2stg", setDumpFlag Opt_D_verbose_stg2stg)
1003 , ( "ddump-hi", setDumpFlag Opt_D_dump_hi)
1004 , ( "ddump-minimal-imports", setDumpFlag Opt_D_dump_minimal_imports)
1005 , ( "ddump-vect", setDumpFlag Opt_D_dump_vect)
1006 , ( "ddump-hpc", setDumpFlag Opt_D_dump_hpc)
1007 , ( "ddump-mod-cycles", setDumpFlag Opt_D_dump_mod_cycles)
1009 , ( "ddump-hi-diffs", NoArg (setDynFlag Opt_D_dump_hi_diffs))
1010 , ( "dcore-lint", NoArg (setDynFlag Opt_DoCoreLinting))
1011 , ( "dstg-lint", NoArg (setDynFlag Opt_DoStgLinting))
1012 , ( "dcmm-lint", NoArg (setDynFlag Opt_DoCmmLinting))
1013 , ( "dshow-passes", NoArg (do setDynFlag Opt_ForceRecomp
1014 setVerbosity (Just 2)) )
1015 , ( "dfaststring-stats", NoArg (setDynFlag Opt_D_faststring_stats))
1017 ------ Machine dependant (-m<blah>) stuff ---------------------------
1019 , ( "monly-2-regs", NoArg (upd (\s -> s{stolen_x86_regs = 2}) ))
1020 , ( "monly-3-regs", NoArg (upd (\s -> s{stolen_x86_regs = 3}) ))
1021 , ( "monly-4-regs", NoArg (upd (\s -> s{stolen_x86_regs = 4}) ))
1023 ------ Warning opts -------------------------------------------------
1024 , ( "W" , NoArg (mapM_ setDynFlag minusWOpts) )
1025 , ( "Werror" , NoArg (setDynFlag Opt_WarnIsError) )
1026 , ( "Wall" , NoArg (mapM_ setDynFlag minusWallOpts) )
1027 , ( "Wnot" , NoArg (mapM_ unSetDynFlag minusWallOpts) ) /* DEPREC */
1028 , ( "w" , NoArg (mapM_ unSetDynFlag minusWallOpts) )
1030 ------ Optimisation flags ------------------------------------------
1031 , ( "O" , NoArg (upd (setOptLevel 1)))
1032 , ( "Onot" , NoArg (upd (setOptLevel 0)))
1033 , ( "O" , OptIntSuffix (\mb_n -> upd (setOptLevel (mb_n `orElse` 1))))
1034 -- If the number is missing, use 1
1036 , ( "fmax-simplifier-iterations", IntSuffix (\n ->
1037 upd (\dfs -> dfs{ maxSimplIterations = n })) )
1039 -- liberate-case-threshold is an old flag for '-fspec-threshold'
1040 , ( "fspec-threshold", IntSuffix (\n -> upd (\dfs -> dfs{ specThreshold = n })))
1041 , ( "fliberate-case-threshold", IntSuffix (\n -> upd (\dfs -> dfs{ specThreshold = n })))
1043 , ( "frule-check", SepArg (\s -> upd (\dfs -> dfs{ ruleCheck = Just s })))
1044 , ( "fcontext-stack" , IntSuffix $ \n -> upd $ \dfs -> dfs{ ctxtStkDepth = n })
1046 ------ Compiler flags -----------------------------------------------
1048 , ( "fasm", NoArg (setObjTarget HscAsm) )
1049 , ( "fvia-c", NoArg (setObjTarget HscC) )
1050 , ( "fvia-C", NoArg (setObjTarget HscC) )
1052 , ( "fno-code", NoArg (setTarget HscNothing))
1053 , ( "fbyte-code", NoArg (setTarget HscInterpreted) )
1054 , ( "fobject-code", NoArg (setTarget defaultHscTarget) )
1056 , ( "fglasgow-exts", NoArg (mapM_ setDynFlag glasgowExtsFlags) )
1057 , ( "fno-glasgow-exts", NoArg (mapM_ unSetDynFlag glasgowExtsFlags) )
1059 -- the rest of the -f* and -fno-* flags
1060 , ( "f", PrefixPred (isFlag fFlags) (\f -> setDynFlag (getFlag fFlags f)) )
1061 , ( "f", PrefixPred (isNoFlag fFlags) (\f -> unSetDynFlag (getNoFlag fFlags f)) )
1063 -- For now, allow -X flags with -f; ToDo: report this as deprecated
1064 , ( "f", PrefixPred (isFlag xFlags) (\f -> setDynFlag (getFlag xFlags f)) )
1065 , ( "f", PrefixPred (isNoFlag xFlags) (\f -> unSetDynFlag (getNoFlag xFlags f)) )
1067 -- the rest of the -X* and -Xno-* flags
1068 , ( "X", PrefixPred (isFlag xFlags) (\f -> setDynFlag (getFlag xFlags f)) )
1069 , ( "X", PrefixPred (isNoFlag xFlags) (\f -> unSetDynFlag (getNoFlag xFlags f)) )
1072 -- these -f<blah> flags can all be reversed with -fno-<blah>
1075 ( "warn-duplicate-exports", Opt_WarnDuplicateExports ),
1076 ( "warn-hi-shadowing", Opt_WarnHiShadows ),
1077 ( "warn-implicit-prelude", Opt_WarnImplicitPrelude ),
1078 ( "warn-incomplete-patterns", Opt_WarnIncompletePatterns ),
1079 ( "warn-incomplete-record-updates", Opt_WarnIncompletePatternsRecUpd ),
1080 ( "warn-missing-fields", Opt_WarnMissingFields ),
1081 ( "warn-missing-methods", Opt_WarnMissingMethods ),
1082 ( "warn-missing-signatures", Opt_WarnMissingSigs ),
1083 ( "warn-name-shadowing", Opt_WarnNameShadowing ),
1084 ( "warn-overlapping-patterns", Opt_WarnOverlappingPatterns ),
1085 ( "warn-simple-patterns", Opt_WarnSimplePatterns ),
1086 ( "warn-type-defaults", Opt_WarnTypeDefaults ),
1087 ( "warn-monomorphism-restriction", Opt_WarnMonomorphism ),
1088 ( "warn-unused-binds", Opt_WarnUnusedBinds ),
1089 ( "warn-unused-imports", Opt_WarnUnusedImports ),
1090 ( "warn-unused-matches", Opt_WarnUnusedMatches ),
1091 ( "warn-deprecations", Opt_WarnDeprecations ),
1092 ( "warn-orphans", Opt_WarnOrphans ),
1093 ( "warn-tabs", Opt_WarnTabs ),
1094 ( "print-explicit-foralls", Opt_PrintExplicitForalls ),
1095 ( "strictness", Opt_Strictness ),
1096 ( "full-laziness", Opt_FullLaziness ),
1097 ( "liberate-case", Opt_LiberateCase ),
1098 ( "spec-constr", Opt_SpecConstr ),
1100 ( "ignore-interface-pragmas", Opt_IgnoreInterfacePragmas ),
1101 ( "omit-interface-pragmas", Opt_OmitInterfacePragmas ),
1102 ( "do-lambda-eta-expansion", Opt_DoLambdaEtaExpansion ),
1103 ( "ignore-asserts", Opt_IgnoreAsserts ),
1104 ( "ignore-breakpoints", Opt_IgnoreBreakpoints),
1105 ( "do-eta-reduction", Opt_DoEtaReduction ),
1106 ( "case-merge", Opt_CaseMerge ),
1107 ( "unbox-strict-fields", Opt_UnboxStrictFields ),
1108 ( "dicts-cheap", Opt_DictsCheap ),
1109 ( "excess-precision", Opt_ExcessPrecision ),
1110 ( "asm-mangling", Opt_DoAsmMangling ),
1111 ( "print-bind-result", Opt_PrintBindResult ),
1112 ( "force-recomp", Opt_ForceRecomp ),
1113 ( "hpc-no-auto", Opt_Hpc_No_Auto ),
1114 ( "rewrite-rules", Opt_RewriteRules ),
1115 ( "break-on-exception", Opt_BreakOnException ),
1116 ( "vectorise", Opt_Vectorise )
1120 -- These -X<blah> flags can all be reversed with -Xno-<blah>
1121 xFlags :: [(String, DynFlag)]
1124 ( "PatternGuards", Opt_PatternGuards ),
1125 ( "UnicodeSyntax", Opt_UnicodeSyntax ),
1126 ( "MagicHash", Opt_MagicHash ),
1127 ( "PolymorphicComponents", Opt_PolymorphicComponents ),
1128 ( "ExistentialQuantification", Opt_ExistentialQuantification ),
1129 ( "KindSignatures", Opt_KindSignatures ),
1130 ( "PatternSignatures", Opt_PatternSignatures ),
1131 ( "EmptyDataDecls", Opt_EmptyDataDecls ),
1132 ( "ParallelListComp", Opt_ParallelListComp ),
1133 ( "FI", Opt_FFI ), -- support `-ffi'...
1134 ( "FFI", Opt_FFI ), -- ...and also `-fffi'
1135 ( "ForeignFunctionInterface", Opt_FFI ),
1136 ( "UnliftedFFITypes", Opt_UnliftedFFITypes ),
1138 ( "PartiallyAppliedClosedTypeSynonyms", Opt_PartiallyAppliedClosedTypeSynonyms ),
1139 ( "Rank2Types", Opt_Rank2Types ),
1140 ( "RankNTypes", Opt_RankNTypes ),
1141 ( "TypeOperators", Opt_TypeOperators ),
1142 ( "RecursiveDo", Opt_RecursiveDo ),
1143 ( "Arrows", Opt_Arrows ), -- arrow syntax
1144 ( "Parr", Opt_PArr ),
1146 ( "TH", Opt_TH ), -- support -fth
1147 ( "TemplateHaskelll", Opt_TH ),
1149 ( "Generics", Opt_Generics ),
1151 ( "ImplicitPrelude", Opt_ImplicitPrelude ), -- On by default
1153 ( "RecordWildCards", Opt_RecordWildCards ),
1154 ( "RecordPuns", Opt_RecordPuns ),
1155 ( "DisambiguateRecordFields", Opt_DisambiguateRecordFields ),
1157 ( "OverloadedStrings", Opt_OverloadedStrings ),
1158 ( "GADTs", Opt_GADTs ),
1159 ( "TypeFamilies", Opt_TypeFamilies ),
1160 ( "BangPatterns", Opt_BangPatterns ),
1161 ( "MonomorphismRestriction", Opt_MonomorphismRestriction ), -- On by default
1162 ( "MonoPatBinds", Opt_MonoPatBinds ), -- On by default (which is not strictly H98)
1163 ( "RelaxedPolyRec", Opt_RelaxedPolyRec),
1164 ( "ExtendedDefaultRules", Opt_ExtendedDefaultRules ),
1165 ( "ImplicitParams", Opt_ImplicitParams ),
1166 ( "ScopedTypeVariables", Opt_ScopedTypeVariables ),
1167 ( "UnboxedTuples", Opt_UnboxedTuples ),
1168 ( "ExpressionSignaturesUnboxedTuples", Opt_ExpressionSignaturesUnboxedTuples ),
1169 ( "TypeSynonymUnboxedTuples", Opt_TypeSynonymUnboxedTuples ),
1170 ( "TypeSynonymInstances", Opt_TypeSynonymInstances ),
1171 ( "FlexibleContexts", Opt_FlexibleContexts ),
1172 ( "FlexibleInstances", Opt_FlexibleInstances ),
1173 ( "ConstrainedClassMethods", Opt_ConstrainedClassMethods ),
1174 ( "MultiParamTypeClasses", Opt_MultiParamTypeClasses ),
1175 ( "FunctionalDependencies", Opt_FunctionalDependencies ),
1176 ( "GeneralizedNewtypeDeriving", Opt_GeneralizedNewtypeDeriving ),
1177 ( "AllowOverlappingInstances", Opt_AllowOverlappingInstances ),
1178 ( "AllowUndecidableInstances", Opt_AllowUndecidableInstances ),
1179 ( "AllowIncoherentInstances", Opt_AllowIncoherentInstances )
1182 impliedFlags :: [(DynFlag, [DynFlag])]
1184 ( Opt_GADTs, [Opt_RelaxedPolyRec] ) -- We want type-sig variables to be completely rigid for GADTs
1187 glasgowExtsFlags = [ Opt_GlasgowExts
1188 , Opt_PrintExplicitForalls
1190 , Opt_UnliftedFFITypes
1192 , Opt_ImplicitParams
1193 , Opt_ScopedTypeVariables
1195 , Opt_ExpressionSignaturesUnboxedTuples
1196 , Opt_TypeSynonymUnboxedTuples
1197 , Opt_TypeSynonymInstances
1198 , Opt_FlexibleContexts
1199 , Opt_FlexibleInstances
1200 , Opt_ConstrainedClassMethods
1201 , Opt_MultiParamTypeClasses
1202 , Opt_FunctionalDependencies
1204 , Opt_PolymorphicComponents
1205 , Opt_ExistentialQuantification
1208 , Opt_PartiallyAppliedClosedTypeSynonyms
1212 , Opt_ParallelListComp
1213 , Opt_EmptyDataDecls
1214 , Opt_KindSignatures
1215 , Opt_PatternSignatures
1216 , Opt_GeneralizedNewtypeDeriving
1217 , Opt_TypeFamilies ]
1220 isNoFlag, isFlag :: [(String,a)] -> String -> Bool
1222 isFlag flags f = is_flag flags (normaliseFlag f)
1225 | Just f <- noFlag_maybe (normaliseFlag no_f) = is_flag flags f
1228 is_flag flags nf = any (\(ff,_) -> normaliseFlag ff == nf) flags
1229 -- nf is normalised alreadly
1232 getFlag, getNoFlag :: [(String,a)] -> String -> a
1234 getFlag flags f = get_flag flags (normaliseFlag f)
1236 getNoFlag flags f = get_flag flags (fromJust (noFlag_maybe (normaliseFlag f)))
1237 -- The flag should be a no-flag already
1239 get_flag flags nf = case [ opt | (ff, opt) <- flags, normaliseFlag ff == nf] of
1241 [] -> panic ("get_flag " ++ nf)
1244 noFlag_maybe :: String -> Maybe String
1245 -- The input is normalised already
1246 noFlag_maybe ('n' : 'o' : f) = Just f
1247 noFlag_maybe other = Nothing
1249 normaliseFlag :: String -> String
1250 -- Normalise a option flag by
1251 -- * map to lower case
1252 -- * removing hyphens
1253 -- Thus: -X=overloaded-strings or -XOverloadedStrings
1254 normaliseFlag [] = []
1255 normaliseFlag ('-':s) = normaliseFlag s
1256 normaliseFlag (c:s) = toLower c : normaliseFlag s
1258 -- -----------------------------------------------------------------------------
1259 -- Parsing the dynamic flags.
1261 parseDynamicFlags :: DynFlags -> [String] -> IO (DynFlags,[String])
1262 parseDynamicFlags dflags args = do
1263 let ((leftover,errs),dflags')
1264 = runCmdLine (processArgs dynamic_flags args) dflags
1265 when (not (null errs)) $ do
1266 throwDyn (UsageError (unlines errs))
1267 return (dflags', leftover)
1270 type DynP = CmdLineP DynFlags
1272 upd :: (DynFlags -> DynFlags) -> DynP ()
1274 dfs <- getCmdLineState
1275 putCmdLineState $! (f dfs)
1277 --------------------------
1278 setDynFlag, unSetDynFlag :: DynFlag -> DynP ()
1279 setDynFlag f = upd (\dfs -> foldl dopt_set (dopt_set dfs f) deps)
1281 deps = [ d | (f', ds) <- impliedFlags, f' == f, d <- ds ]
1282 -- When you set f, set the ones it implies
1283 -- When you un-set f, however, we don't un-set the things it implies
1284 -- (except for -fno-glasgow-exts, which is treated specially)
1286 unSetDynFlag f = upd (\dfs -> dopt_unset dfs f)
1288 --------------------------
1289 setDumpFlag :: DynFlag -> OptKind DynP
1290 setDumpFlag dump_flag
1291 = NoArg (setDynFlag Opt_ForceRecomp >> setDynFlag dump_flag)
1292 -- Whenver we -ddump, switch off the recompilation checker,
1293 -- else you don't see the dump!
1295 setVerbosity :: Maybe Int -> DynP ()
1296 setVerbosity mb_n = upd (\dfs -> dfs{ verbosity = mb_n `orElse` 3 })
1298 addCmdlineHCInclude a = upd (\s -> s{cmdlineHcIncludes = a : cmdlineHcIncludes s})
1300 extraPkgConf_ p = upd (\s -> s{ extraPkgConfs = p : extraPkgConfs s })
1303 upd (\s -> s{ packageFlags = ExposePackage p : packageFlags s })
1305 upd (\s -> s{ packageFlags = HidePackage p : packageFlags s })
1307 upd (\s -> s{ packageFlags = IgnorePackage p : packageFlags s })
1310 | Nothing <- unpackPackageId pid
1311 = throwDyn (CmdLineError ("cannot parse \'" ++ p ++ "\' as a package identifier"))
1313 = \s -> s{ thisPackage = pid }
1315 pid = stringToPackageId p
1317 -- If we're linking a binary, then only targets that produce object
1318 -- code are allowed (requests for other target types are ignored).
1319 setTarget l = upd set
1322 | ghcLink dfs /= LinkBinary || isObjectTarget l = dfs{ hscTarget = l }
1325 -- Changes the target only if we're compiling object code. This is
1326 -- used by -fasm and -fvia-C, which switch from one to the other, but
1327 -- not from bytecode to object-code. The idea is that -fasm/-fvia-C
1328 -- can be safely used in an OPTIONS_GHC pragma.
1329 setObjTarget l = upd set
1332 | isObjectTarget (hscTarget dfs) = dfs { hscTarget = l }
1335 setOptLevel :: Int -> DynFlags -> DynFlags
1336 setOptLevel n dflags
1337 | hscTarget dflags == HscInterpreted && n > 0
1339 -- not in IO any more, oh well:
1340 -- putStr "warning: -O conflicts with --interactive; -O ignored.\n"
1342 = updOptLevel n dflags
1345 setMainIs :: String -> DynP ()
1347 | not (null main_fn) -- The arg looked like "Foo.baz"
1348 = upd $ \d -> d{ mainFunIs = Just main_fn,
1349 mainModIs = mkModule mainPackageId (mkModuleName main_mod) }
1351 | isUpper (head main_mod) -- The arg looked like "Foo"
1352 = upd $ \d -> d{ mainModIs = mkModule mainPackageId (mkModuleName main_mod) }
1354 | otherwise -- The arg looked like "baz"
1355 = upd $ \d -> d{ mainFunIs = Just main_mod }
1357 (main_mod, main_fn) = splitLongestPrefix arg (== '.')
1359 -----------------------------------------------------------------------------
1360 -- Paths & Libraries
1362 -- -i on its own deletes the import paths
1363 addImportPath "" = upd (\s -> s{importPaths = []})
1364 addImportPath p = upd (\s -> s{importPaths = importPaths s ++ splitPathList p})
1368 upd (\s -> s{libraryPaths = libraryPaths s ++ splitPathList p})
1371 upd (\s -> s{includePaths = includePaths s ++ splitPathList p})
1373 addFrameworkPath p =
1374 upd (\s -> s{frameworkPaths = frameworkPaths s ++ splitPathList p})
1376 split_marker = ':' -- not configurable (ToDo)
1378 splitPathList :: String -> [String]
1379 splitPathList s = filter notNull (splitUp s)
1380 -- empty paths are ignored: there might be a trailing
1381 -- ':' in the initial list, for example. Empty paths can
1382 -- cause confusion when they are translated into -I options
1383 -- for passing to gcc.
1385 #ifndef mingw32_TARGET_OS
1386 splitUp xs = split split_marker xs
1388 -- Windows: 'hybrid' support for DOS-style paths in directory lists.
1390 -- That is, if "foo:bar:baz" is used, this interpreted as
1391 -- consisting of three entries, 'foo', 'bar', 'baz'.
1392 -- However, with "c:/foo:c:\\foo;x:/bar", this is interpreted
1393 -- as 3 elts, "c:/foo", "c:\\foo", "x:/bar"
1395 -- Notice that no attempt is made to fully replace the 'standard'
1396 -- split marker ':' with the Windows / DOS one, ';'. The reason being
1397 -- that this will cause too much breakage for users & ':' will
1398 -- work fine even with DOS paths, if you're not insisting on being silly.
1401 splitUp (x:':':div:xs) | div `elem` dir_markers
1402 = ((x:':':div:p): splitUp rs)
1404 (p,rs) = findNextPath xs
1405 -- we used to check for existence of the path here, but that
1406 -- required the IO monad to be threaded through the command-line
1407 -- parser which is quite inconvenient. The
1408 splitUp xs = cons p (splitUp rs)
1410 (p,rs) = findNextPath xs
1415 -- will be called either when we've consumed nought or the
1416 -- "<Drive>:/" part of a DOS path, so splitting is just a Q of
1417 -- finding the next split marker.
1419 case break (`elem` split_markers) xs of
1420 (p, d:ds) -> (p, ds)
1423 split_markers :: [Char]
1424 split_markers = [':', ';']
1426 dir_markers :: [Char]
1427 dir_markers = ['/', '\\']
1430 -- -----------------------------------------------------------------------------
1431 -- tmpDir, where we store temporary files.
1433 setTmpDir :: FilePath -> DynFlags -> DynFlags
1434 setTmpDir dir dflags = dflags{ tmpDir = canonicalise dir }
1436 #if !defined(mingw32_HOST_OS)
1437 canonicalise p = normalisePath p
1439 -- Canonicalisation of temp path under win32 is a bit more
1440 -- involved: (a) strip trailing slash,
1441 -- (b) normalise slashes
1442 -- (c) just in case, if there is a prefix /cygdrive/x/, change to x:
1444 canonicalise path = normalisePath (xltCygdrive (removeTrailingSlash path))
1446 -- if we're operating under cygwin, and TMP/TEMP is of
1447 -- the form "/cygdrive/drive/path", translate this to
1448 -- "drive:/path" (as GHC isn't a cygwin app and doesn't
1449 -- understand /cygdrive paths.)
1451 | "/cygdrive/" `isPrefixOf` path =
1452 case drop (length "/cygdrive/") path of
1453 drive:xs@('/':_) -> drive:':':xs
1457 -- strip the trailing backslash (awful, but we only do this once).
1458 removeTrailingSlash path =
1465 -----------------------------------------------------------------------------
1468 setOptHpcDir :: String -> DynP ()
1469 setOptHpcDir arg = upd $ \ d -> d{hpcDir = arg}
1471 -----------------------------------------------------------------------------
1472 -- Via-C compilation stuff
1474 machdepCCOpts :: DynFlags -> ([String], -- flags for all C compilations
1475 [String]) -- for registerised HC compilations
1476 machdepCCOpts dflags
1477 #if alpha_TARGET_ARCH
1479 #ifdef HAVE_THREADED_RTS_SUPPORT
1483 -- For now, to suppress the gcc warning "call-clobbered
1484 -- register used for global register variable", we simply
1485 -- disable all warnings altogether using the -w flag. Oh well.
1487 #elif hppa_TARGET_ARCH
1488 -- ___HPUX_SOURCE, not _HPUX_SOURCE, is #defined if -ansi!
1489 -- (very nice, but too bad the HP /usr/include files don't agree.)
1490 = ( ["-D_HPUX_SOURCE"], [] )
1492 #elif m68k_TARGET_ARCH
1493 -- -fno-defer-pop : for the .hc files, we want all the pushing/
1494 -- popping of args to routines to be explicit; if we let things
1495 -- be deferred 'til after an STGJUMP, imminent death is certain!
1497 -- -fomit-frame-pointer : *don't*
1498 -- It's better to have a6 completely tied up being a frame pointer
1499 -- rather than let GCC pick random things to do with it.
1500 -- (If we want to steal a6, then we would try to do things
1501 -- as on iX86, where we *do* steal the frame pointer [%ebp].)
1502 = ( [], ["-fno-defer-pop", "-fno-omit-frame-pointer"] )
1504 #elif i386_TARGET_ARCH
1505 -- -fno-defer-pop : basically the same game as for m68k
1507 -- -fomit-frame-pointer : *must* in .hc files; because we're stealing
1508 -- the fp (%ebp) for our register maps.
1509 = let n_regs = stolen_x86_regs dflags
1512 ( [ if sta then "-DDONT_WANT_WIN32_DLL_SUPPORT" else ""
1513 -- , if "mingw32" `isSuffixOf` cTARGETPLATFORM then "-mno-cygwin" else ""
1516 #ifdef HAVE_GCC_MNO_OMIT_LFPTR
1517 -- Some gccs are configured with
1518 -- -momit-leaf-frame-pointer on by default, and it
1519 -- apparently takes precedence over
1520 -- -fomit-frame-pointer, so we disable it first here.
1521 "-mno-omit-leaf-frame-pointer",
1523 #ifdef HAVE_GCC_HAS_NO_UNIT_AT_A_TIME
1524 "-fno-unit-at-a-time",
1525 -- unit-at-a-time doesn't do us any good, and screws
1526 -- up -split-objs by moving the split markers around.
1527 -- It's only turned on with -O2, but put it here just
1528 -- in case someone uses -optc-O2.
1530 "-fomit-frame-pointer",
1531 -- we want -fno-builtin, because when gcc inlines
1532 -- built-in functions like memcpy() it tends to
1533 -- run out of registers, requiring -monly-n-regs
1535 "-DSTOLEN_X86_REGS="++show n_regs ]
1538 #elif ia64_TARGET_ARCH
1539 = ( [], ["-fomit-frame-pointer", "-G0"] )
1541 #elif x86_64_TARGET_ARCH
1542 = ( [], ["-fomit-frame-pointer",
1543 "-fno-asynchronous-unwind-tables",
1544 -- the unwind tables are unnecessary for HC code,
1545 -- and get in the way of -split-objs. Another option
1546 -- would be to throw them away in the mangler, but this
1548 #ifdef HAVE_GCC_HAS_NO_UNIT_AT_A_TIME
1549 "-fno-unit-at-a-time",
1550 -- unit-at-a-time doesn't do us any good, and screws
1551 -- up -split-objs by moving the split markers around.
1552 -- It's only turned on with -O2, but put it here just
1553 -- in case someone uses -optc-O2.
1556 -- calling builtins like strlen() using the FFI can
1557 -- cause gcc to run out of regs, so use the external
1561 #elif sparc_TARGET_ARCH
1563 -- For now, to suppress the gcc warning "call-clobbered
1564 -- register used for global register variable", we simply
1565 -- disable all warnings altogether using the -w flag. Oh well.
1567 #elif powerpc_apple_darwin_TARGET
1569 -- Disable Apple's precompiling preprocessor. It's a great thing
1570 -- for "normal" programs, but it doesn't support register variable
1572 = ( [], ["-no-cpp-precomp"] )
1577 picCCOpts :: DynFlags -> [String]
1579 #if darwin_TARGET_OS
1580 -- Apple prefers to do things the other way round.
1581 -- PIC is on by default.
1582 -- -mdynamic-no-pic:
1583 -- Turn off PIC code generation.
1585 -- Don't generate "common" symbols - these are unwanted
1586 -- in dynamic libraries.
1591 = ["-mdynamic-no-pic"]
1592 #elif mingw32_TARGET_OS
1593 -- no -fPIC for Windows
1602 -- -----------------------------------------------------------------------------
1607 #if defined(i386_TARGET_ARCH) \
1608 || defined(x86_64_TARGET_ARCH) \
1609 || defined(alpha_TARGET_ARCH) \
1610 || defined(hppa_TARGET_ARCH) \
1611 || defined(m68k_TARGET_ARCH) \
1612 || defined(mips_TARGET_ARCH) \
1613 || defined(powerpc_TARGET_ARCH) \
1614 || defined(rs6000_TARGET_ARCH) \
1615 || defined(sparc_TARGET_ARCH)