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