c26efb259772c70f78936b6ca16064bf015b7612
[ghc.git] / compiler / main / DynFlags.hs
1 -------------------------------------------------------------------------------
2 --
3 -- | Dynamic flags
4 --
5 -- Most flags are dynamic flags, which means they can change from compilation
6 -- to compilation using @OPTIONS_GHC@ pragmas, and in a multi-session GHC each
7 -- session can be using different dynamic flags. Dynamic flags can also be set
8 -- at the prompt in GHCi.
9 --
10 -- (c) The University of Glasgow 2005
11 --
12 -------------------------------------------------------------------------------
13
14 module DynFlags (
15 -- * Dynamic flags and associated configuration types
16 DynFlag(..),
17 WarningFlag(..),
18 ExtensionFlag(..),
19 Language(..),
20 LogAction, FlushOut(..), FlushErr(..),
21 ProfAuto(..),
22 glasgowExtsFlags,
23 dopt,
24 dopt_set,
25 dopt_unset,
26 wopt,
27 wopt_set,
28 wopt_unset,
29 xopt,
30 xopt_set,
31 xopt_unset,
32 lang_set,
33 DynFlags(..),
34 HasDynFlags(..), ContainsDynFlags(..),
35 RtsOptsEnabled(..),
36 HscTarget(..), isObjectTarget, defaultObjectTarget,
37 targetRetainsAllBindings,
38 GhcMode(..), isOneShot,
39 GhcLink(..), isNoLink,
40 PackageFlag(..),
41 PkgConfRef(..),
42 Option(..), showOpt,
43 DynLibLoader(..),
44 fFlags, fWarningFlags, fLangFlags, xFlags,
45 wayNames, dynFlagDependencies,
46
47 -- ** Safe Haskell
48 SafeHaskellMode(..),
49 safeHaskellOn, safeImportsOn, safeLanguageOn, safeInferOn,
50 packageTrustOn,
51 safeDirectImpsReq, safeImplicitImpsReq,
52 unsafeFlags,
53
54 -- ** System tool settings and locations
55 Settings(..),
56 targetPlatform,
57 ghcUsagePath, ghciUsagePath, topDir, tmpDir, rawSettings,
58 extraGccViaCFlags, systemPackageConfig,
59 pgm_L, pgm_P, pgm_F, pgm_c, pgm_s, pgm_a, pgm_l, pgm_dll, pgm_T,
60 pgm_sysman, pgm_windres, pgm_lo, pgm_lc,
61 opt_L, opt_P, opt_F, opt_c, opt_a, opt_l,
62 opt_windres, opt_lo, opt_lc,
63
64
65 -- ** Manipulating DynFlags
66 defaultDynFlags, -- Settings -> DynFlags
67 initDynFlags, -- DynFlags -> IO DynFlags
68 defaultLogAction,
69 defaultFlushOut,
70 defaultFlushErr,
71
72 getOpts, -- DynFlags -> (DynFlags -> [a]) -> [a]
73 getVerbFlags,
74 updOptLevel,
75 setTmpDir,
76 setPackageName,
77 doingTickyProfiling,
78
79 -- ** Parsing DynFlags
80 parseDynamicFlagsCmdLine,
81 parseDynamicFilePragma,
82 allFlags,
83
84 supportedLanguagesAndExtensions,
85
86 -- ** DynFlag C compiler options
87 picCCOpts,
88
89 -- * Configuration of the stg-to-stg passes
90 StgToDo(..),
91 getStgToDo,
92
93 -- * Compiler configuration suitable for display to the user
94 compilerInfo
95 #ifdef GHCI
96 -- Only in stage 2 can we be sure that the RTS
97 -- exposes the appropriate runtime boolean
98 , rtsIsProfiled
99 #endif
100 ) where
101
102 #include "HsVersions.h"
103
104 import Platform
105 import Module
106 import PackageConfig
107 import PrelNames ( mAIN )
108 import StaticFlags
109 import {-# SOURCE #-} Packages (PackageState)
110 import DriverPhases ( Phase(..), phaseInputExt )
111 import Config
112 import CmdLineParser
113 import Constants ( mAX_CONTEXT_REDUCTION_DEPTH )
114 import Panic
115 import Util
116 import Maybes ( orElse )
117 import SrcLoc
118 import FastString
119 import Outputable
120 #ifdef GHCI
121 import Foreign.C ( CInt(..) )
122 #endif
123 import {-# SOURCE #-} ErrUtils ( Severity(..), MsgDoc, mkLocMessage )
124
125 #ifdef GHCI
126 import System.IO.Unsafe ( unsafePerformIO )
127 #endif
128 import Data.IORef
129 import Control.Monad ( when )
130
131 import Data.Char
132 import Data.List
133 import Data.Map (Map)
134 import qualified Data.Map as Map
135 import Data.Set (Set)
136 import qualified Data.Set as Set
137 import System.FilePath
138 import System.IO
139
140 import Data.IntSet (IntSet)
141 import qualified Data.IntSet as IntSet
142
143 -- -----------------------------------------------------------------------------
144 -- DynFlags
145
146 -- | Enumerates the simple on-or-off dynamic flags
147 data DynFlag
148
149 -- debugging flags
150 = Opt_D_dump_cmm
151 | Opt_D_dump_raw_cmm
152 | Opt_D_dump_cmmz
153 | Opt_D_dump_cmmz_pretty
154 -- All of the cmmz subflags (there are a lot!) Automatically
155 -- enabled if you run -ddump-cmmz
156 | Opt_D_dump_cmmz_cbe
157 | Opt_D_dump_cmmz_proc
158 | Opt_D_dump_cmmz_spills
159 | Opt_D_dump_cmmz_rewrite
160 | Opt_D_dump_cmmz_dead
161 | Opt_D_dump_cmmz_stub
162 | Opt_D_dump_cmmz_sp
163 | Opt_D_dump_cmmz_procmap
164 | Opt_D_dump_cmmz_split
165 | Opt_D_dump_cmmz_lower
166 | Opt_D_dump_cmmz_info
167 | Opt_D_dump_cmmz_cafs
168 -- end cmmz subflags
169 | Opt_D_dump_cps_cmm
170 | Opt_D_dump_cvt_cmm
171 | Opt_D_dump_asm
172 | Opt_D_dump_asm_native
173 | Opt_D_dump_asm_liveness
174 | Opt_D_dump_asm_coalesce
175 | Opt_D_dump_asm_regalloc
176 | Opt_D_dump_asm_regalloc_stages
177 | Opt_D_dump_asm_conflicts
178 | Opt_D_dump_asm_stats
179 | Opt_D_dump_asm_expanded
180 | Opt_D_dump_llvm
181 | Opt_D_dump_core_stats
182 | Opt_D_dump_cpranal
183 | Opt_D_dump_deriv
184 | Opt_D_dump_ds
185 | Opt_D_dump_flatC
186 | Opt_D_dump_foreign
187 | Opt_D_dump_inlinings
188 | Opt_D_dump_rule_firings
189 | Opt_D_dump_rule_rewrites
190 | Opt_D_dump_occur_anal
191 | Opt_D_dump_parsed
192 | Opt_D_dump_rn
193 | Opt_D_dump_core_pipeline -- TODO FIXME: dump after simplifier stats
194 | Opt_D_dump_simpl
195 | Opt_D_dump_simpl_iterations
196 | Opt_D_dump_simpl_phases
197 | Opt_D_dump_spec
198 | Opt_D_dump_prep
199 | Opt_D_dump_stg
200 | Opt_D_dump_stranal
201 | Opt_D_dump_tc
202 | Opt_D_dump_types
203 | Opt_D_dump_rules
204 | Opt_D_dump_cse
205 | Opt_D_dump_worker_wrapper
206 | Opt_D_dump_rn_trace
207 | Opt_D_dump_rn_stats
208 | Opt_D_dump_opt_cmm
209 | Opt_D_dump_simpl_stats
210 | Opt_D_dump_cs_trace -- Constraint solver in type checker
211 | Opt_D_dump_tc_trace
212 | Opt_D_dump_if_trace
213 | Opt_D_dump_vt_trace
214 | Opt_D_dump_splices
215 | Opt_D_dump_BCOs
216 | Opt_D_dump_vect
217 | Opt_D_dump_avoid_vect
218 | Opt_D_dump_ticked
219 | Opt_D_dump_rtti
220 | Opt_D_source_stats
221 | Opt_D_verbose_core2core
222 | Opt_D_verbose_stg2stg
223 | Opt_D_dump_hi
224 | Opt_D_dump_hi_diffs
225 | Opt_D_dump_minimal_imports
226 | Opt_D_dump_mod_cycles
227 | Opt_D_dump_view_pattern_commoning
228 | Opt_D_faststring_stats
229 | Opt_DumpToFile -- ^ Append dump output to files instead of stdout.
230 | Opt_D_no_debug_output
231 | Opt_DoCoreLinting
232 | Opt_DoStgLinting
233 | Opt_DoCmmLinting
234 | Opt_DoAsmLinting
235 | Opt_NoLlvmMangler -- hidden flag
236
237 | Opt_WarnIsError -- -Werror; makes warnings fatal
238
239 | Opt_PrintExplicitForalls
240
241 -- optimisation opts
242 | Opt_Strictness
243 | Opt_FullLaziness
244 | Opt_FloatIn
245 | Opt_Specialise
246 | Opt_StaticArgumentTransformation
247 | Opt_CSE
248 | Opt_LiberateCase
249 | Opt_SpecConstr
250 | Opt_DoLambdaEtaExpansion
251 | Opt_IgnoreAsserts
252 | Opt_DoEtaReduction
253 | Opt_CaseMerge
254 | Opt_UnboxStrictFields
255 | Opt_DictsCheap
256 | Opt_EnableRewriteRules -- Apply rewrite rules during simplification
257 | Opt_Vectorise
258 | Opt_AvoidVect
259 | Opt_RegsGraph -- do graph coloring register allocation
260 | Opt_RegsIterative -- do iterative coalescing graph coloring register allocation
261 | Opt_PedanticBottoms -- Be picky about how we treat bottom
262 | Opt_LlvmTBAA -- Use LLVM TBAA infastructure for improving AA (hidden flag)
263 | Opt_RegLiveness -- Use the STG Reg liveness information (hidden flag)
264
265 -- Interface files
266 | Opt_IgnoreInterfacePragmas
267 | Opt_OmitInterfacePragmas
268 | Opt_ExposeAllUnfoldings
269
270 -- profiling opts
271 | Opt_AutoSccsOnIndividualCafs
272 | Opt_ProfCountEntries
273
274 -- misc opts
275 | Opt_Pp
276 | Opt_ForceRecomp
277 | Opt_ExcessPrecision
278 | Opt_EagerBlackHoling
279 | Opt_NoHsMain
280 | Opt_SplitObjs
281 | Opt_StgStats
282 | Opt_HideAllPackages
283 | Opt_PrintBindResult
284 | Opt_Haddock
285 | Opt_HaddockOptions
286 | Opt_Hpc_No_Auto
287 | Opt_BreakOnException
288 | Opt_BreakOnError
289 | Opt_PrintEvldWithShow
290 | Opt_PrintBindContents
291 | Opt_GenManifest
292 | Opt_EmbedManifest
293 | Opt_EmitExternalCore
294 | Opt_SharedImplib
295 | Opt_BuildingCabalPackage
296 | Opt_SSE2
297 | Opt_SSE4_2
298 | Opt_GhciSandbox
299 | Opt_GhciHistory
300 | Opt_HelpfulErrors
301 | Opt_DeferTypeErrors
302
303 -- temporary flags
304 | Opt_RunCPS
305 | Opt_RunCPSZ
306 | Opt_AutoLinkPackages
307 | Opt_ImplicitImportQualified
308 | Opt_TryNewCodeGen
309
310 -- keeping stuff
311 | Opt_KeepHiDiffs
312 | Opt_KeepHcFiles
313 | Opt_KeepSFiles
314 | Opt_KeepTmpFiles
315 | Opt_KeepRawTokenStream
316 | Opt_KeepLlvmFiles
317
318 -- safe haskell flags
319 | Opt_DistrustAllPackages
320 | Opt_PackageTrust
321
322 deriving (Eq, Show, Enum)
323
324 data WarningFlag =
325 Opt_WarnDuplicateExports
326 | Opt_WarnHiShadows
327 | Opt_WarnImplicitPrelude
328 | Opt_WarnIncompletePatterns
329 | Opt_WarnIncompleteUniPatterns
330 | Opt_WarnIncompletePatternsRecUpd
331 | Opt_WarnMissingFields
332 | Opt_WarnMissingImportList
333 | Opt_WarnMissingMethods
334 | Opt_WarnMissingSigs
335 | Opt_WarnMissingLocalSigs
336 | Opt_WarnNameShadowing
337 | Opt_WarnOverlappingPatterns
338 | Opt_WarnTypeDefaults
339 | Opt_WarnMonomorphism
340 | Opt_WarnUnusedBinds
341 | Opt_WarnUnusedImports
342 | Opt_WarnUnusedMatches
343 | Opt_WarnWarningsDeprecations
344 | Opt_WarnDeprecatedFlags
345 | Opt_WarnDodgyExports
346 | Opt_WarnDodgyImports
347 | Opt_WarnOrphans
348 | Opt_WarnAutoOrphans
349 | Opt_WarnIdentities
350 | Opt_WarnTabs
351 | Opt_WarnUnrecognisedPragmas
352 | Opt_WarnDodgyForeignImports
353 | Opt_WarnLazyUnliftedBindings
354 | Opt_WarnUnusedDoBind
355 | Opt_WarnWrongDoBind
356 | Opt_WarnAlternativeLayoutRuleTransitional
357 | Opt_WarnUnsafe
358 | Opt_WarnSafe
359 | Opt_WarnPointlessPragmas
360 | Opt_WarnUnsupportedCallingConventions
361 deriving (Eq, Show, Enum)
362
363 data Language = Haskell98 | Haskell2010
364 deriving Enum
365
366 -- | The various Safe Haskell modes
367 data SafeHaskellMode
368 = Sf_None
369 | Sf_Unsafe
370 | Sf_Trustworthy
371 | Sf_Safe
372 | Sf_SafeInfered
373 deriving (Eq)
374
375 instance Outputable SafeHaskellMode where
376 ppr Sf_None = ptext $ sLit "None"
377 ppr Sf_Unsafe = ptext $ sLit "Unsafe"
378 ppr Sf_Trustworthy = ptext $ sLit "Trustworthy"
379 ppr Sf_Safe = ptext $ sLit "Safe"
380 ppr Sf_SafeInfered = ptext $ sLit "Safe-Infered"
381
382 data ExtensionFlag
383 = Opt_Cpp
384 | Opt_OverlappingInstances
385 | Opt_UndecidableInstances
386 | Opt_IncoherentInstances
387 | Opt_MonomorphismRestriction
388 | Opt_MonoPatBinds
389 | Opt_MonoLocalBinds
390 | Opt_RelaxedPolyRec -- Deprecated
391 | Opt_ExtendedDefaultRules -- Use GHC's extended rules for defaulting
392 | Opt_ForeignFunctionInterface
393 | Opt_UnliftedFFITypes
394 | Opt_InterruptibleFFI
395 | Opt_CApiFFI
396 | Opt_GHCForeignImportPrim
397 | Opt_ParallelArrays -- Syntactic support for parallel arrays
398 | Opt_Arrows -- Arrow-notation syntax
399 | Opt_TemplateHaskell
400 | Opt_QuasiQuotes
401 | Opt_ImplicitParams
402 | Opt_ImplicitPrelude
403 | Opt_ScopedTypeVariables
404 | Opt_UnboxedTuples
405 | Opt_BangPatterns
406 | Opt_TypeFamilies
407 | Opt_OverloadedStrings
408 | Opt_DisambiguateRecordFields
409 | Opt_RecordWildCards
410 | Opt_RecordPuns
411 | Opt_ViewPatterns
412 | Opt_GADTs
413 | Opt_GADTSyntax
414 | Opt_NPlusKPatterns
415 | Opt_DoAndIfThenElse
416 | Opt_RebindableSyntax
417 | Opt_ConstraintKinds
418 | Opt_PolyKinds -- Kind polymorphism
419 | Opt_DataKinds -- Datatype promotion
420 | Opt_InstanceSigs
421
422 | Opt_StandaloneDeriving
423 | Opt_DeriveDataTypeable
424 | Opt_DeriveFunctor
425 | Opt_DeriveTraversable
426 | Opt_DeriveFoldable
427 | Opt_DeriveGeneric -- Allow deriving Generic/1
428 | Opt_DefaultSignatures -- Allow extra signatures for defmeths
429
430 | Opt_TypeSynonymInstances
431 | Opt_FlexibleContexts
432 | Opt_FlexibleInstances
433 | Opt_ConstrainedClassMethods
434 | Opt_MultiParamTypeClasses
435 | Opt_FunctionalDependencies
436 | Opt_UnicodeSyntax
437 | Opt_PolymorphicComponents
438 | Opt_ExistentialQuantification
439 | Opt_MagicHash
440 | Opt_EmptyDataDecls
441 | Opt_KindSignatures
442 | Opt_ParallelListComp
443 | Opt_TransformListComp
444 | Opt_MonadComprehensions
445 | Opt_GeneralizedNewtypeDeriving
446 | Opt_RecursiveDo
447 | Opt_DoRec
448 | Opt_PostfixOperators
449 | Opt_TupleSections
450 | Opt_PatternGuards
451 | Opt_LiberalTypeSynonyms
452 | Opt_Rank2Types
453 | Opt_RankNTypes
454 | Opt_ImpredicativeTypes
455 | Opt_TypeOperators
456 | Opt_ExplicitNamespaces
457 | Opt_PackageImports
458 | Opt_ExplicitForAll
459 | Opt_AlternativeLayoutRule
460 | Opt_AlternativeLayoutRuleTransitional
461 | Opt_DatatypeContexts
462 | Opt_NondecreasingIndentation
463 | Opt_RelaxedLayout
464 | Opt_TraditionalRecordSyntax
465 deriving (Eq, Enum, Show)
466
467 -- | Contains not only a collection of 'DynFlag's but also a plethora of
468 -- information relating to the compilation of a single file or GHC session
469 data DynFlags = DynFlags {
470 ghcMode :: GhcMode,
471 ghcLink :: GhcLink,
472 hscTarget :: HscTarget,
473 settings :: Settings,
474 hscOutName :: String, -- ^ Name of the output file
475 extCoreName :: String, -- ^ Name of the .hcr output file
476 verbosity :: Int, -- ^ Verbosity level: see Note [Verbosity levels]
477 optLevel :: Int, -- ^ Optimisation level
478 simplPhases :: Int, -- ^ Number of simplifier phases
479 maxSimplIterations :: Int, -- ^ Max simplifier iterations
480 shouldDumpSimplPhase :: Maybe String,
481 ruleCheck :: Maybe String,
482 strictnessBefore :: [Int], -- ^ Additional demand analysis
483
484 simplTickFactor :: Int, -- ^ Multiplier for simplifier ticks
485 specConstrThreshold :: Maybe Int, -- ^ Threshold for SpecConstr
486 specConstrCount :: Maybe Int, -- ^ Max number of specialisations for any one function
487 liberateCaseThreshold :: Maybe Int, -- ^ Threshold for LiberateCase
488 floatLamArgs :: Maybe Int, -- ^ Arg count for lambda floating
489 -- See CoreMonad.FloatOutSwitches
490
491 cmdlineHcIncludes :: [String], -- ^ @\-\#includes@
492 importPaths :: [FilePath],
493 mainModIs :: Module,
494 mainFunIs :: Maybe String,
495 ctxtStkDepth :: Int, -- ^ Typechecker context stack depth
496
497 thisPackage :: PackageId, -- ^ name of package currently being compiled
498
499 -- ways
500 ways :: [Way], -- ^ Way flags from the command line
501 buildTag :: String, -- ^ The global \"way\" (e.g. \"p\" for prof)
502 rtsBuildTag :: String, -- ^ The RTS \"way\"
503
504 -- For object splitting
505 splitInfo :: Maybe (String,Int),
506
507 -- paths etc.
508 objectDir :: Maybe String,
509 dylibInstallName :: Maybe String,
510 hiDir :: Maybe String,
511 stubDir :: Maybe String,
512 dumpDir :: Maybe String,
513
514 objectSuf :: String,
515 hcSuf :: String,
516 hiSuf :: String,
517
518 outputFile :: Maybe String,
519 outputHi :: Maybe String,
520 dynLibLoader :: DynLibLoader,
521
522 -- | This is set by 'DriverPipeline.runPipeline' based on where
523 -- its output is going.
524 dumpPrefix :: Maybe FilePath,
525
526 -- | Override the 'dumpPrefix' set by 'DriverPipeline.runPipeline'.
527 -- Set by @-ddump-file-prefix@
528 dumpPrefixForce :: Maybe FilePath,
529
530 includePaths :: [String],
531 libraryPaths :: [String],
532 frameworkPaths :: [String], -- used on darwin only
533 cmdlineFrameworks :: [String], -- ditto
534
535 rtsOpts :: Maybe String,
536 rtsOptsEnabled :: RtsOptsEnabled,
537
538 hpcDir :: String, -- ^ Path to store the .mix files
539
540 -- Plugins
541 pluginModNames :: [ModuleName],
542 pluginModNameOpts :: [(ModuleName,String)],
543
544 -- For ghc -M
545 depMakefile :: FilePath,
546 depIncludePkgDeps :: Bool,
547 depExcludeMods :: [ModuleName],
548 depSuffixes :: [String],
549
550 -- Package flags
551 extraPkgConfs :: [PkgConfRef] -> [PkgConfRef],
552 -- ^ The @-package-db@ flags given on the command line, in the order
553 -- they appeared.
554
555 packageFlags :: [PackageFlag],
556 -- ^ The @-package@ and @-hide-package@ flags from the command-line
557
558 -- Package state
559 -- NB. do not modify this field, it is calculated by
560 -- Packages.initPackages and Packages.updatePackages.
561 pkgDatabase :: Maybe [PackageConfig],
562 pkgState :: PackageState,
563
564 -- Temporary files
565 -- These have to be IORefs, because the defaultCleanupHandler needs to
566 -- know what to clean when an exception happens
567 filesToClean :: IORef [FilePath],
568 dirsToClean :: IORef (Map FilePath FilePath),
569
570 -- Names of files which were generated from -ddump-to-file; used to
571 -- track which ones we need to truncate because it's our first run
572 -- through
573 generatedDumps :: IORef (Set FilePath),
574
575 -- hsc dynamic flags
576 flags :: IntSet,
577 warningFlags :: IntSet,
578 -- Don't change this without updating extensionFlags:
579 language :: Maybe Language,
580 -- | Safe Haskell mode
581 safeHaskell :: SafeHaskellMode,
582 -- We store the location of where some extension and flags were turned on so
583 -- we can produce accurate error messages when Safe Haskell fails due to
584 -- them.
585 thOnLoc :: SrcSpan,
586 newDerivOnLoc :: SrcSpan,
587 pkgTrustOnLoc :: SrcSpan,
588 warnSafeOnLoc :: SrcSpan,
589 warnUnsafeOnLoc :: SrcSpan,
590 -- Don't change this without updating extensionFlags:
591 extensions :: [OnOff ExtensionFlag],
592 -- extensionFlags should always be equal to
593 -- flattenExtensionFlags language extensions
594 extensionFlags :: IntSet,
595
596 -- | MsgDoc output action: use "ErrUtils" instead of this if you can
597 log_action :: LogAction,
598 flushOut :: FlushOut,
599 flushErr :: FlushErr,
600
601 haddockOptions :: Maybe String,
602 ghciScripts :: [String],
603
604 -- | what kind of {-# SCC #-} to add automatically
605 profAuto :: ProfAuto,
606
607 llvmVersion :: IORef (Int)
608 }
609
610 class HasDynFlags m where
611 getDynFlags :: m DynFlags
612
613 class ContainsDynFlags t where
614 extractDynFlags :: t -> DynFlags
615
616 data ProfAuto
617 = NoProfAuto -- ^ no SCC annotations added
618 | ProfAutoAll -- ^ top-level and nested functions are annotated
619 | ProfAutoTop -- ^ top-level functions annotated only
620 | ProfAutoExports -- ^ exported functions annotated only
621 | ProfAutoCalls -- ^ annotate call-sites
622 deriving (Enum)
623
624 data Settings = Settings {
625 sTargetPlatform :: Platform, -- Filled in by SysTools
626 sGhcUsagePath :: FilePath, -- Filled in by SysTools
627 sGhciUsagePath :: FilePath, -- ditto
628 sTopDir :: FilePath,
629 sTmpDir :: String, -- no trailing '/'
630 -- You shouldn't need to look things up in rawSettings directly.
631 -- They should have their own fields instead.
632 sRawSettings :: [(String, String)],
633 sExtraGccViaCFlags :: [String],
634 sSystemPackageConfig :: FilePath,
635 -- commands for particular phases
636 sPgm_L :: String,
637 sPgm_P :: (String,[Option]),
638 sPgm_F :: String,
639 sPgm_c :: (String,[Option]),
640 sPgm_s :: (String,[Option]),
641 sPgm_a :: (String,[Option]),
642 sPgm_l :: (String,[Option]),
643 sPgm_dll :: (String,[Option]),
644 sPgm_T :: String,
645 sPgm_sysman :: String,
646 sPgm_windres :: String,
647 sPgm_lo :: (String,[Option]), -- LLVM: opt llvm optimiser
648 sPgm_lc :: (String,[Option]), -- LLVM: llc static compiler
649 -- options for particular phases
650 sOpt_L :: [String],
651 sOpt_P :: [String],
652 sOpt_F :: [String],
653 sOpt_c :: [String],
654 sOpt_a :: [String],
655 sOpt_l :: [String],
656 sOpt_windres :: [String],
657 sOpt_lo :: [String], -- LLVM: llvm optimiser
658 sOpt_lc :: [String] -- LLVM: llc static compiler
659
660 }
661
662 targetPlatform :: DynFlags -> Platform
663 targetPlatform dflags = sTargetPlatform (settings dflags)
664
665 ghcUsagePath :: DynFlags -> FilePath
666 ghcUsagePath dflags = sGhcUsagePath (settings dflags)
667 ghciUsagePath :: DynFlags -> FilePath
668 ghciUsagePath dflags = sGhciUsagePath (settings dflags)
669 topDir :: DynFlags -> FilePath
670 topDir dflags = sTopDir (settings dflags)
671 tmpDir :: DynFlags -> String
672 tmpDir dflags = sTmpDir (settings dflags)
673 rawSettings :: DynFlags -> [(String, String)]
674 rawSettings dflags = sRawSettings (settings dflags)
675 extraGccViaCFlags :: DynFlags -> [String]
676 extraGccViaCFlags dflags = sExtraGccViaCFlags (settings dflags)
677 systemPackageConfig :: DynFlags -> FilePath
678 systemPackageConfig dflags = sSystemPackageConfig (settings dflags)
679 pgm_L :: DynFlags -> String
680 pgm_L dflags = sPgm_L (settings dflags)
681 pgm_P :: DynFlags -> (String,[Option])
682 pgm_P dflags = sPgm_P (settings dflags)
683 pgm_F :: DynFlags -> String
684 pgm_F dflags = sPgm_F (settings dflags)
685 pgm_c :: DynFlags -> (String,[Option])
686 pgm_c dflags = sPgm_c (settings dflags)
687 pgm_s :: DynFlags -> (String,[Option])
688 pgm_s dflags = sPgm_s (settings dflags)
689 pgm_a :: DynFlags -> (String,[Option])
690 pgm_a dflags = sPgm_a (settings dflags)
691 pgm_l :: DynFlags -> (String,[Option])
692 pgm_l dflags = sPgm_l (settings dflags)
693 pgm_dll :: DynFlags -> (String,[Option])
694 pgm_dll dflags = sPgm_dll (settings dflags)
695 pgm_T :: DynFlags -> String
696 pgm_T dflags = sPgm_T (settings dflags)
697 pgm_sysman :: DynFlags -> String
698 pgm_sysman dflags = sPgm_sysman (settings dflags)
699 pgm_windres :: DynFlags -> String
700 pgm_windres dflags = sPgm_windres (settings dflags)
701 pgm_lo :: DynFlags -> (String,[Option])
702 pgm_lo dflags = sPgm_lo (settings dflags)
703 pgm_lc :: DynFlags -> (String,[Option])
704 pgm_lc dflags = sPgm_lc (settings dflags)
705 opt_L :: DynFlags -> [String]
706 opt_L dflags = sOpt_L (settings dflags)
707 opt_P :: DynFlags -> [String]
708 opt_P dflags = sOpt_P (settings dflags)
709 opt_F :: DynFlags -> [String]
710 opt_F dflags = sOpt_F (settings dflags)
711 opt_c :: DynFlags -> [String]
712 opt_c dflags = sOpt_c (settings dflags)
713 opt_a :: DynFlags -> [String]
714 opt_a dflags = sOpt_a (settings dflags)
715 opt_l :: DynFlags -> [String]
716 opt_l dflags = sOpt_l (settings dflags)
717 opt_windres :: DynFlags -> [String]
718 opt_windres dflags = sOpt_windres (settings dflags)
719 opt_lo :: DynFlags -> [String]
720 opt_lo dflags = sOpt_lo (settings dflags)
721 opt_lc :: DynFlags -> [String]
722 opt_lc dflags = sOpt_lc (settings dflags)
723
724 wayNames :: DynFlags -> [WayName]
725 wayNames = map wayName . ways
726
727 -- | The target code type of the compilation (if any).
728 --
729 -- Whenever you change the target, also make sure to set 'ghcLink' to
730 -- something sensible.
731 --
732 -- 'HscNothing' can be used to avoid generating any output, however, note
733 -- that:
734 --
735 -- * This will not run the desugaring step, thus no warnings generated in
736 -- this step will be output. In particular, this includes warnings related
737 -- to pattern matching. You can run the desugarer manually using
738 -- 'GHC.desugarModule'.
739 --
740 -- * If a program uses Template Haskell the typechecker may try to run code
741 -- from an imported module. This will fail if no code has been generated
742 -- for this module. You can use 'GHC.needsTemplateHaskell' to detect
743 -- whether this might be the case and choose to either switch to a
744 -- different target or avoid typechecking such modules. (The latter may be
745 -- preferable for security reasons.)
746 --
747 data HscTarget
748 = HscC -- ^ Generate C code.
749 | HscAsm -- ^ Generate assembly using the native code generator.
750 | HscLlvm -- ^ Generate assembly using the llvm code generator.
751 | HscInterpreted -- ^ Generate bytecode. (Requires 'LinkInMemory')
752 | HscNothing -- ^ Don't generate any code. See notes above.
753 deriving (Eq, Show)
754
755 showHscTargetFlag :: HscTarget -> String
756 showHscTargetFlag HscC = "-fvia-c"
757 showHscTargetFlag HscAsm = "-fasm"
758 showHscTargetFlag HscLlvm = "-fllvm"
759 showHscTargetFlag HscInterpreted = "-fbyte-code"
760 showHscTargetFlag HscNothing = "-fno-code"
761
762 -- | Will this target result in an object file on the disk?
763 isObjectTarget :: HscTarget -> Bool
764 isObjectTarget HscC = True
765 isObjectTarget HscAsm = True
766 isObjectTarget HscLlvm = True
767 isObjectTarget _ = False
768
769 -- | Does this target retain *all* top-level bindings for a module,
770 -- rather than just the exported bindings, in the TypeEnv and compiled
771 -- code (if any)? In interpreted mode we do this, so that GHCi can
772 -- call functions inside a module. In HscNothing mode we also do it,
773 -- so that Haddock can get access to the GlobalRdrEnv for a module
774 -- after typechecking it.
775 targetRetainsAllBindings :: HscTarget -> Bool
776 targetRetainsAllBindings HscInterpreted = True
777 targetRetainsAllBindings HscNothing = True
778 targetRetainsAllBindings _ = False
779
780 -- | The 'GhcMode' tells us whether we're doing multi-module
781 -- compilation (controlled via the "GHC" API) or one-shot
782 -- (single-module) compilation. This makes a difference primarily to
783 -- the "Finder": in one-shot mode we look for interface files for
784 -- imported modules, but in multi-module mode we look for source files
785 -- in order to check whether they need to be recompiled.
786 data GhcMode
787 = CompManager -- ^ @\-\-make@, GHCi, etc.
788 | OneShot -- ^ @ghc -c Foo.hs@
789 | MkDepend -- ^ @ghc -M@, see "Finder" for why we need this
790 deriving Eq
791
792 instance Outputable GhcMode where
793 ppr CompManager = ptext (sLit "CompManager")
794 ppr OneShot = ptext (sLit "OneShot")
795 ppr MkDepend = ptext (sLit "MkDepend")
796
797 isOneShot :: GhcMode -> Bool
798 isOneShot OneShot = True
799 isOneShot _other = False
800
801 -- | What to do in the link step, if there is one.
802 data GhcLink
803 = NoLink -- ^ Don't link at all
804 | LinkBinary -- ^ Link object code into a binary
805 | LinkInMemory -- ^ Use the in-memory dynamic linker (works for both
806 -- bytecode and object code).
807 | LinkDynLib -- ^ Link objects into a dynamic lib (DLL on Windows, DSO on ELF platforms)
808 deriving (Eq, Show)
809
810 isNoLink :: GhcLink -> Bool
811 isNoLink NoLink = True
812 isNoLink _ = False
813
814 -- Is it worth evaluating this Bool and caching it in the DynFlags value
815 -- during initDynFlags?
816 doingTickyProfiling :: DynFlags -> Bool
817 doingTickyProfiling _ = opt_Ticky
818 -- XXX -ticky is a static flag, because it implies -debug which is also
819 -- static. If the way flags were made dynamic, we could fix this.
820
821 data PackageFlag
822 = ExposePackage String
823 | ExposePackageId String
824 | HidePackage String
825 | IgnorePackage String
826 | TrustPackage String
827 | DistrustPackage String
828 deriving Eq
829
830 defaultHscTarget :: HscTarget
831 defaultHscTarget = defaultObjectTarget
832
833 -- | The 'HscTarget' value corresponding to the default way to create
834 -- object files on the current platform.
835 defaultObjectTarget :: HscTarget
836 defaultObjectTarget
837 | cGhcUnregisterised == "YES" = HscC
838 | cGhcWithNativeCodeGen == "YES" = HscAsm
839 | otherwise = HscLlvm
840
841 data DynLibLoader
842 = Deployable
843 | SystemDependent
844 deriving Eq
845
846 data RtsOptsEnabled = RtsOptsNone | RtsOptsSafeOnly | RtsOptsAll
847 deriving (Show)
848
849 -- | Used by 'GHC.newSession' to partially initialize a new 'DynFlags' value
850 initDynFlags :: DynFlags -> IO DynFlags
851 initDynFlags dflags = do
852 -- someday these will be dynamic flags
853 ways <- readIORef v_Ways
854 refFilesToClean <- newIORef []
855 refDirsToClean <- newIORef Map.empty
856 refGeneratedDumps <- newIORef Set.empty
857 refLlvmVersion <- newIORef 28
858 return dflags{
859 ways = ways,
860 buildTag = mkBuildTag (filter (not . wayRTSOnly) ways),
861 rtsBuildTag = mkBuildTag ways,
862 filesToClean = refFilesToClean,
863 dirsToClean = refDirsToClean,
864 generatedDumps = refGeneratedDumps,
865 llvmVersion = refLlvmVersion
866 }
867
868 -- | The normal 'DynFlags'. Note that they is not suitable for use in this form
869 -- and must be fully initialized by 'GHC.newSession' first.
870 defaultDynFlags :: Settings -> DynFlags
871 defaultDynFlags mySettings =
872 DynFlags {
873 ghcMode = CompManager,
874 ghcLink = LinkBinary,
875 hscTarget = defaultHscTarget,
876 hscOutName = "",
877 extCoreName = "",
878 verbosity = 0,
879 optLevel = 0,
880 simplPhases = 2,
881 maxSimplIterations = 4,
882 shouldDumpSimplPhase = Nothing,
883 ruleCheck = Nothing,
884 simplTickFactor = 100,
885 specConstrThreshold = Just 2000,
886 specConstrCount = Just 3,
887 liberateCaseThreshold = Just 2000,
888 floatLamArgs = Just 0, -- Default: float only if no fvs
889 strictnessBefore = [],
890
891 cmdlineHcIncludes = [],
892 importPaths = ["."],
893 mainModIs = mAIN,
894 mainFunIs = Nothing,
895 ctxtStkDepth = mAX_CONTEXT_REDUCTION_DEPTH,
896
897 thisPackage = mainPackageId,
898
899 objectDir = Nothing,
900 dylibInstallName = Nothing,
901 hiDir = Nothing,
902 stubDir = Nothing,
903 dumpDir = Nothing,
904
905 objectSuf = phaseInputExt StopLn,
906 hcSuf = phaseInputExt HCc,
907 hiSuf = "hi",
908
909 pluginModNames = [],
910 pluginModNameOpts = [],
911
912 outputFile = Nothing,
913 outputHi = Nothing,
914 dynLibLoader = SystemDependent,
915 dumpPrefix = Nothing,
916 dumpPrefixForce = Nothing,
917 includePaths = [],
918 libraryPaths = [],
919 frameworkPaths = [],
920 cmdlineFrameworks = [],
921 rtsOpts = Nothing,
922 rtsOptsEnabled = RtsOptsSafeOnly,
923
924 hpcDir = ".hpc",
925
926 extraPkgConfs = id,
927 packageFlags = [],
928 pkgDatabase = Nothing,
929 pkgState = panic "no package state yet: call GHC.setSessionDynFlags",
930 ways = panic "defaultDynFlags: No ways",
931 buildTag = panic "defaultDynFlags: No buildTag",
932 rtsBuildTag = panic "defaultDynFlags: No rtsBuildTag",
933 splitInfo = Nothing,
934 settings = mySettings,
935 -- ghc -M values
936 depMakefile = "Makefile",
937 depIncludePkgDeps = False,
938 depExcludeMods = [],
939 depSuffixes = [],
940 -- end of ghc -M values
941 filesToClean = panic "defaultDynFlags: No filesToClean",
942 dirsToClean = panic "defaultDynFlags: No dirsToClean",
943 generatedDumps = panic "defaultDynFlags: No generatedDumps",
944 haddockOptions = Nothing,
945 flags = IntSet.fromList (map fromEnum defaultFlags),
946 warningFlags = IntSet.fromList (map fromEnum standardWarnings),
947 ghciScripts = [],
948 language = Nothing,
949 safeHaskell = Sf_SafeInfered,
950 thOnLoc = noSrcSpan,
951 newDerivOnLoc = noSrcSpan,
952 pkgTrustOnLoc = noSrcSpan,
953 warnSafeOnLoc = noSrcSpan,
954 warnUnsafeOnLoc = noSrcSpan,
955 extensions = [],
956 extensionFlags = flattenExtensionFlags Nothing [],
957 log_action = defaultLogAction,
958 flushOut = defaultFlushOut,
959 flushErr = defaultFlushErr,
960 profAuto = NoProfAuto,
961 llvmVersion = panic "defaultDynFlags: No llvmVersion"
962 }
963
964 type LogAction = Severity -> SrcSpan -> PprStyle -> MsgDoc -> IO ()
965
966 defaultLogAction :: LogAction
967 defaultLogAction severity srcSpan style msg
968 = case severity of
969 SevOutput -> printSDoc msg style
970 SevInfo -> printErrs msg style
971 SevFatal -> printErrs msg style
972 _ -> do hPutChar stderr '\n'
973 printErrs (mkLocMessage severity srcSpan msg) style
974 -- careful (#2302): printErrs prints in UTF-8, whereas
975 -- converting to string first and using hPutStr would
976 -- just emit the low 8 bits of each unicode char.
977
978 newtype FlushOut = FlushOut (IO ())
979
980 defaultFlushOut :: FlushOut
981 defaultFlushOut = FlushOut $ hFlush stdout
982
983 newtype FlushErr = FlushErr (IO ())
984
985 defaultFlushErr :: FlushErr
986 defaultFlushErr = FlushErr $ hFlush stderr
987
988 {-
989 Note [Verbosity levels]
990 ~~~~~~~~~~~~~~~~~~~~~~~
991 0 | print errors & warnings only
992 1 | minimal verbosity: print "compiling M ... done." for each module.
993 2 | equivalent to -dshow-passes
994 3 | equivalent to existing "ghc -v"
995 4 | "ghc -v -ddump-most"
996 5 | "ghc -v -ddump-all"
997 -}
998
999 data OnOff a = On a
1000 | Off a
1001
1002 -- OnOffs accumulate in reverse order, so we use foldr in order to
1003 -- process them in the right order
1004 flattenExtensionFlags :: Maybe Language -> [OnOff ExtensionFlag] -> IntSet
1005 flattenExtensionFlags ml = foldr f defaultExtensionFlags
1006 where f (On f) flags = IntSet.insert (fromEnum f) flags
1007 f (Off f) flags = IntSet.delete (fromEnum f) flags
1008 defaultExtensionFlags = IntSet.fromList (map fromEnum (languageExtensions ml))
1009
1010 languageExtensions :: Maybe Language -> [ExtensionFlag]
1011
1012 languageExtensions Nothing
1013 -- Nothing => the default case
1014 = Opt_NondecreasingIndentation -- This has been on by default for some time
1015 : delete Opt_DatatypeContexts -- The Haskell' committee decided to
1016 -- remove datatype contexts from the
1017 -- language:
1018 -- http://www.haskell.org/pipermail/haskell-prime/2011-January/003335.html
1019 (languageExtensions (Just Haskell2010))
1020
1021 -- NB: MonoPatBinds is no longer the default
1022
1023 languageExtensions (Just Haskell98)
1024 = [Opt_ImplicitPrelude,
1025 Opt_MonomorphismRestriction,
1026 Opt_NPlusKPatterns,
1027 Opt_DatatypeContexts,
1028 Opt_TraditionalRecordSyntax,
1029 Opt_NondecreasingIndentation
1030 -- strictly speaking non-standard, but we always had this
1031 -- on implicitly before the option was added in 7.1, and
1032 -- turning it off breaks code, so we're keeping it on for
1033 -- backwards compatibility. Cabal uses -XHaskell98 by
1034 -- default unless you specify another language.
1035 ]
1036
1037 languageExtensions (Just Haskell2010)
1038 = [Opt_ImplicitPrelude,
1039 Opt_MonomorphismRestriction,
1040 Opt_DatatypeContexts,
1041 Opt_TraditionalRecordSyntax,
1042 Opt_EmptyDataDecls,
1043 Opt_ForeignFunctionInterface,
1044 Opt_PatternGuards,
1045 Opt_DoAndIfThenElse,
1046 Opt_RelaxedPolyRec]
1047
1048 -- | Test whether a 'DynFlag' is set
1049 dopt :: DynFlag -> DynFlags -> Bool
1050 dopt f dflags = fromEnum f `IntSet.member` flags dflags
1051
1052 -- | Set a 'DynFlag'
1053 dopt_set :: DynFlags -> DynFlag -> DynFlags
1054 dopt_set dfs f = dfs{ flags = IntSet.insert (fromEnum f) (flags dfs) }
1055
1056 -- | Unset a 'DynFlag'
1057 dopt_unset :: DynFlags -> DynFlag -> DynFlags
1058 dopt_unset dfs f = dfs{ flags = IntSet.delete (fromEnum f) (flags dfs) }
1059
1060 -- | Test whether a 'WarningFlag' is set
1061 wopt :: WarningFlag -> DynFlags -> Bool
1062 wopt f dflags = fromEnum f `IntSet.member` warningFlags dflags
1063
1064 -- | Set a 'WarningFlag'
1065 wopt_set :: DynFlags -> WarningFlag -> DynFlags
1066 wopt_set dfs f = dfs{ warningFlags = IntSet.insert (fromEnum f) (warningFlags dfs) }
1067
1068 -- | Unset a 'WarningFlag'
1069 wopt_unset :: DynFlags -> WarningFlag -> DynFlags
1070 wopt_unset dfs f = dfs{ warningFlags = IntSet.delete (fromEnum f) (warningFlags dfs) }
1071
1072 -- | Test whether a 'ExtensionFlag' is set
1073 xopt :: ExtensionFlag -> DynFlags -> Bool
1074 xopt f dflags = fromEnum f `IntSet.member` extensionFlags dflags
1075
1076 -- | Set a 'ExtensionFlag'
1077 xopt_set :: DynFlags -> ExtensionFlag -> DynFlags
1078 xopt_set dfs f
1079 = let onoffs = On f : extensions dfs
1080 in dfs { extensions = onoffs,
1081 extensionFlags = flattenExtensionFlags (language dfs) onoffs }
1082
1083 -- | Unset a 'ExtensionFlag'
1084 xopt_unset :: DynFlags -> ExtensionFlag -> DynFlags
1085 xopt_unset dfs f
1086 = let onoffs = Off f : extensions dfs
1087 in dfs { extensions = onoffs,
1088 extensionFlags = flattenExtensionFlags (language dfs) onoffs }
1089
1090 lang_set :: DynFlags -> Maybe Language -> DynFlags
1091 lang_set dflags lang =
1092 dflags {
1093 language = lang,
1094 extensionFlags = flattenExtensionFlags lang (extensions dflags)
1095 }
1096
1097 -- | Set the Haskell language standard to use
1098 setLanguage :: Language -> DynP ()
1099 setLanguage l = upd (`lang_set` Just l)
1100
1101 -- | Some modules have dependencies on others through the DynFlags rather than textual imports
1102 dynFlagDependencies :: DynFlags -> [ModuleName]
1103 dynFlagDependencies = pluginModNames
1104
1105 -- | Is the -fpackage-trust mode on
1106 packageTrustOn :: DynFlags -> Bool
1107 packageTrustOn = dopt Opt_PackageTrust
1108
1109 -- | Is Safe Haskell on in some way (including inference mode)
1110 safeHaskellOn :: DynFlags -> Bool
1111 safeHaskellOn dflags = safeHaskell dflags /= Sf_None
1112
1113 -- | Is the Safe Haskell safe language in use
1114 safeLanguageOn :: DynFlags -> Bool
1115 safeLanguageOn dflags = safeHaskell dflags == Sf_Safe
1116
1117 -- | Is the Safe Haskell safe inference mode active
1118 safeInferOn :: DynFlags -> Bool
1119 safeInferOn dflags = safeHaskell dflags == Sf_SafeInfered
1120
1121 -- | Test if Safe Imports are on in some form
1122 safeImportsOn :: DynFlags -> Bool
1123 safeImportsOn dflags = safeHaskell dflags == Sf_Unsafe ||
1124 safeHaskell dflags == Sf_Trustworthy ||
1125 safeHaskell dflags == Sf_Safe
1126
1127 -- | Set a 'Safe Haskell' flag
1128 setSafeHaskell :: SafeHaskellMode -> DynP ()
1129 setSafeHaskell s = updM f
1130 where f dfs = do
1131 let sf = safeHaskell dfs
1132 safeM <- combineSafeFlags sf s
1133 return $ dfs { safeHaskell = safeM }
1134
1135 -- | Are all direct imports required to be safe for this Safe Haskell mode?
1136 -- Direct imports are when the code explicitly imports a module
1137 safeDirectImpsReq :: DynFlags -> Bool
1138 safeDirectImpsReq d = safeLanguageOn d
1139
1140 -- | Are all implicit imports required to be safe for this Safe Haskell mode?
1141 -- Implicit imports are things in the prelude. e.g System.IO when print is used.
1142 safeImplicitImpsReq :: DynFlags -> Bool
1143 safeImplicitImpsReq d = safeLanguageOn d
1144
1145 -- | Combine two Safe Haskell modes correctly. Used for dealing with multiple flags.
1146 -- This makes Safe Haskell very much a monoid but for now I prefer this as I don't
1147 -- want to export this functionality from the module but do want to export the
1148 -- type constructors.
1149 combineSafeFlags :: SafeHaskellMode -> SafeHaskellMode -> DynP SafeHaskellMode
1150 combineSafeFlags a b | a == Sf_SafeInfered = return b
1151 | b == Sf_SafeInfered = return a
1152 | a == Sf_None = return b
1153 | b == Sf_None = return a
1154 | a == b = return a
1155 | otherwise = addErr errm >> return (panic errm)
1156 where errm = "Incompatible Safe Haskell flags! ("
1157 ++ showPpr a ++ ", " ++ showPpr b ++ ")"
1158
1159 -- | A list of unsafe flags under Safe Haskell. Tuple elements are:
1160 -- * name of the flag
1161 -- * function to get srcspan that enabled the flag
1162 -- * function to test if the flag is on
1163 -- * function to turn the flag off
1164 unsafeFlags :: [(String, DynFlags -> SrcSpan, DynFlags -> Bool, DynFlags -> DynFlags)]
1165 unsafeFlags = [("-XGeneralizedNewtypeDeriving", newDerivOnLoc,
1166 xopt Opt_GeneralizedNewtypeDeriving,
1167 flip xopt_unset Opt_GeneralizedNewtypeDeriving),
1168 ("-XTemplateHaskell", thOnLoc,
1169 xopt Opt_TemplateHaskell,
1170 flip xopt_unset Opt_TemplateHaskell)]
1171
1172 -- | Retrieve the options corresponding to a particular @opt_*@ field in the correct order
1173 getOpts :: DynFlags -- ^ 'DynFlags' to retrieve the options from
1174 -> (DynFlags -> [a]) -- ^ Relevant record accessor: one of the @opt_*@ accessors
1175 -> [a] -- ^ Correctly ordered extracted options
1176 getOpts dflags opts = reverse (opts dflags)
1177 -- We add to the options from the front, so we need to reverse the list
1178
1179 -- | Gets the verbosity flag for the current verbosity level. This is fed to
1180 -- other tools, so GHC-specific verbosity flags like @-ddump-most@ are not included
1181 getVerbFlags :: DynFlags -> [String]
1182 getVerbFlags dflags
1183 | verbosity dflags >= 4 = ["-v"]
1184 | otherwise = []
1185
1186 setObjectDir, setHiDir, setStubDir, setDumpDir, setOutputDir,
1187 setDylibInstallName,
1188 setObjectSuf, setHiSuf, setHcSuf, parseDynLibLoaderMode,
1189 setPgmP, addOptl, addOptP,
1190 addCmdlineFramework, addHaddockOpts, addGhciScript
1191 :: String -> DynFlags -> DynFlags
1192 setOutputFile, setOutputHi, setDumpPrefixForce
1193 :: Maybe String -> DynFlags -> DynFlags
1194
1195 setObjectDir f d = d{ objectDir = Just f}
1196 setHiDir f d = d{ hiDir = Just f}
1197 setStubDir f d = d{ stubDir = Just f, includePaths = f : includePaths d }
1198 -- -stubdir D adds an implicit -I D, so that gcc can find the _stub.h file
1199 -- \#included from the .hc file when compiling via C (i.e. unregisterised
1200 -- builds).
1201 setDumpDir f d = d{ dumpDir = Just f}
1202 setOutputDir f = setObjectDir f . setHiDir f . setStubDir f . setDumpDir f
1203 setDylibInstallName f d = d{ dylibInstallName = Just f}
1204
1205 setObjectSuf f d = d{ objectSuf = f}
1206 setHiSuf f d = d{ hiSuf = f}
1207 setHcSuf f d = d{ hcSuf = f}
1208
1209 setOutputFile f d = d{ outputFile = f}
1210 setOutputHi f d = d{ outputHi = f}
1211
1212 addPluginModuleName :: String -> DynFlags -> DynFlags
1213 addPluginModuleName name d = d { pluginModNames = (mkModuleName name) : (pluginModNames d) }
1214
1215 addPluginModuleNameOption :: String -> DynFlags -> DynFlags
1216 addPluginModuleNameOption optflag d = d { pluginModNameOpts = (mkModuleName m, option) : (pluginModNameOpts d) }
1217 where (m, rest) = break (== ':') optflag
1218 option = case rest of
1219 [] -> "" -- should probably signal an error
1220 (_:plug_opt) -> plug_opt -- ignore the ':' from break
1221
1222 parseDynLibLoaderMode f d =
1223 case splitAt 8 f of
1224 ("deploy", "") -> d{ dynLibLoader = Deployable }
1225 ("sysdep", "") -> d{ dynLibLoader = SystemDependent }
1226 _ -> ghcError (CmdLineError ("Unknown dynlib loader: " ++ f))
1227
1228 setDumpPrefixForce f d = d { dumpPrefixForce = f}
1229
1230 -- XXX HACK: Prelude> words "'does not' work" ===> ["'does","not'","work"]
1231 -- Config.hs should really use Option.
1232 setPgmP f = let (pgm:args) = words f in alterSettings (\s -> s { sPgm_P = (pgm, map Option args)})
1233 addOptl f = alterSettings (\s -> s { sOpt_l = f : sOpt_l s})
1234 addOptP f = alterSettings (\s -> s { sOpt_P = f : sOpt_P s})
1235
1236
1237 setDepMakefile :: FilePath -> DynFlags -> DynFlags
1238 setDepMakefile f d = d { depMakefile = deOptDep f }
1239
1240 setDepIncludePkgDeps :: Bool -> DynFlags -> DynFlags
1241 setDepIncludePkgDeps b d = d { depIncludePkgDeps = b }
1242
1243 addDepExcludeMod :: String -> DynFlags -> DynFlags
1244 addDepExcludeMod m d
1245 = d { depExcludeMods = mkModuleName (deOptDep m) : depExcludeMods d }
1246
1247 addDepSuffix :: FilePath -> DynFlags -> DynFlags
1248 addDepSuffix s d = d { depSuffixes = deOptDep s : depSuffixes d }
1249
1250 -- XXX Legacy code:
1251 -- We used to use "-optdep-flag -optdeparg", so for legacy applications
1252 -- we need to strip the "-optdep" off of the arg
1253 deOptDep :: String -> String
1254 deOptDep x = case stripPrefix "-optdep" x of
1255 Just rest -> rest
1256 Nothing -> x
1257
1258 addCmdlineFramework f d = d{ cmdlineFrameworks = f : cmdlineFrameworks d}
1259
1260 addHaddockOpts f d = d{ haddockOptions = Just f}
1261
1262 addGhciScript f d = d{ ghciScripts = f : ghciScripts d}
1263
1264 -- -----------------------------------------------------------------------------
1265 -- Command-line options
1266
1267 -- | When invoking external tools as part of the compilation pipeline, we
1268 -- pass these a sequence of options on the command-line. Rather than
1269 -- just using a list of Strings, we use a type that allows us to distinguish
1270 -- between filepaths and 'other stuff'. The reason for this is that
1271 -- this type gives us a handle on transforming filenames, and filenames only,
1272 -- to whatever format they're expected to be on a particular platform.
1273 data Option
1274 = FileOption -- an entry that _contains_ filename(s) / filepaths.
1275 String -- a non-filepath prefix that shouldn't be
1276 -- transformed (e.g., "/out=")
1277 String -- the filepath/filename portion
1278 | Option String
1279 deriving ( Eq )
1280
1281 showOpt :: Option -> String
1282 showOpt (FileOption pre f) = pre ++ f
1283 showOpt (Option s) = s
1284
1285 -----------------------------------------------------------------------------
1286 -- Setting the optimisation level
1287
1288 updOptLevel :: Int -> DynFlags -> DynFlags
1289 -- ^ Sets the 'DynFlags' to be appropriate to the optimisation level
1290 updOptLevel n dfs
1291 = dfs2{ optLevel = final_n }
1292 where
1293 final_n = max 0 (min 2 n) -- Clamp to 0 <= n <= 2
1294 dfs1 = foldr (flip dopt_unset) dfs remove_dopts
1295 dfs2 = foldr (flip dopt_set) dfs1 extra_dopts
1296
1297 extra_dopts = [ f | (ns,f) <- optLevelFlags, final_n `elem` ns ]
1298 remove_dopts = [ f | (ns,f) <- optLevelFlags, final_n `notElem` ns ]
1299
1300 -- -----------------------------------------------------------------------------
1301 -- StgToDo: abstraction of stg-to-stg passes to run.
1302
1303 data StgToDo
1304 = StgDoMassageForProfiling -- should be (next to) last
1305 -- There's also setStgVarInfo, but its absolute "lastness"
1306 -- is so critical that it is hardwired in (no flag).
1307 | D_stg_stats
1308
1309 getStgToDo :: DynFlags -> [StgToDo]
1310 getStgToDo dflags
1311 = todo2
1312 where
1313 stg_stats = dopt Opt_StgStats dflags
1314
1315 todo1 = if stg_stats then [D_stg_stats] else []
1316
1317 todo2 | WayProf `elem` wayNames dflags
1318 = StgDoMassageForProfiling : todo1
1319 | otherwise
1320 = todo1
1321
1322 {- **********************************************************************
1323 %* *
1324 DynFlags parser
1325 %* *
1326 %********************************************************************* -}
1327
1328 -- -----------------------------------------------------------------------------
1329 -- Parsing the dynamic flags.
1330
1331 -- | Parse dynamic flags from a list of command line arguments. Returns the
1332 -- the parsed 'DynFlags', the left-over arguments, and a list of warnings.
1333 -- Throws a 'UsageError' if errors occurred during parsing (such as unknown
1334 -- flags or missing arguments).
1335 parseDynamicFlagsCmdLine :: Monad m =>
1336 DynFlags -> [Located String]
1337 -> m (DynFlags, [Located String], [Located String])
1338 -- ^ Updated 'DynFlags', left-over arguments, and
1339 -- list of warnings.
1340 parseDynamicFlagsCmdLine dflags args = parseDynamicFlags dflags args True
1341
1342 -- | Like 'parseDynamicFlagsCmdLine' but does not allow the package flags
1343 -- (-package, -hide-package, -ignore-package, -hide-all-packages, -package-db).
1344 -- Used to parse flags set in a modules pragma.
1345 parseDynamicFilePragma :: Monad m =>
1346 DynFlags -> [Located String]
1347 -> m (DynFlags, [Located String], [Located String])
1348 -- ^ Updated 'DynFlags', left-over arguments, and
1349 -- list of warnings.
1350 parseDynamicFilePragma dflags args = parseDynamicFlags dflags args False
1351
1352 parseDynamicFlags :: Monad m =>
1353 DynFlags -> [Located String] -> Bool
1354 -> m (DynFlags, [Located String], [Located String])
1355 parseDynamicFlags dflags0 args cmdline = do
1356 -- XXX Legacy support code
1357 -- We used to accept things like
1358 -- optdep-f -optdepdepend
1359 -- optdep-f -optdep depend
1360 -- optdep -f -optdepdepend
1361 -- optdep -f -optdep depend
1362 -- but the spaces trip up proper argument handling. So get rid of them.
1363 let f (L p "-optdep" : L _ x : xs) = (L p ("-optdep" ++ x)) : f xs
1364 f (x : xs) = x : f xs
1365 f xs = xs
1366 args' = f args
1367
1368 -- Note: -ignore-package (package_flags) must precede -i* (dynamic_flags)
1369 flag_spec | cmdline = package_flags ++ dynamic_flags
1370 | otherwise = dynamic_flags
1371
1372 let ((leftover, errs, warns), dflags1)
1373 = runCmdLine (processArgs flag_spec args') dflags0
1374 when (not (null errs)) $ ghcError $ errorsToGhcException errs
1375
1376 -- check for disabled flags in safe haskell
1377 let (dflags2, sh_warns) = safeFlagCheck cmdline dflags1
1378
1379 return (dflags2, leftover, sh_warns ++ warns)
1380
1381 -- | Check (and potentially disable) any extensions that aren't allowed
1382 -- in safe mode.
1383 safeFlagCheck :: Bool -> DynFlags -> (DynFlags, [Located String])
1384 safeFlagCheck _ dflags | not (safeLanguageOn dflags || safeInferOn dflags)
1385 = (dflags, [])
1386
1387 -- safe or safe-infer ON
1388 safeFlagCheck cmdl dflags =
1389 case safeLanguageOn dflags of
1390 True -> (dflags', warns)
1391
1392 -- throw error if -fpackage-trust by itself with no safe haskell flag
1393 False | not cmdl && packageTrustOn dflags
1394 -> (dopt_unset dflags' Opt_PackageTrust,
1395 [L (pkgTrustOnLoc dflags') $
1396 "-fpackage-trust ignored;" ++
1397 " must be specified with a Safe Haskell flag"]
1398 )
1399
1400 False | null warns && safeInfOk
1401 -> (dflags', [])
1402
1403 | otherwise
1404 -> (dflags' { safeHaskell = Sf_None }, [])
1405 -- Have we infered Unsafe?
1406 -- See Note [HscMain . Safe Haskell Inference]
1407 where
1408 -- TODO: Can we do better than this for inference?
1409 safeInfOk = not $ xopt Opt_OverlappingInstances dflags
1410
1411 (dflags', warns) = foldl check_method (dflags, []) unsafeFlags
1412
1413 check_method (df, warns) (str,loc,test,fix)
1414 | test df = (apFix fix df, warns ++ safeFailure (loc dflags) str)
1415 | otherwise = (df, warns)
1416
1417 apFix f = if safeInferOn dflags then id else f
1418
1419 safeFailure loc str
1420 = [L loc $ str ++ " is not allowed in Safe Haskell; ignoring " ++ str]
1421
1422 {- **********************************************************************
1423 %* *
1424 DynFlags specifications
1425 %* *
1426 %********************************************************************* -}
1427
1428 allFlags :: [String]
1429 allFlags = map ('-':) $
1430 [ flagName flag | flag <- dynamic_flags ++ package_flags, ok (flagOptKind flag) ] ++
1431 map ("fno-"++) fflags ++
1432 map ("f"++) fflags ++
1433 map ("X"++) supportedExtensions
1434 where ok (PrefixPred _ _) = False
1435 ok _ = True
1436 fflags = fflags0 ++ fflags1 ++ fflags2
1437 fflags0 = [ name | (name, _, _) <- fFlags ]
1438 fflags1 = [ name | (name, _, _) <- fWarningFlags ]
1439 fflags2 = [ name | (name, _, _) <- fLangFlags ]
1440
1441 --------------- The main flags themselves ------------------
1442 dynamic_flags :: [Flag (CmdLineP DynFlags)]
1443 dynamic_flags = [
1444 Flag "n" (NoArg (addWarn "The -n flag is deprecated and no longer has any effect"))
1445 , Flag "cpp" (NoArg (setExtensionFlag Opt_Cpp))
1446 , Flag "F" (NoArg (setDynFlag Opt_Pp))
1447 , Flag "#include"
1448 (HasArg (\s -> do addCmdlineHCInclude s
1449 addWarn "-#include and INCLUDE pragmas are deprecated: They no longer have any effect"))
1450 , Flag "v" (OptIntSuffix setVerbosity)
1451
1452 ------- Specific phases --------------------------------------------
1453 -- need to appear before -pgmL to be parsed as LLVM flags.
1454 , Flag "pgmlo" (hasArg (\f -> alterSettings (\s -> s { sPgm_lo = (f,[])})))
1455 , Flag "pgmlc" (hasArg (\f -> alterSettings (\s -> s { sPgm_lc = (f,[])})))
1456 , Flag "pgmL" (hasArg (\f -> alterSettings (\s -> s { sPgm_L = f})))
1457 , Flag "pgmP" (hasArg setPgmP)
1458 , Flag "pgmF" (hasArg (\f -> alterSettings (\s -> s { sPgm_F = f})))
1459 , Flag "pgmc" (hasArg (\f -> alterSettings (\s -> s { sPgm_c = (f,[])})))
1460 , Flag "pgmm" (HasArg (\_ -> addWarn "The -pgmm flag does nothing; it will be removed in a future GHC release"))
1461 , Flag "pgms" (hasArg (\f -> alterSettings (\s -> s { sPgm_s = (f,[])})))
1462 , Flag "pgma" (hasArg (\f -> alterSettings (\s -> s { sPgm_a = (f,[])})))
1463 , Flag "pgml" (hasArg (\f -> alterSettings (\s -> s { sPgm_l = (f,[])})))
1464 , Flag "pgmdll" (hasArg (\f -> alterSettings (\s -> s { sPgm_dll = (f,[])})))
1465 , Flag "pgmwindres" (hasArg (\f -> alterSettings (\s -> s { sPgm_windres = f})))
1466
1467 -- need to appear before -optl/-opta to be parsed as LLVM flags.
1468 , Flag "optlo" (hasArg (\f -> alterSettings (\s -> s { sOpt_lo = f : sOpt_lo s})))
1469 , Flag "optlc" (hasArg (\f -> alterSettings (\s -> s { sOpt_lc = f : sOpt_lc s})))
1470 , Flag "optL" (hasArg (\f -> alterSettings (\s -> s { sOpt_L = f : sOpt_L s})))
1471 , Flag "optP" (hasArg addOptP)
1472 , Flag "optF" (hasArg (\f -> alterSettings (\s -> s { sOpt_F = f : sOpt_F s})))
1473 , Flag "optc" (hasArg (\f -> alterSettings (\s -> s { sOpt_c = f : sOpt_c s})))
1474 , Flag "optm" (HasArg (\_ -> addWarn "The -optm flag does nothing; it will be removed in a future GHC release"))
1475 , Flag "opta" (hasArg (\f -> alterSettings (\s -> s { sOpt_a = f : sOpt_a s})))
1476 , Flag "optl" (hasArg addOptl)
1477 , Flag "optwindres" (hasArg (\f -> alterSettings (\s -> s { sOpt_windres = f : sOpt_windres s})))
1478
1479 , Flag "split-objs"
1480 (NoArg (if can_split
1481 then setDynFlag Opt_SplitObjs
1482 else addWarn "ignoring -fsplit-objs"))
1483
1484 -------- ghc -M -----------------------------------------------------
1485 , Flag "dep-suffix" (hasArg addDepSuffix)
1486 , Flag "optdep-s" (hasArgDF addDepSuffix "Use -dep-suffix instead")
1487 , Flag "dep-makefile" (hasArg setDepMakefile)
1488 , Flag "optdep-f" (hasArgDF setDepMakefile "Use -dep-makefile instead")
1489 , Flag "optdep-w" (NoArg (deprecate "doesn't do anything"))
1490 , Flag "include-pkg-deps" (noArg (setDepIncludePkgDeps True))
1491 , Flag "optdep--include-prelude" (noArgDF (setDepIncludePkgDeps True) "Use -include-pkg-deps instead")
1492 , Flag "optdep--include-pkg-deps" (noArgDF (setDepIncludePkgDeps True) "Use -include-pkg-deps instead")
1493 , Flag "exclude-module" (hasArg addDepExcludeMod)
1494 , Flag "optdep--exclude-module" (hasArgDF addDepExcludeMod "Use -exclude-module instead")
1495 , Flag "optdep-x" (hasArgDF addDepExcludeMod "Use -exclude-module instead")
1496
1497 -------- Linking ----------------------------------------------------
1498 , Flag "no-link" (noArg (\d -> d{ ghcLink=NoLink }))
1499 , Flag "shared" (noArg (\d -> d{ ghcLink=LinkDynLib }))
1500 , Flag "dynload" (hasArg parseDynLibLoaderMode)
1501 , Flag "dylib-install-name" (hasArg setDylibInstallName)
1502
1503 ------- Libraries ---------------------------------------------------
1504 , Flag "L" (Prefix addLibraryPath)
1505 , Flag "l" (hasArg (addOptl . ("-l" ++)))
1506
1507 ------- Frameworks --------------------------------------------------
1508 -- -framework-path should really be -F ...
1509 , Flag "framework-path" (HasArg addFrameworkPath)
1510 , Flag "framework" (hasArg addCmdlineFramework)
1511
1512 ------- Output Redirection ------------------------------------------
1513 , Flag "odir" (hasArg setObjectDir)
1514 , Flag "o" (sepArg (setOutputFile . Just))
1515 , Flag "ohi" (hasArg (setOutputHi . Just ))
1516 , Flag "osuf" (hasArg setObjectSuf)
1517 , Flag "hcsuf" (hasArg setHcSuf)
1518 , Flag "hisuf" (hasArg setHiSuf)
1519 , Flag "hidir" (hasArg setHiDir)
1520 , Flag "tmpdir" (hasArg setTmpDir)
1521 , Flag "stubdir" (hasArg setStubDir)
1522 , Flag "dumpdir" (hasArg setDumpDir)
1523 , Flag "outputdir" (hasArg setOutputDir)
1524 , Flag "ddump-file-prefix" (hasArg (setDumpPrefixForce . Just))
1525
1526 ------- Keeping temporary files -------------------------------------
1527 -- These can be singular (think ghc -c) or plural (think ghc --make)
1528 , Flag "keep-hc-file" (NoArg (setDynFlag Opt_KeepHcFiles))
1529 , Flag "keep-hc-files" (NoArg (setDynFlag Opt_KeepHcFiles))
1530 , Flag "keep-s-file" (NoArg (setDynFlag Opt_KeepSFiles))
1531 , Flag "keep-s-files" (NoArg (setDynFlag Opt_KeepSFiles))
1532 , Flag "keep-raw-s-file" (NoArg (addWarn "The -keep-raw-s-file flag does nothing; it will be removed in a future GHC release"))
1533 , Flag "keep-raw-s-files" (NoArg (addWarn "The -keep-raw-s-files flag does nothing; it will be removed in a future GHC release"))
1534 , Flag "keep-llvm-file" (NoArg (do setObjTarget HscLlvm
1535 setDynFlag Opt_KeepLlvmFiles))
1536 , Flag "keep-llvm-files" (NoArg (do setObjTarget HscLlvm
1537 setDynFlag Opt_KeepLlvmFiles))
1538 -- This only makes sense as plural
1539 , Flag "keep-tmp-files" (NoArg (setDynFlag Opt_KeepTmpFiles))
1540
1541 ------- Miscellaneous ----------------------------------------------
1542 , Flag "no-auto-link-packages" (NoArg (unSetDynFlag Opt_AutoLinkPackages))
1543 , Flag "no-hs-main" (NoArg (setDynFlag Opt_NoHsMain))
1544 , Flag "with-rtsopts" (HasArg setRtsOpts)
1545 , Flag "rtsopts" (NoArg (setRtsOptsEnabled RtsOptsAll))
1546 , Flag "rtsopts=all" (NoArg (setRtsOptsEnabled RtsOptsAll))
1547 , Flag "rtsopts=some" (NoArg (setRtsOptsEnabled RtsOptsSafeOnly))
1548 , Flag "rtsopts=none" (NoArg (setRtsOptsEnabled RtsOptsNone))
1549 , Flag "no-rtsopts" (NoArg (setRtsOptsEnabled RtsOptsNone))
1550 , Flag "main-is" (SepArg setMainIs)
1551 , Flag "haddock" (NoArg (setDynFlag Opt_Haddock))
1552 , Flag "haddock-opts" (hasArg addHaddockOpts)
1553 , Flag "hpcdir" (SepArg setOptHpcDir)
1554 , Flag "ghci-script" (hasArg addGhciScript)
1555
1556 ------- recompilation checker --------------------------------------
1557 , Flag "recomp" (NoArg (do unSetDynFlag Opt_ForceRecomp
1558 deprecate "Use -fno-force-recomp instead"))
1559 , Flag "no-recomp" (NoArg (do setDynFlag Opt_ForceRecomp
1560 deprecate "Use -fforce-recomp instead"))
1561
1562 ------ HsCpp opts ---------------------------------------------------
1563 , Flag "D" (AnySuffix (upd . addOptP))
1564 , Flag "U" (AnySuffix (upd . addOptP))
1565
1566 ------- Include/Import Paths ----------------------------------------
1567 , Flag "I" (Prefix addIncludePath)
1568 , Flag "i" (OptPrefix addImportPath)
1569
1570 ------ Debugging ----------------------------------------------------
1571 , Flag "dstg-stats" (NoArg (setDynFlag Opt_StgStats))
1572
1573 , Flag "ddump-cmm" (setDumpFlag Opt_D_dump_cmm)
1574 , Flag "ddump-raw-cmm" (setDumpFlag Opt_D_dump_raw_cmm)
1575 , Flag "ddump-cmmz" (setDumpFlag Opt_D_dump_cmmz)
1576 , Flag "ddump-cmmz-pretty" (setDumpFlag Opt_D_dump_cmmz_pretty)
1577 , Flag "ddump-cmmz-cbe" (setDumpFlag Opt_D_dump_cmmz_cbe)
1578 , Flag "ddump-cmmz-spills" (setDumpFlag Opt_D_dump_cmmz_spills)
1579 , Flag "ddump-cmmz-proc" (setDumpFlag Opt_D_dump_cmmz_proc)
1580 , Flag "ddump-cmmz-rewrite" (setDumpFlag Opt_D_dump_cmmz_rewrite)
1581 , Flag "ddump-cmmz-dead" (setDumpFlag Opt_D_dump_cmmz_dead)
1582 , Flag "ddump-cmmz-stub" (setDumpFlag Opt_D_dump_cmmz_stub)
1583 , Flag "ddump-cmmz-sp" (setDumpFlag Opt_D_dump_cmmz_sp)
1584 , Flag "ddump-cmmz-procmap" (setDumpFlag Opt_D_dump_cmmz_procmap)
1585 , Flag "ddump-cmmz-split" (setDumpFlag Opt_D_dump_cmmz_split)
1586 , Flag "ddump-cmmz-lower" (setDumpFlag Opt_D_dump_cmmz_lower)
1587 , Flag "ddump-cmmz-info" (setDumpFlag Opt_D_dump_cmmz_info)
1588 , Flag "ddump-cmmz-cafs" (setDumpFlag Opt_D_dump_cmmz_cafs)
1589 , Flag "ddump-core-stats" (setDumpFlag Opt_D_dump_core_stats)
1590 , Flag "ddump-cps-cmm" (setDumpFlag Opt_D_dump_cps_cmm)
1591 , Flag "ddump-cvt-cmm" (setDumpFlag Opt_D_dump_cvt_cmm)
1592 , Flag "ddump-asm" (setDumpFlag Opt_D_dump_asm)
1593 , Flag "ddump-asm-native" (setDumpFlag Opt_D_dump_asm_native)
1594 , Flag "ddump-asm-liveness" (setDumpFlag Opt_D_dump_asm_liveness)
1595 , Flag "ddump-asm-coalesce" (setDumpFlag Opt_D_dump_asm_coalesce)
1596 , Flag "ddump-asm-regalloc" (setDumpFlag Opt_D_dump_asm_regalloc)
1597 , Flag "ddump-asm-conflicts" (setDumpFlag Opt_D_dump_asm_conflicts)
1598 , Flag "ddump-asm-regalloc-stages" (setDumpFlag Opt_D_dump_asm_regalloc_stages)
1599 , Flag "ddump-asm-stats" (setDumpFlag Opt_D_dump_asm_stats)
1600 , Flag "ddump-asm-expanded" (setDumpFlag Opt_D_dump_asm_expanded)
1601 , Flag "ddump-llvm" (NoArg (do setObjTarget HscLlvm
1602 setDumpFlag' Opt_D_dump_llvm))
1603 , Flag "ddump-cpranal" (setDumpFlag Opt_D_dump_cpranal)
1604 , Flag "ddump-deriv" (setDumpFlag Opt_D_dump_deriv)
1605 , Flag "ddump-ds" (setDumpFlag Opt_D_dump_ds)
1606 , Flag "ddump-flatC" (setDumpFlag Opt_D_dump_flatC)
1607 , Flag "ddump-foreign" (setDumpFlag Opt_D_dump_foreign)
1608 , Flag "ddump-inlinings" (setDumpFlag Opt_D_dump_inlinings)
1609 , Flag "ddump-rule-firings" (setDumpFlag Opt_D_dump_rule_firings)
1610 , Flag "ddump-rule-rewrites" (setDumpFlag Opt_D_dump_rule_rewrites)
1611 , Flag "ddump-occur-anal" (setDumpFlag Opt_D_dump_occur_anal)
1612 , Flag "ddump-parsed" (setDumpFlag Opt_D_dump_parsed)
1613 , Flag "ddump-rn" (setDumpFlag Opt_D_dump_rn)
1614 , Flag "ddump-core-pipeline" (setDumpFlag Opt_D_dump_core_pipeline)
1615 , Flag "ddump-simpl" (setDumpFlag Opt_D_dump_simpl)
1616 , Flag "ddump-simpl-iterations" (setDumpFlag Opt_D_dump_simpl_iterations)
1617 , Flag "ddump-simpl-phases" (OptPrefix setDumpSimplPhases)
1618 , Flag "ddump-spec" (setDumpFlag Opt_D_dump_spec)
1619 , Flag "ddump-prep" (setDumpFlag Opt_D_dump_prep)
1620 , Flag "ddump-stg" (setDumpFlag Opt_D_dump_stg)
1621 , Flag "ddump-stranal" (setDumpFlag Opt_D_dump_stranal)
1622 , Flag "ddump-tc" (setDumpFlag Opt_D_dump_tc)
1623 , Flag "ddump-types" (setDumpFlag Opt_D_dump_types)
1624 , Flag "ddump-rules" (setDumpFlag Opt_D_dump_rules)
1625 , Flag "ddump-cse" (setDumpFlag Opt_D_dump_cse)
1626 , Flag "ddump-worker-wrapper" (setDumpFlag Opt_D_dump_worker_wrapper)
1627 , Flag "ddump-rn-trace" (setDumpFlag Opt_D_dump_rn_trace)
1628 , Flag "ddump-if-trace" (setDumpFlag Opt_D_dump_if_trace)
1629 , Flag "ddump-cs-trace" (setDumpFlag Opt_D_dump_cs_trace)
1630 , Flag "ddump-tc-trace" (setDumpFlag Opt_D_dump_tc_trace)
1631 , Flag "ddump-vt-trace" (setDumpFlag Opt_D_dump_vt_trace)
1632 , Flag "ddump-splices" (setDumpFlag Opt_D_dump_splices)
1633 , Flag "ddump-rn-stats" (setDumpFlag Opt_D_dump_rn_stats)
1634 , Flag "ddump-opt-cmm" (setDumpFlag Opt_D_dump_opt_cmm)
1635 , Flag "ddump-simpl-stats" (setDumpFlag Opt_D_dump_simpl_stats)
1636 , Flag "ddump-bcos" (setDumpFlag Opt_D_dump_BCOs)
1637 , Flag "dsource-stats" (setDumpFlag Opt_D_source_stats)
1638 , Flag "dverbose-core2core" (NoArg (do setVerbosity (Just 2)
1639 setVerboseCore2Core))
1640 , Flag "dverbose-stg2stg" (setDumpFlag Opt_D_verbose_stg2stg)
1641 , Flag "ddump-hi" (setDumpFlag Opt_D_dump_hi)
1642 , Flag "ddump-minimal-imports" (setDumpFlag Opt_D_dump_minimal_imports)
1643 , Flag "ddump-vect" (setDumpFlag Opt_D_dump_vect)
1644 , Flag "ddump-avoid-vect" (setDumpFlag Opt_D_dump_avoid_vect)
1645 , Flag "ddump-hpc" (setDumpFlag Opt_D_dump_ticked) -- back compat
1646 , Flag "ddump-ticked" (setDumpFlag Opt_D_dump_ticked)
1647 , Flag "ddump-mod-cycles" (setDumpFlag Opt_D_dump_mod_cycles)
1648 , Flag "ddump-view-pattern-commoning" (setDumpFlag Opt_D_dump_view_pattern_commoning)
1649 , Flag "ddump-to-file" (setDumpFlag Opt_DumpToFile)
1650 , Flag "ddump-hi-diffs" (setDumpFlag Opt_D_dump_hi_diffs)
1651 , Flag "ddump-rtti" (setDumpFlag Opt_D_dump_rtti)
1652 , Flag "dcore-lint" (NoArg (setDynFlag Opt_DoCoreLinting))
1653 , Flag "dstg-lint" (NoArg (setDynFlag Opt_DoStgLinting))
1654 , Flag "dcmm-lint" (NoArg (setDynFlag Opt_DoCmmLinting))
1655 , Flag "dasm-lint" (NoArg (setDynFlag Opt_DoAsmLinting))
1656 , Flag "dshow-passes" (NoArg (do forceRecompile
1657 setVerbosity $ Just 2))
1658 , Flag "dfaststring-stats" (NoArg (setDynFlag Opt_D_faststring_stats))
1659 , Flag "dno-llvm-mangler" (NoArg (setDynFlag Opt_NoLlvmMangler)) -- hidden flag
1660
1661 ------ Machine dependant (-m<blah>) stuff ---------------------------
1662
1663 , Flag "monly-2-regs" (NoArg (addWarn "The -monly-2-regs flag does nothing; it will be removed in a future GHC release"))
1664 , Flag "monly-3-regs" (NoArg (addWarn "The -monly-3-regs flag does nothing; it will be removed in a future GHC release"))
1665 , Flag "monly-4-regs" (NoArg (addWarn "The -monly-4-regs flag does nothing; it will be removed in a future GHC release"))
1666 , Flag "msse2" (NoArg (setDynFlag Opt_SSE2))
1667 , Flag "msse4.2" (NoArg (setDynFlag Opt_SSE4_2))
1668
1669 ------ Warning opts -------------------------------------------------
1670 , Flag "W" (NoArg (mapM_ setWarningFlag minusWOpts))
1671 , Flag "Werror" (NoArg (setDynFlag Opt_WarnIsError))
1672 , Flag "Wwarn" (NoArg (unSetDynFlag Opt_WarnIsError))
1673 , Flag "Wall" (NoArg (mapM_ setWarningFlag minusWallOpts))
1674 , Flag "Wnot" (NoArg (do upd (\dfs -> dfs {warningFlags = IntSet.empty})
1675 deprecate "Use -w instead"))
1676 , Flag "w" (NoArg (upd (\dfs -> dfs {warningFlags = IntSet.empty})))
1677
1678 ------ Plugin flags ------------------------------------------------
1679 , Flag "fplugin-opt" (hasArg addPluginModuleNameOption)
1680 , Flag "fplugin" (hasArg addPluginModuleName)
1681
1682 ------ Optimisation flags ------------------------------------------
1683 , Flag "O" (noArgM (setOptLevel 1))
1684 , Flag "Onot" (noArgM (\dflags -> do deprecate "Use -O0 instead"
1685 setOptLevel 0 dflags))
1686 , Flag "Odph" (noArgM setDPHOpt)
1687 , Flag "O" (optIntSuffixM (\mb_n -> setOptLevel (mb_n `orElse` 1)))
1688 -- If the number is missing, use 1
1689
1690 , Flag "fsimplifier-phases" (intSuffix (\n d -> d{ simplPhases = n }))
1691 , Flag "fmax-simplifier-iterations" (intSuffix (\n d -> d{ maxSimplIterations = n }))
1692 , Flag "fsimpl-tick-factor" (intSuffix (\n d -> d{ simplTickFactor = n }))
1693 , Flag "fspec-constr-threshold" (intSuffix (\n d -> d{ specConstrThreshold = Just n }))
1694 , Flag "fno-spec-constr-threshold" (noArg (\d -> d{ specConstrThreshold = Nothing }))
1695 , Flag "fspec-constr-count" (intSuffix (\n d -> d{ specConstrCount = Just n }))
1696 , Flag "fno-spec-constr-count" (noArg (\d -> d{ specConstrCount = Nothing }))
1697 , Flag "fliberate-case-threshold" (intSuffix (\n d -> d{ liberateCaseThreshold = Just n }))
1698 , Flag "fno-liberate-case-threshold" (noArg (\d -> d{ liberateCaseThreshold = Nothing }))
1699 , Flag "frule-check" (sepArg (\s d -> d{ ruleCheck = Just s }))
1700 , Flag "fcontext-stack" (intSuffix (\n d -> d{ ctxtStkDepth = n }))
1701 , Flag "fstrictness-before" (intSuffix (\n d -> d{ strictnessBefore = n : strictnessBefore d }))
1702 , Flag "ffloat-lam-args" (intSuffix (\n d -> d{ floatLamArgs = Just n }))
1703 , Flag "ffloat-all-lams" (noArg (\d -> d{ floatLamArgs = Nothing }))
1704
1705 ------ Profiling ----------------------------------------------------
1706
1707 -- OLD profiling flags
1708 , Flag "auto-all" (noArg (\d -> d { profAuto = ProfAutoAll } ))
1709 , Flag "no-auto-all" (noArg (\d -> d { profAuto = NoProfAuto } ))
1710 , Flag "auto" (noArg (\d -> d { profAuto = ProfAutoExports } ))
1711 , Flag "no-auto" (noArg (\d -> d { profAuto = NoProfAuto } ))
1712 , Flag "caf-all" (NoArg (setDynFlag Opt_AutoSccsOnIndividualCafs))
1713 , Flag "no-caf-all" (NoArg (unSetDynFlag Opt_AutoSccsOnIndividualCafs))
1714
1715 -- NEW profiling flags
1716 , Flag "fprof-auto" (noArg (\d -> d { profAuto = ProfAutoAll } ))
1717 , Flag "fprof-auto-top" (noArg (\d -> d { profAuto = ProfAutoTop } ))
1718 , Flag "fprof-auto-exported" (noArg (\d -> d { profAuto = ProfAutoExports } ))
1719 , Flag "fprof-auto-calls" (noArg (\d -> d { profAuto = ProfAutoCalls } ))
1720 , Flag "fno-prof-auto" (noArg (\d -> d { profAuto = NoProfAuto } ))
1721
1722 ------ Compiler flags -----------------------------------------------
1723
1724 , Flag "fasm" (NoArg (setObjTarget HscAsm))
1725 , Flag "fvia-c" (NoArg
1726 (addWarn "The -fvia-c flag does nothing; it will be removed in a future GHC release"))
1727 , Flag "fvia-C" (NoArg
1728 (addWarn "The -fvia-C flag does nothing; it will be removed in a future GHC release"))
1729 , Flag "fllvm" (NoArg (setObjTarget HscLlvm))
1730
1731 , Flag "fno-code" (NoArg (do upd $ \d -> d{ ghcLink=NoLink }
1732 setTarget HscNothing))
1733 , Flag "fbyte-code" (NoArg (setTarget HscInterpreted))
1734 , Flag "fobject-code" (NoArg (setTarget defaultHscTarget))
1735 , Flag "fglasgow-exts" (NoArg (enableGlasgowExts >> deprecate "Use individual extensions instead"))
1736 , Flag "fno-glasgow-exts" (NoArg (disableGlasgowExts >> deprecate "Use individual extensions instead"))
1737
1738 ------ Safe Haskell flags -------------------------------------------
1739 , Flag "fpackage-trust" (NoArg setPackageTrust)
1740 , Flag "fno-safe-infer" (NoArg (setSafeHaskell Sf_None))
1741 ]
1742 ++ map (mkFlag turnOn "f" setDynFlag ) fFlags
1743 ++ map (mkFlag turnOff "fno-" unSetDynFlag) fFlags
1744 ++ map (mkFlag turnOn "f" setWarningFlag ) fWarningFlags
1745 ++ map (mkFlag turnOff "fno-" unSetWarningFlag) fWarningFlags
1746 ++ map (mkFlag turnOn "f" setExtensionFlag ) fLangFlags
1747 ++ map (mkFlag turnOff "fno-" unSetExtensionFlag) fLangFlags
1748 ++ map (mkFlag turnOn "X" setExtensionFlag ) xFlags
1749 ++ map (mkFlag turnOff "XNo" unSetExtensionFlag) xFlags
1750 ++ map (mkFlag turnOn "X" setLanguage) languageFlags
1751 ++ map (mkFlag turnOn "X" setSafeHaskell) safeHaskellFlags
1752 ++ [ Flag "XGenerics" (NoArg (deprecate "it does nothing; look into -XDefaultSignatures and -XDeriveGeneric for generic programming support."))
1753 , Flag "XNoGenerics" (NoArg (deprecate "it does nothing; look into -XDefaultSignatures and -XDeriveGeneric for generic programming support.")) ]
1754
1755 package_flags :: [Flag (CmdLineP DynFlags)]
1756 package_flags = [
1757 ------- Packages ----------------------------------------------------
1758 Flag "package-db" (HasArg (addPkgConfRef . PkgConfFile))
1759 , Flag "clear-package-db" (NoArg clearPkgConf)
1760 , Flag "no-global-package-db" (NoArg removeGlobalPkgConf)
1761 , Flag "no-user-package-db" (NoArg removeUserPkgConf)
1762 , Flag "global-package-db" (NoArg (addPkgConfRef GlobalPkgConf))
1763 , Flag "user-package-db" (NoArg (addPkgConfRef UserPkgConf))
1764
1765 , Flag "package-name" (hasArg setPackageName)
1766 , Flag "package-id" (HasArg exposePackageId)
1767 , Flag "package" (HasArg exposePackage)
1768 , Flag "hide-package" (HasArg hidePackage)
1769 , Flag "hide-all-packages" (NoArg (setDynFlag Opt_HideAllPackages))
1770 , Flag "ignore-package" (HasArg ignorePackage)
1771 , Flag "syslib" (HasArg (\s -> do exposePackage s
1772 deprecate "Use -package instead"))
1773 , Flag "distrust-all-packages" (NoArg (setDynFlag Opt_DistrustAllPackages))
1774 , Flag "trust" (HasArg trustPackage)
1775 , Flag "distrust" (HasArg distrustPackage)
1776 ]
1777
1778 type TurnOnFlag = Bool -- True <=> we are turning the flag on
1779 -- False <=> we are turning the flag off
1780 turnOn :: TurnOnFlag; turnOn = True
1781 turnOff :: TurnOnFlag; turnOff = False
1782
1783 type FlagSpec flag
1784 = ( String -- Flag in string form
1785 , flag -- Flag in internal form
1786 , TurnOnFlag -> DynP ()) -- Extra action to run when the flag is found
1787 -- Typically, emit a warning or error
1788
1789 mkFlag :: TurnOnFlag -- ^ True <=> it should be turned on
1790 -> String -- ^ The flag prefix
1791 -> (flag -> DynP ()) -- ^ What to do when the flag is found
1792 -> FlagSpec flag -- ^ Specification of this particular flag
1793 -> Flag (CmdLineP DynFlags)
1794 mkFlag turn_on flagPrefix f (name, flag, extra_action)
1795 = Flag (flagPrefix ++ name) (NoArg (f flag >> extra_action turn_on))
1796
1797 deprecatedForExtension :: String -> TurnOnFlag -> DynP ()
1798 deprecatedForExtension lang turn_on
1799 = deprecate ("use -X" ++ flag ++ " or pragma {-# LANGUAGE " ++ flag ++ " #-} instead")
1800 where
1801 flag | turn_on = lang
1802 | otherwise = "No"++lang
1803
1804 useInstead :: String -> TurnOnFlag -> DynP ()
1805 useInstead flag turn_on
1806 = deprecate ("Use -f" ++ no ++ flag ++ " instead")
1807 where
1808 no = if turn_on then "" else "no-"
1809
1810 nop :: TurnOnFlag -> DynP ()
1811 nop _ = return ()
1812
1813 -- | These @-f\<blah\>@ flags can all be reversed with @-fno-\<blah\>@
1814 fWarningFlags :: [FlagSpec WarningFlag]
1815 fWarningFlags = [
1816 ( "warn-dodgy-foreign-imports", Opt_WarnDodgyForeignImports, nop ),
1817 ( "warn-dodgy-exports", Opt_WarnDodgyExports, nop ),
1818 ( "warn-dodgy-imports", Opt_WarnDodgyImports, nop ),
1819 ( "warn-duplicate-exports", Opt_WarnDuplicateExports, nop ),
1820 ( "warn-hi-shadowing", Opt_WarnHiShadows, nop ),
1821 ( "warn-implicit-prelude", Opt_WarnImplicitPrelude, nop ),
1822 ( "warn-incomplete-patterns", Opt_WarnIncompletePatterns, nop ),
1823 ( "warn-incomplete-uni-patterns", Opt_WarnIncompleteUniPatterns, nop ),
1824 ( "warn-incomplete-record-updates", Opt_WarnIncompletePatternsRecUpd, nop ),
1825 ( "warn-missing-fields", Opt_WarnMissingFields, nop ),
1826 ( "warn-missing-import-lists", Opt_WarnMissingImportList, nop ),
1827 ( "warn-missing-methods", Opt_WarnMissingMethods, nop ),
1828 ( "warn-missing-signatures", Opt_WarnMissingSigs, nop ),
1829 ( "warn-missing-local-sigs", Opt_WarnMissingLocalSigs, nop ),
1830 ( "warn-name-shadowing", Opt_WarnNameShadowing, nop ),
1831 ( "warn-overlapping-patterns", Opt_WarnOverlappingPatterns, nop ),
1832 ( "warn-type-defaults", Opt_WarnTypeDefaults, nop ),
1833 ( "warn-monomorphism-restriction", Opt_WarnMonomorphism, nop ),
1834 ( "warn-unused-binds", Opt_WarnUnusedBinds, nop ),
1835 ( "warn-unused-imports", Opt_WarnUnusedImports, nop ),
1836 ( "warn-unused-matches", Opt_WarnUnusedMatches, nop ),
1837 ( "warn-warnings-deprecations", Opt_WarnWarningsDeprecations, nop ),
1838 ( "warn-deprecations", Opt_WarnWarningsDeprecations, nop ),
1839 ( "warn-deprecated-flags", Opt_WarnDeprecatedFlags, nop ),
1840 ( "warn-orphans", Opt_WarnOrphans, nop ),
1841 ( "warn-identities", Opt_WarnIdentities, nop ),
1842 ( "warn-auto-orphans", Opt_WarnAutoOrphans, nop ),
1843 ( "warn-tabs", Opt_WarnTabs, nop ),
1844 ( "warn-unrecognised-pragmas", Opt_WarnUnrecognisedPragmas, nop ),
1845 ( "warn-lazy-unlifted-bindings", Opt_WarnLazyUnliftedBindings, nop ),
1846 ( "warn-unused-do-bind", Opt_WarnUnusedDoBind, nop ),
1847 ( "warn-wrong-do-bind", Opt_WarnWrongDoBind, nop ),
1848 ( "warn-alternative-layout-rule-transitional", Opt_WarnAlternativeLayoutRuleTransitional, nop ),
1849 ( "warn-unsafe", Opt_WarnUnsafe, setWarnUnsafe ),
1850 ( "warn-safe", Opt_WarnSafe, setWarnSafe ),
1851 ( "warn-pointless-pragmas", Opt_WarnPointlessPragmas, nop ),
1852 ( "warn-unsupported-calling-conventions", Opt_WarnUnsupportedCallingConventions, nop ) ]
1853
1854 -- | These @-f\<blah\>@ flags can all be reversed with @-fno-\<blah\>@
1855 fFlags :: [FlagSpec DynFlag]
1856 fFlags = [
1857 ( "print-explicit-foralls", Opt_PrintExplicitForalls, nop ),
1858 ( "strictness", Opt_Strictness, nop ),
1859 ( "specialise", Opt_Specialise, nop ),
1860 ( "float-in", Opt_FloatIn, nop ),
1861 ( "static-argument-transformation", Opt_StaticArgumentTransformation, nop ),
1862 ( "full-laziness", Opt_FullLaziness, nop ),
1863 ( "liberate-case", Opt_LiberateCase, nop ),
1864 ( "spec-constr", Opt_SpecConstr, nop ),
1865 ( "cse", Opt_CSE, nop ),
1866 ( "pedantic-bottoms", Opt_PedanticBottoms, nop ),
1867 ( "ignore-interface-pragmas", Opt_IgnoreInterfacePragmas, nop ),
1868 ( "omit-interface-pragmas", Opt_OmitInterfacePragmas, nop ),
1869 ( "expose-all-unfoldings", Opt_ExposeAllUnfoldings, nop ),
1870 ( "do-lambda-eta-expansion", Opt_DoLambdaEtaExpansion, nop ),
1871 ( "ignore-asserts", Opt_IgnoreAsserts, nop ),
1872 ( "do-eta-reduction", Opt_DoEtaReduction, nop ),
1873 ( "case-merge", Opt_CaseMerge, nop ),
1874 ( "unbox-strict-fields", Opt_UnboxStrictFields, nop ),
1875 ( "dicts-cheap", Opt_DictsCheap, nop ),
1876 ( "excess-precision", Opt_ExcessPrecision, nop ),
1877 ( "eager-blackholing", Opt_EagerBlackHoling, nop ),
1878 ( "print-bind-result", Opt_PrintBindResult, nop ),
1879 ( "force-recomp", Opt_ForceRecomp, nop ),
1880 ( "hpc-no-auto", Opt_Hpc_No_Auto, nop ),
1881 ( "rewrite-rules", Opt_EnableRewriteRules, useInstead "enable-rewrite-rules" ),
1882 ( "enable-rewrite-rules", Opt_EnableRewriteRules, nop ),
1883 ( "break-on-exception", Opt_BreakOnException, nop ),
1884 ( "break-on-error", Opt_BreakOnError, nop ),
1885 ( "print-evld-with-show", Opt_PrintEvldWithShow, nop ),
1886 ( "print-bind-contents", Opt_PrintBindContents, nop ),
1887 ( "run-cps", Opt_RunCPS, nop ),
1888 ( "run-cpsz", Opt_RunCPSZ, nop ),
1889 ( "new-codegen", Opt_TryNewCodeGen, nop ),
1890 ( "vectorise", Opt_Vectorise, nop ),
1891 ( "avoid-vect", Opt_AvoidVect, nop ),
1892 ( "regs-graph", Opt_RegsGraph, nop ),
1893 ( "regs-iterative", Opt_RegsIterative, nop ),
1894 ( "llvm-tbaa", Opt_LlvmTBAA, nop), -- hidden flag
1895 ( "regs-liveness", Opt_RegLiveness, nop), -- hidden flag
1896 ( "gen-manifest", Opt_GenManifest, nop ),
1897 ( "embed-manifest", Opt_EmbedManifest, nop ),
1898 ( "ext-core", Opt_EmitExternalCore, nop ),
1899 ( "shared-implib", Opt_SharedImplib, nop ),
1900 ( "ghci-sandbox", Opt_GhciSandbox, nop ),
1901 ( "ghci-history", Opt_GhciHistory, nop ),
1902 ( "helpful-errors", Opt_HelpfulErrors, nop ),
1903 ( "defer-type-errors", Opt_DeferTypeErrors, nop ),
1904 ( "building-cabal-package", Opt_BuildingCabalPackage, nop ),
1905 ( "implicit-import-qualified", Opt_ImplicitImportQualified, nop ),
1906 ( "prof-count-entries", Opt_ProfCountEntries, nop ),
1907 ( "prof-cafs", Opt_AutoSccsOnIndividualCafs, nop )
1908 ]
1909
1910 -- | These @-f\<blah\>@ flags can all be reversed with @-fno-\<blah\>@
1911 fLangFlags :: [FlagSpec ExtensionFlag]
1912 fLangFlags = [
1913 ( "th", Opt_TemplateHaskell,
1914 deprecatedForExtension "TemplateHaskell" >> checkTemplateHaskellOk ),
1915 ( "fi", Opt_ForeignFunctionInterface,
1916 deprecatedForExtension "ForeignFunctionInterface" ),
1917 ( "ffi", Opt_ForeignFunctionInterface,
1918 deprecatedForExtension "ForeignFunctionInterface" ),
1919 ( "arrows", Opt_Arrows,
1920 deprecatedForExtension "Arrows" ),
1921 ( "implicit-prelude", Opt_ImplicitPrelude,
1922 deprecatedForExtension "ImplicitPrelude" ),
1923 ( "bang-patterns", Opt_BangPatterns,
1924 deprecatedForExtension "BangPatterns" ),
1925 ( "monomorphism-restriction", Opt_MonomorphismRestriction,
1926 deprecatedForExtension "MonomorphismRestriction" ),
1927 ( "mono-pat-binds", Opt_MonoPatBinds,
1928 deprecatedForExtension "MonoPatBinds" ),
1929 ( "extended-default-rules", Opt_ExtendedDefaultRules,
1930 deprecatedForExtension "ExtendedDefaultRules" ),
1931 ( "implicit-params", Opt_ImplicitParams,
1932 deprecatedForExtension "ImplicitParams" ),
1933 ( "scoped-type-variables", Opt_ScopedTypeVariables,
1934 deprecatedForExtension "ScopedTypeVariables" ),
1935 ( "parr", Opt_ParallelArrays,
1936 deprecatedForExtension "ParallelArrays" ),
1937 ( "PArr", Opt_ParallelArrays,
1938 deprecatedForExtension "ParallelArrays" ),
1939 ( "allow-overlapping-instances", Opt_OverlappingInstances,
1940 deprecatedForExtension "OverlappingInstances" ),
1941 ( "allow-undecidable-instances", Opt_UndecidableInstances,
1942 deprecatedForExtension "UndecidableInstances" ),
1943 ( "allow-incoherent-instances", Opt_IncoherentInstances,
1944 deprecatedForExtension "IncoherentInstances" )
1945 ]
1946
1947 supportedLanguages :: [String]
1948 supportedLanguages = [ name | (name, _, _) <- languageFlags ]
1949
1950 supportedLanguageOverlays :: [String]
1951 supportedLanguageOverlays = [ name | (name, _, _) <- safeHaskellFlags ]
1952
1953 supportedExtensions :: [String]
1954 supportedExtensions = [ name' | (name, _, _) <- xFlags, name' <- [name, "No" ++ name] ]
1955
1956 supportedLanguagesAndExtensions :: [String]
1957 supportedLanguagesAndExtensions =
1958 supportedLanguages ++ supportedLanguageOverlays ++ supportedExtensions
1959
1960 -- | These -X<blah> flags cannot be reversed with -XNo<blah>
1961 languageFlags :: [FlagSpec Language]
1962 languageFlags = [
1963 ( "Haskell98", Haskell98, nop ),
1964 ( "Haskell2010", Haskell2010, nop )
1965 ]
1966
1967 -- | These -X<blah> flags cannot be reversed with -XNo<blah>
1968 -- They are used to place hard requirements on what GHC Haskell language
1969 -- features can be used.
1970 safeHaskellFlags :: [FlagSpec SafeHaskellMode]
1971 safeHaskellFlags = [mkF Sf_Unsafe, mkF Sf_Trustworthy, mkF Sf_Safe]
1972 where mkF flag = (showPpr flag, flag, nop)
1973
1974 -- | These -X<blah> flags can all be reversed with -XNo<blah>
1975 xFlags :: [FlagSpec ExtensionFlag]
1976 xFlags = [
1977 ( "CPP", Opt_Cpp, nop ),
1978 ( "PostfixOperators", Opt_PostfixOperators, nop ),
1979 ( "TupleSections", Opt_TupleSections, nop ),
1980 ( "PatternGuards", Opt_PatternGuards, nop ),
1981 ( "UnicodeSyntax", Opt_UnicodeSyntax, nop ),
1982 ( "MagicHash", Opt_MagicHash, nop ),
1983 ( "PolymorphicComponents", Opt_PolymorphicComponents, nop ),
1984 ( "ExistentialQuantification", Opt_ExistentialQuantification, nop ),
1985 ( "KindSignatures", Opt_KindSignatures, nop ),
1986 ( "EmptyDataDecls", Opt_EmptyDataDecls, nop ),
1987 ( "ParallelListComp", Opt_ParallelListComp, nop ),
1988 ( "TransformListComp", Opt_TransformListComp, nop ),
1989 ( "MonadComprehensions", Opt_MonadComprehensions, nop),
1990 ( "ForeignFunctionInterface", Opt_ForeignFunctionInterface, nop ),
1991 ( "UnliftedFFITypes", Opt_UnliftedFFITypes, nop ),
1992 ( "InterruptibleFFI", Opt_InterruptibleFFI, nop ),
1993 ( "CApiFFI", Opt_CApiFFI, nop ),
1994 ( "GHCForeignImportPrim", Opt_GHCForeignImportPrim, nop ),
1995 ( "LiberalTypeSynonyms", Opt_LiberalTypeSynonyms, nop ),
1996 ( "Rank2Types", Opt_Rank2Types, nop ),
1997 ( "RankNTypes", Opt_RankNTypes, nop ),
1998 ( "ImpredicativeTypes", Opt_ImpredicativeTypes, nop),
1999 ( "TypeOperators", Opt_TypeOperators, nop ),
2000 ( "ExplicitNamespaces", Opt_ExplicitNamespaces, nop ),
2001 ( "RecursiveDo", Opt_RecursiveDo, -- Enables 'mdo'
2002 deprecatedForExtension "DoRec"),
2003 ( "DoRec", Opt_DoRec, nop ), -- Enables 'rec' keyword
2004 ( "Arrows", Opt_Arrows, nop ),
2005 ( "ParallelArrays", Opt_ParallelArrays, nop ),
2006 ( "TemplateHaskell", Opt_TemplateHaskell, checkTemplateHaskellOk ),
2007 ( "QuasiQuotes", Opt_QuasiQuotes, nop ),
2008 ( "ImplicitPrelude", Opt_ImplicitPrelude, nop ),
2009 ( "RecordWildCards", Opt_RecordWildCards, nop ),
2010 ( "NamedFieldPuns", Opt_RecordPuns, nop ),
2011 ( "RecordPuns", Opt_RecordPuns,
2012 deprecatedForExtension "NamedFieldPuns" ),
2013 ( "DisambiguateRecordFields", Opt_DisambiguateRecordFields, nop ),
2014 ( "OverloadedStrings", Opt_OverloadedStrings, nop ),
2015 ( "GADTs", Opt_GADTs, nop ),
2016 ( "GADTSyntax", Opt_GADTSyntax, nop ),
2017 ( "ViewPatterns", Opt_ViewPatterns, nop ),
2018 ( "TypeFamilies", Opt_TypeFamilies, nop ),
2019 ( "BangPatterns", Opt_BangPatterns, nop ),
2020 ( "MonomorphismRestriction", Opt_MonomorphismRestriction, nop ),
2021 ( "NPlusKPatterns", Opt_NPlusKPatterns, nop ),
2022 ( "DoAndIfThenElse", Opt_DoAndIfThenElse, nop ),
2023 ( "RebindableSyntax", Opt_RebindableSyntax, nop ),
2024 ( "ConstraintKinds", Opt_ConstraintKinds, nop ),
2025 ( "PolyKinds", Opt_PolyKinds, nop ),
2026 ( "DataKinds", Opt_DataKinds, nop ),
2027 ( "InstanceSigs", Opt_InstanceSigs, nop ),
2028 ( "MonoPatBinds", Opt_MonoPatBinds,
2029 \ turn_on -> when turn_on $ deprecate "Experimental feature now removed; has no effect" ),
2030 ( "ExplicitForAll", Opt_ExplicitForAll, nop ),
2031 ( "AlternativeLayoutRule", Opt_AlternativeLayoutRule, nop ),
2032 ( "AlternativeLayoutRuleTransitional",Opt_AlternativeLayoutRuleTransitional, nop ),
2033 ( "DatatypeContexts", Opt_DatatypeContexts,
2034 \ turn_on -> when turn_on $ deprecate "It was widely considered a misfeature, and has been removed from the Haskell language." ),
2035 ( "NondecreasingIndentation", Opt_NondecreasingIndentation, nop ),
2036 ( "RelaxedLayout", Opt_RelaxedLayout, nop ),
2037 ( "TraditionalRecordSyntax", Opt_TraditionalRecordSyntax, nop ),
2038 ( "MonoLocalBinds", Opt_MonoLocalBinds, nop ),
2039 ( "RelaxedPolyRec", Opt_RelaxedPolyRec,
2040 \ turn_on -> if not turn_on
2041 then deprecate "You can't turn off RelaxedPolyRec any more"
2042 else return () ),
2043 ( "ExtendedDefaultRules", Opt_ExtendedDefaultRules, nop ),
2044 ( "ImplicitParams", Opt_ImplicitParams, nop ),
2045 ( "ScopedTypeVariables", Opt_ScopedTypeVariables, nop ),
2046
2047 ( "PatternSignatures", Opt_ScopedTypeVariables,
2048 deprecatedForExtension "ScopedTypeVariables" ),
2049
2050 ( "UnboxedTuples", Opt_UnboxedTuples, nop ),
2051 ( "StandaloneDeriving", Opt_StandaloneDeriving, nop ),
2052 ( "DeriveDataTypeable", Opt_DeriveDataTypeable, nop ),
2053 ( "DeriveFunctor", Opt_DeriveFunctor, nop ),
2054 ( "DeriveTraversable", Opt_DeriveTraversable, nop ),
2055 ( "DeriveFoldable", Opt_DeriveFoldable, nop ),
2056 ( "DeriveGeneric", Opt_DeriveGeneric, nop ),
2057 ( "DefaultSignatures", Opt_DefaultSignatures, nop ),
2058 ( "TypeSynonymInstances", Opt_TypeSynonymInstances, nop ),
2059 ( "FlexibleContexts", Opt_FlexibleContexts, nop ),
2060 ( "FlexibleInstances", Opt_FlexibleInstances, nop ),
2061 ( "ConstrainedClassMethods", Opt_ConstrainedClassMethods, nop ),
2062 ( "MultiParamTypeClasses", Opt_MultiParamTypeClasses, nop ),
2063 ( "FunctionalDependencies", Opt_FunctionalDependencies, nop ),
2064 ( "GeneralizedNewtypeDeriving", Opt_GeneralizedNewtypeDeriving, setGenDeriving ),
2065 ( "OverlappingInstances", Opt_OverlappingInstances, nop ),
2066 ( "UndecidableInstances", Opt_UndecidableInstances, nop ),
2067 ( "IncoherentInstances", Opt_IncoherentInstances, nop ),
2068 ( "PackageImports", Opt_PackageImports, nop )
2069 ]
2070
2071 defaultFlags :: [DynFlag]
2072 defaultFlags
2073 = [ Opt_AutoLinkPackages,
2074
2075 Opt_SharedImplib,
2076
2077 #if GHC_DEFAULT_NEW_CODEGEN
2078 Opt_TryNewCodeGen,
2079 #endif
2080
2081 Opt_GenManifest,
2082 Opt_EmbedManifest,
2083 Opt_PrintBindContents,
2084 Opt_GhciSandbox,
2085 Opt_GhciHistory,
2086 Opt_HelpfulErrors,
2087 Opt_ProfCountEntries
2088 ]
2089
2090 ++ [f | (ns,f) <- optLevelFlags, 0 `elem` ns]
2091 -- The default -O0 options
2092
2093 impliedFlags :: [(ExtensionFlag, TurnOnFlag, ExtensionFlag)]
2094 impliedFlags
2095 = [ (Opt_RankNTypes, turnOn, Opt_ExplicitForAll)
2096 , (Opt_Rank2Types, turnOn, Opt_ExplicitForAll)
2097 , (Opt_ScopedTypeVariables, turnOn, Opt_ExplicitForAll)
2098 , (Opt_LiberalTypeSynonyms, turnOn, Opt_ExplicitForAll)
2099 , (Opt_ExistentialQuantification, turnOn, Opt_ExplicitForAll)
2100 , (Opt_PolymorphicComponents, turnOn, Opt_ExplicitForAll)
2101 , (Opt_FlexibleInstances, turnOn, Opt_TypeSynonymInstances)
2102 , (Opt_FunctionalDependencies, turnOn, Opt_MultiParamTypeClasses)
2103
2104 , (Opt_RebindableSyntax, turnOff, Opt_ImplicitPrelude) -- NB: turn off!
2105
2106 , (Opt_GADTs, turnOn, Opt_GADTSyntax)
2107 , (Opt_GADTs, turnOn, Opt_MonoLocalBinds)
2108 , (Opt_TypeFamilies, turnOn, Opt_MonoLocalBinds)
2109
2110 , (Opt_TypeFamilies, turnOn, Opt_KindSignatures) -- Type families use kind signatures
2111
2112 -- We turn this on so that we can export associated type
2113 -- type synonyms in subordinates (e.g. MyClass(type AssocType))
2114 , (Opt_TypeFamilies, turnOn, Opt_ExplicitNamespaces)
2115 , (Opt_TypeOperators, turnOn, Opt_ExplicitNamespaces)
2116
2117 , (Opt_ImpredicativeTypes, turnOn, Opt_RankNTypes)
2118
2119 -- Record wild-cards implies field disambiguation
2120 -- Otherwise if you write (C {..}) you may well get
2121 -- stuff like " 'a' not in scope ", which is a bit silly
2122 -- if the compiler has just filled in field 'a' of constructor 'C'
2123 , (Opt_RecordWildCards, turnOn, Opt_DisambiguateRecordFields)
2124
2125 , (Opt_ParallelArrays, turnOn, Opt_ParallelListComp)
2126 ]
2127
2128 optLevelFlags :: [([Int], DynFlag)]
2129 optLevelFlags
2130 = [ ([0], Opt_IgnoreInterfacePragmas)
2131 , ([0], Opt_OmitInterfacePragmas)
2132
2133 , ([1,2], Opt_IgnoreAsserts)
2134 , ([1,2], Opt_EnableRewriteRules) -- Off for -O0; see Note [Scoping for Builtin rules]
2135 -- in PrelRules
2136 , ([1,2], Opt_DoEtaReduction)
2137 , ([1,2], Opt_CaseMerge)
2138 , ([1,2], Opt_Strictness)
2139 , ([1,2], Opt_CSE)
2140 , ([1,2], Opt_FullLaziness)
2141 , ([1,2], Opt_Specialise)
2142 , ([1,2], Opt_FloatIn)
2143
2144 , ([2], Opt_LiberateCase)
2145 , ([2], Opt_SpecConstr)
2146 , ([2], Opt_RegsGraph)
2147 , ([0,1,2], Opt_LlvmTBAA)
2148 , ([0,1,2], Opt_RegLiveness)
2149
2150 -- , ([2], Opt_StaticArgumentTransformation)
2151 -- Max writes: I think it's probably best not to enable SAT with -O2 for the
2152 -- 6.10 release. The version of SAT in HEAD at the moment doesn't incorporate
2153 -- several improvements to the heuristics, and I'm concerned that without
2154 -- those changes SAT will interfere with some attempts to write "high
2155 -- performance Haskell", as we saw in some posts on Haskell-Cafe earlier
2156 -- this year. In particular, the version in HEAD lacks the tail call
2157 -- criterion, so many things that look like reasonable loops will be
2158 -- turned into functions with extra (unneccesary) thunk creation.
2159
2160 , ([0,1,2], Opt_DoLambdaEtaExpansion)
2161 -- This one is important for a tiresome reason:
2162 -- we want to make sure that the bindings for data
2163 -- constructors are eta-expanded. This is probably
2164 -- a good thing anyway, but it seems fragile.
2165 ]
2166
2167 -- -----------------------------------------------------------------------------
2168 -- Standard sets of warning options
2169
2170 standardWarnings :: [WarningFlag]
2171 standardWarnings
2172 = [ Opt_WarnWarningsDeprecations,
2173 Opt_WarnDeprecatedFlags,
2174 Opt_WarnUnrecognisedPragmas,
2175 Opt_WarnOverlappingPatterns,
2176 Opt_WarnMissingFields,
2177 Opt_WarnMissingMethods,
2178 Opt_WarnDuplicateExports,
2179 Opt_WarnLazyUnliftedBindings,
2180 Opt_WarnDodgyForeignImports,
2181 Opt_WarnWrongDoBind,
2182 Opt_WarnAlternativeLayoutRuleTransitional,
2183 Opt_WarnPointlessPragmas,
2184 Opt_WarnUnsupportedCallingConventions
2185 ]
2186
2187 minusWOpts :: [WarningFlag]
2188 -- Things you get with -W
2189 minusWOpts
2190 = standardWarnings ++
2191 [ Opt_WarnUnusedBinds,
2192 Opt_WarnUnusedMatches,
2193 Opt_WarnUnusedImports,
2194 Opt_WarnIncompletePatterns,
2195 Opt_WarnDodgyExports,
2196 Opt_WarnDodgyImports
2197 ]
2198
2199 minusWallOpts :: [WarningFlag]
2200 -- Things you get with -Wall
2201 minusWallOpts
2202 = minusWOpts ++
2203 [ Opt_WarnTypeDefaults,
2204 Opt_WarnNameShadowing,
2205 Opt_WarnMissingSigs,
2206 Opt_WarnHiShadows,
2207 Opt_WarnOrphans,
2208 Opt_WarnUnusedDoBind
2209 ]
2210
2211 enableGlasgowExts :: DynP ()
2212 enableGlasgowExts = do setDynFlag Opt_PrintExplicitForalls
2213 mapM_ setExtensionFlag glasgowExtsFlags
2214
2215 disableGlasgowExts :: DynP ()
2216 disableGlasgowExts = do unSetDynFlag Opt_PrintExplicitForalls
2217 mapM_ unSetExtensionFlag glasgowExtsFlags
2218
2219 glasgowExtsFlags :: [ExtensionFlag]
2220 glasgowExtsFlags = [
2221 Opt_ForeignFunctionInterface
2222 , Opt_UnliftedFFITypes
2223 , Opt_ImplicitParams
2224 , Opt_ScopedTypeVariables
2225 , Opt_UnboxedTuples
2226 , Opt_TypeSynonymInstances
2227 , Opt_StandaloneDeriving
2228 , Opt_DeriveDataTypeable
2229 , Opt_DeriveFunctor
2230 , Opt_DeriveFoldable
2231 , Opt_DeriveTraversable
2232 , Opt_DeriveGeneric
2233 , Opt_FlexibleContexts
2234 , Opt_FlexibleInstances
2235 , Opt_ConstrainedClassMethods
2236 , Opt_MultiParamTypeClasses
2237 , Opt_FunctionalDependencies
2238 , Opt_MagicHash
2239 , Opt_PolymorphicComponents
2240 , Opt_ExistentialQuantification
2241 , Opt_UnicodeSyntax
2242 , Opt_PostfixOperators
2243 , Opt_PatternGuards
2244 , Opt_LiberalTypeSynonyms
2245 , Opt_RankNTypes
2246 , Opt_TypeOperators
2247 , Opt_ExplicitNamespaces
2248 , Opt_DoRec
2249 , Opt_ParallelListComp
2250 , Opt_EmptyDataDecls
2251 , Opt_KindSignatures
2252 , Opt_GeneralizedNewtypeDeriving ]
2253
2254 #ifdef GHCI
2255 -- Consult the RTS to find whether GHC itself has been built profiled
2256 -- If so, you can't use Template Haskell
2257 foreign import ccall unsafe "rts_isProfiled" rtsIsProfiledIO :: IO CInt
2258
2259 rtsIsProfiled :: Bool
2260 rtsIsProfiled = unsafePerformIO rtsIsProfiledIO /= 0
2261 #endif
2262
2263 setWarnSafe :: Bool -> DynP ()
2264 setWarnSafe True = getCurLoc >>= \l -> upd (\d -> d { warnSafeOnLoc = l })
2265 setWarnSafe False = return ()
2266
2267 setWarnUnsafe :: Bool -> DynP ()
2268 setWarnUnsafe True = getCurLoc >>= \l -> upd (\d -> d { warnUnsafeOnLoc = l })
2269 setWarnUnsafe False = return ()
2270
2271 setPackageTrust :: DynP ()
2272 setPackageTrust = do
2273 setDynFlag Opt_PackageTrust
2274 l <- getCurLoc
2275 upd $ \d -> d { pkgTrustOnLoc = l }
2276
2277 setGenDeriving :: Bool -> DynP ()
2278 setGenDeriving True = getCurLoc >>= \l -> upd (\d -> d { newDerivOnLoc = l })
2279 setGenDeriving False = return ()
2280
2281 checkTemplateHaskellOk :: Bool -> DynP ()
2282 #ifdef GHCI
2283 checkTemplateHaskellOk turn_on
2284 | turn_on && rtsIsProfiled
2285 = addErr "You can't use Template Haskell with a profiled compiler"
2286 | otherwise
2287 = getCurLoc >>= \l -> upd (\d -> d { thOnLoc = l })
2288 #else
2289 -- In stage 1 we don't know that the RTS has rts_isProfiled,
2290 -- so we simply say "ok". It doesn't matter because TH isn't
2291 -- available in stage 1 anyway.
2292 checkTemplateHaskellOk _ = return ()
2293 #endif
2294
2295 {- **********************************************************************
2296 %* *
2297 DynFlags constructors
2298 %* *
2299 %********************************************************************* -}
2300
2301 type DynP = EwM (CmdLineP DynFlags)
2302
2303 upd :: (DynFlags -> DynFlags) -> DynP ()
2304 upd f = liftEwM (do dflags <- getCmdLineState
2305 putCmdLineState $! f dflags)
2306
2307 updM :: (DynFlags -> DynP DynFlags) -> DynP ()
2308 updM f = do dflags <- liftEwM getCmdLineState
2309 dflags' <- f dflags
2310 liftEwM $ putCmdLineState $! dflags'
2311
2312 --------------- Constructor functions for OptKind -----------------
2313 noArg :: (DynFlags -> DynFlags) -> OptKind (CmdLineP DynFlags)
2314 noArg fn = NoArg (upd fn)
2315
2316 noArgM :: (DynFlags -> DynP DynFlags) -> OptKind (CmdLineP DynFlags)
2317 noArgM fn = NoArg (updM fn)
2318
2319 noArgDF :: (DynFlags -> DynFlags) -> String -> OptKind (CmdLineP DynFlags)
2320 noArgDF fn deprec = NoArg (upd fn >> deprecate deprec)
2321
2322 hasArg :: (String -> DynFlags -> DynFlags) -> OptKind (CmdLineP DynFlags)
2323 hasArg fn = HasArg (upd . fn)
2324
2325 hasArgDF :: (String -> DynFlags -> DynFlags) -> String -> OptKind (CmdLineP DynFlags)
2326 hasArgDF fn deprec = HasArg (\s -> do upd (fn s)
2327 deprecate deprec)
2328
2329 sepArg :: (String -> DynFlags -> DynFlags) -> OptKind (CmdLineP DynFlags)
2330 sepArg fn = SepArg (upd . fn)
2331
2332 intSuffix :: (Int -> DynFlags -> DynFlags) -> OptKind (CmdLineP DynFlags)
2333 intSuffix fn = IntSuffix (\n -> upd (fn n))
2334
2335 optIntSuffixM :: (Maybe Int -> DynFlags -> DynP DynFlags)
2336 -> OptKind (CmdLineP DynFlags)
2337 optIntSuffixM fn = OptIntSuffix (\mi -> updM (fn mi))
2338
2339 setDumpFlag :: DynFlag -> OptKind (CmdLineP DynFlags)
2340 setDumpFlag dump_flag = NoArg (setDumpFlag' dump_flag)
2341
2342 --------------------------
2343 setDynFlag, unSetDynFlag :: DynFlag -> DynP ()
2344 setDynFlag f = upd (\dfs -> dopt_set dfs f)
2345 unSetDynFlag f = upd (\dfs -> dopt_unset dfs f)
2346
2347 --------------------------
2348 setWarningFlag, unSetWarningFlag :: WarningFlag -> DynP ()
2349 setWarningFlag f = upd (\dfs -> wopt_set dfs f)
2350 unSetWarningFlag f = upd (\dfs -> wopt_unset dfs f)
2351
2352 --------------------------
2353 setExtensionFlag, unSetExtensionFlag :: ExtensionFlag -> DynP ()
2354 setExtensionFlag f = do upd (\dfs -> xopt_set dfs f)
2355 sequence_ deps
2356 where
2357 deps = [ if turn_on then setExtensionFlag d
2358 else unSetExtensionFlag d
2359 | (f', turn_on, d) <- impliedFlags, f' == f ]
2360 -- When you set f, set the ones it implies
2361 -- NB: use setExtensionFlag recursively, in case the implied flags
2362 -- implies further flags
2363
2364 unSetExtensionFlag f = upd (\dfs -> xopt_unset dfs f)
2365 -- When you un-set f, however, we don't un-set the things it implies
2366 -- (except for -fno-glasgow-exts, which is treated specially)
2367
2368 --------------------------
2369 alterSettings :: (Settings -> Settings) -> DynFlags -> DynFlags
2370 alterSettings f dflags = dflags { settings = f (settings dflags) }
2371
2372 --------------------------
2373 setDumpFlag' :: DynFlag -> DynP ()
2374 setDumpFlag' dump_flag
2375 = do setDynFlag dump_flag
2376 when want_recomp forceRecompile
2377 where
2378 -- Certain dumpy-things are really interested in what's going
2379 -- on during recompilation checking, so in those cases we
2380 -- don't want to turn it off.
2381 want_recomp = dump_flag `notElem` [Opt_D_dump_if_trace,
2382 Opt_D_dump_hi_diffs]
2383
2384 forceRecompile :: DynP ()
2385 -- Whenver we -ddump, force recompilation (by switching off the
2386 -- recompilation checker), else you don't see the dump! However,
2387 -- don't switch it off in --make mode, else *everything* gets
2388 -- recompiled which probably isn't what you want
2389 forceRecompile = do dfs <- liftEwM getCmdLineState
2390 when (force_recomp dfs) (setDynFlag Opt_ForceRecomp)
2391 where
2392 force_recomp dfs = isOneShot (ghcMode dfs)
2393
2394 setVerboseCore2Core :: DynP ()
2395 setVerboseCore2Core = do forceRecompile
2396 setDynFlag Opt_D_verbose_core2core
2397 upd (\dfs -> dfs { shouldDumpSimplPhase = Nothing })
2398
2399 setDumpSimplPhases :: String -> DynP ()
2400 setDumpSimplPhases s = do forceRecompile
2401 upd (\dfs -> dfs { shouldDumpSimplPhase = Just spec })
2402 where
2403 spec = case s of { ('=' : s') -> s'; _ -> s }
2404
2405 setVerbosity :: Maybe Int -> DynP ()
2406 setVerbosity mb_n = upd (\dfs -> dfs{ verbosity = mb_n `orElse` 3 })
2407
2408 addCmdlineHCInclude :: String -> DynP ()
2409 addCmdlineHCInclude a = upd (\s -> s{cmdlineHcIncludes = a : cmdlineHcIncludes s})
2410
2411 data PkgConfRef
2412 = GlobalPkgConf
2413 | UserPkgConf
2414 | PkgConfFile FilePath
2415
2416 addPkgConfRef :: PkgConfRef -> DynP ()
2417 addPkgConfRef p = upd $ \s -> s { extraPkgConfs = (p:) . extraPkgConfs s }
2418
2419 removeUserPkgConf :: DynP ()
2420 removeUserPkgConf = upd $ \s -> s { extraPkgConfs = filter isNotUser . extraPkgConfs s }
2421 where
2422 isNotUser UserPkgConf = False
2423 isNotUser _ = True
2424
2425 removeGlobalPkgConf :: DynP ()
2426 removeGlobalPkgConf = upd $ \s -> s { extraPkgConfs = filter isNotGlobal . extraPkgConfs s }
2427 where
2428 isNotGlobal GlobalPkgConf = False
2429 isNotGlobal _ = True
2430
2431 clearPkgConf :: DynP ()
2432 clearPkgConf = upd $ \s -> s { extraPkgConfs = const [] }
2433
2434 exposePackage, exposePackageId, hidePackage, ignorePackage,
2435 trustPackage, distrustPackage :: String -> DynP ()
2436 exposePackage p =
2437 upd (\s -> s{ packageFlags = ExposePackage p : packageFlags s })
2438 exposePackageId p =
2439 upd (\s -> s{ packageFlags = ExposePackageId p : packageFlags s })
2440 hidePackage p =
2441 upd (\s -> s{ packageFlags = HidePackage p : packageFlags s })
2442 ignorePackage p =
2443 upd (\s -> s{ packageFlags = IgnorePackage p : packageFlags s })
2444 trustPackage p = exposePackage p >> -- both trust and distrust also expose a package
2445 upd (\s -> s{ packageFlags = TrustPackage p : packageFlags s })
2446 distrustPackage p = exposePackage p >>
2447 upd (\s -> s{ packageFlags = DistrustPackage p : packageFlags s })
2448
2449 setPackageName :: String -> DynFlags -> DynFlags
2450 setPackageName p s = s{ thisPackage = stringToPackageId p }
2451
2452 -- If we're linking a binary, then only targets that produce object
2453 -- code are allowed (requests for other target types are ignored).
2454 setTarget :: HscTarget -> DynP ()
2455 setTarget l = upd set
2456 where
2457 set dfs
2458 | ghcLink dfs /= LinkBinary || isObjectTarget l = dfs{ hscTarget = l }
2459 | otherwise = dfs
2460
2461 -- Changes the target only if we're compiling object code. This is
2462 -- used by -fasm and -fllvm, which switch from one to the other, but
2463 -- not from bytecode to object-code. The idea is that -fasm/-fllvm
2464 -- can be safely used in an OPTIONS_GHC pragma.
2465 setObjTarget :: HscTarget -> DynP ()
2466 setObjTarget l = updM set
2467 where
2468 set dflags
2469 | isObjectTarget (hscTarget dflags)
2470 = case l of
2471 HscC
2472 | cGhcUnregisterised /= "YES" ->
2473 do addWarn ("Compiler not unregisterised, so ignoring " ++ flag)
2474 return dflags
2475 HscAsm
2476 | cGhcWithNativeCodeGen /= "YES" ->
2477 do addWarn ("Compiler has no native codegen, so ignoring " ++
2478 flag)
2479 return dflags
2480 HscLlvm
2481 | not ((arch == ArchX86_64) && (os == OSLinux || os == OSDarwin)) &&
2482 (not opt_Static || opt_PIC)
2483 ->
2484 do addWarn ("Ignoring " ++ flag ++ " as it is incompatible with -fPIC and -dynamic on this platform")
2485 return dflags
2486 _ -> return $ dflags { hscTarget = l }
2487 | otherwise = return dflags
2488 where platform = targetPlatform dflags
2489 arch = platformArch platform
2490 os = platformOS platform
2491 flag = showHscTargetFlag l
2492
2493 setOptLevel :: Int -> DynFlags -> DynP DynFlags
2494 setOptLevel n dflags
2495 | hscTarget dflags == HscInterpreted && n > 0
2496 = do addWarn "-O conflicts with --interactive; -O ignored."
2497 return dflags
2498 | otherwise
2499 = return (updOptLevel n dflags)
2500
2501
2502 -- -Odph is equivalent to
2503 --
2504 -- -O2 optimise as much as possible
2505 -- -fmax-simplifier-iterations20 this is necessary sometimes
2506 -- -fsimplifier-phases=3 we use an additional simplifier phase for fusion
2507 --
2508 setDPHOpt :: DynFlags -> DynP DynFlags
2509 setDPHOpt dflags = setOptLevel 2 (dflags { maxSimplIterations = 20
2510 , simplPhases = 3
2511 })
2512
2513 setMainIs :: String -> DynP ()
2514 setMainIs arg
2515 | not (null main_fn) && isLower (head main_fn)
2516 -- The arg looked like "Foo.Bar.baz"
2517 = upd $ \d -> d{ mainFunIs = Just main_fn,
2518 mainModIs = mkModule mainPackageId (mkModuleName main_mod) }
2519
2520 | isUpper (head arg) -- The arg looked like "Foo" or "Foo.Bar"
2521 = upd $ \d -> d{ mainModIs = mkModule mainPackageId (mkModuleName arg) }
2522
2523 | otherwise -- The arg looked like "baz"
2524 = upd $ \d -> d{ mainFunIs = Just arg }
2525 where
2526 (main_mod, main_fn) = splitLongestPrefix arg (== '.')
2527
2528 -----------------------------------------------------------------------------
2529 -- Paths & Libraries
2530
2531 addImportPath, addLibraryPath, addIncludePath, addFrameworkPath :: FilePath -> DynP ()
2532
2533 -- -i on its own deletes the import paths
2534 addImportPath "" = upd (\s -> s{importPaths = []})
2535 addImportPath p = upd (\s -> s{importPaths = importPaths s ++ splitPathList p})
2536
2537 addLibraryPath p =
2538 upd (\s -> s{libraryPaths = libraryPaths s ++ splitPathList p})
2539
2540 addIncludePath p =
2541 upd (\s -> s{includePaths = includePaths s ++ splitPathList p})
2542
2543 addFrameworkPath p =
2544 upd (\s -> s{frameworkPaths = frameworkPaths s ++ splitPathList p})
2545
2546 #ifndef mingw32_TARGET_OS
2547 split_marker :: Char
2548 split_marker = ':' -- not configurable (ToDo)
2549 #endif
2550
2551 splitPathList :: String -> [String]
2552 splitPathList s = filter notNull (splitUp s)
2553 -- empty paths are ignored: there might be a trailing
2554 -- ':' in the initial list, for example. Empty paths can
2555 -- cause confusion when they are translated into -I options
2556 -- for passing to gcc.
2557 where
2558 #ifndef mingw32_TARGET_OS
2559 splitUp xs = split split_marker xs
2560 #else
2561 -- Windows: 'hybrid' support for DOS-style paths in directory lists.
2562 --
2563 -- That is, if "foo:bar:baz" is used, this interpreted as
2564 -- consisting of three entries, 'foo', 'bar', 'baz'.
2565 -- However, with "c:/foo:c:\\foo;x:/bar", this is interpreted
2566 -- as 3 elts, "c:/foo", "c:\\foo", "x:/bar"
2567 --
2568 -- Notice that no attempt is made to fully replace the 'standard'
2569 -- split marker ':' with the Windows / DOS one, ';'. The reason being
2570 -- that this will cause too much breakage for users & ':' will
2571 -- work fine even with DOS paths, if you're not insisting on being silly.
2572 -- So, use either.
2573 splitUp [] = []
2574 splitUp (x:':':div:xs) | div `elem` dir_markers
2575 = ((x:':':div:p): splitUp rs)
2576 where
2577 (p,rs) = findNextPath xs
2578 -- we used to check for existence of the path here, but that
2579 -- required the IO monad to be threaded through the command-line
2580 -- parser which is quite inconvenient. The
2581 splitUp xs = cons p (splitUp rs)
2582 where
2583 (p,rs) = findNextPath xs
2584
2585 cons "" xs = xs
2586 cons x xs = x:xs
2587
2588 -- will be called either when we've consumed nought or the
2589 -- "<Drive>:/" part of a DOS path, so splitting is just a Q of
2590 -- finding the next split marker.
2591 findNextPath xs =
2592 case break (`elem` split_markers) xs of
2593 (p, _:ds) -> (p, ds)
2594 (p, xs) -> (p, xs)
2595
2596 split_markers :: [Char]
2597 split_markers = [':', ';']
2598
2599 dir_markers :: [Char]
2600 dir_markers = ['/', '\\']
2601 #endif
2602
2603 -- -----------------------------------------------------------------------------
2604 -- tmpDir, where we store temporary files.
2605
2606 setTmpDir :: FilePath -> DynFlags -> DynFlags
2607 setTmpDir dir = alterSettings (\s -> s { sTmpDir = normalise dir })
2608 -- we used to fix /cygdrive/c/.. on Windows, but this doesn't
2609 -- seem necessary now --SDM 7/2/2008
2610
2611 -----------------------------------------------------------------------------
2612 -- RTS opts
2613
2614 setRtsOpts :: String -> DynP ()
2615 setRtsOpts arg = upd $ \ d -> d {rtsOpts = Just arg}
2616
2617 setRtsOptsEnabled :: RtsOptsEnabled -> DynP ()
2618 setRtsOptsEnabled arg = upd $ \ d -> d {rtsOptsEnabled = arg}
2619
2620 -----------------------------------------------------------------------------
2621 -- Hpc stuff
2622
2623 setOptHpcDir :: String -> DynP ()
2624 setOptHpcDir arg = upd $ \ d -> d{hpcDir = arg}
2625
2626 -----------------------------------------------------------------------------
2627 -- Via-C compilation stuff
2628
2629 -- There are some options that we need to pass to gcc when compiling
2630 -- Haskell code via C, but are only supported by recent versions of
2631 -- gcc. The configure script decides which of these options we need,
2632 -- and puts them in the "settings" file in $topdir. The advantage of
2633 -- having these in a separate file is that the file can be created at
2634 -- install-time depending on the available gcc version, and even
2635 -- re-generated later if gcc is upgraded.
2636 --
2637 -- The options below are not dependent on the version of gcc, only the
2638 -- platform.
2639
2640 picCCOpts :: DynFlags -> [String]
2641 picCCOpts dflags
2642 = case platformOS (targetPlatform dflags) of
2643 OSDarwin
2644 -- Apple prefers to do things the other way round.
2645 -- PIC is on by default.
2646 -- -mdynamic-no-pic:
2647 -- Turn off PIC code generation.
2648 -- -fno-common:
2649 -- Don't generate "common" symbols - these are unwanted
2650 -- in dynamic libraries.
2651
2652 | opt_PIC -> ["-fno-common", "-U __PIC__", "-D__PIC__"]
2653 | otherwise -> ["-mdynamic-no-pic"]
2654 OSMinGW32 -- no -fPIC for Windows
2655 | opt_PIC -> ["-U __PIC__", "-D__PIC__"]
2656 | otherwise -> []
2657 _
2658 -- we need -fPIC for C files when we are compiling with -dynamic,
2659 -- otherwise things like stub.c files don't get compiled
2660 -- correctly. They need to reference data in the Haskell
2661 -- objects, but can't without -fPIC. See
2662 -- http://hackage.haskell.org/trac/ghc/wiki/Commentary/PositionIndependentCode
2663 | opt_PIC || not opt_Static -> ["-fPIC", "-U __PIC__", "-D__PIC__"]
2664 | otherwise -> []
2665
2666 -- -----------------------------------------------------------------------------
2667 -- Splitting
2668
2669 can_split :: Bool
2670 can_split = cSupportsSplitObjs == "YES"
2671
2672 -- -----------------------------------------------------------------------------
2673 -- Compiler Info
2674
2675 compilerInfo :: DynFlags -> [(String, String)]
2676 compilerInfo dflags
2677 = -- We always make "Project name" be first to keep parsing in
2678 -- other languages simple, i.e. when looking for other fields,
2679 -- you don't have to worry whether there is a leading '[' or not
2680 ("Project name", cProjectName)
2681 -- Next come the settings, so anything else can be overridden
2682 -- in the settings file (as "lookup" uses the first match for the
2683 -- key)
2684 : rawSettings dflags
2685 ++ [("Project version", cProjectVersion),
2686 ("Booter version", cBooterVersion),
2687 ("Stage", cStage),
2688 ("Build platform", cBuildPlatformString),
2689 ("Host platform", cHostPlatformString),
2690 ("Target platform", cTargetPlatformString),
2691 ("Have interpreter", cGhcWithInterpreter),
2692 ("Object splitting supported", cSupportsSplitObjs),
2693 ("Have native code generator", cGhcWithNativeCodeGen),
2694 ("Support SMP", cGhcWithSMP),
2695 ("Unregisterised", cGhcUnregisterised),
2696 ("Tables next to code", cGhcEnableTablesNextToCode),
2697 ("RTS ways", cGhcRTSWays),
2698 ("Leading underscore", cLeadingUnderscore),
2699 ("Debug on", show debugIsOn),
2700 ("LibDir", topDir dflags),
2701 ("Global Package DB", systemPackageConfig dflags),
2702 ("Gcc Linker flags", show cGccLinkerOpts),
2703 ("Ld Linker flags", show cLdLinkerOpts)
2704 ]
2705