Revert D727
[ghc.git] / compiler / main / DynFlags.hs
1 {-# LANGUAGE CPP #-}
2
3 -------------------------------------------------------------------------------
4 --
5 -- | Dynamic flags
6 --
7 -- Most flags are dynamic flags, which means they can change from compilation
8 -- to compilation using @OPTIONS_GHC@ pragmas, and in a multi-session GHC each
9 -- session can be using different dynamic flags. Dynamic flags can also be set
10 -- at the prompt in GHCi.
11 --
12 -- (c) The University of Glasgow 2005
13 --
14 -------------------------------------------------------------------------------
15
16 {-# OPTIONS_GHC -fno-cse #-}
17 -- -fno-cse is needed for GLOBAL_VAR's to behave properly
18
19 module DynFlags (
20 -- * Dynamic flags and associated configuration types
21 DumpFlag(..),
22 GeneralFlag(..),
23 WarningFlag(..),
24 ExtensionFlag(..),
25 Language(..),
26 PlatformConstants(..),
27 FatalMessager, LogAction, FlushOut(..), FlushErr(..),
28 ProfAuto(..),
29 glasgowExtsFlags,
30 dopt, dopt_set, dopt_unset,
31 gopt, gopt_set, gopt_unset,
32 wopt, wopt_set, wopt_unset,
33 xopt, xopt_set, xopt_unset,
34 lang_set,
35 useUnicodeSyntax,
36 whenGeneratingDynamicToo, ifGeneratingDynamicToo,
37 whenCannotGenerateDynamicToo,
38 dynamicTooMkDynamicDynFlags,
39 DynFlags(..),
40 FlagSpec(..),
41 HasDynFlags(..), ContainsDynFlags(..),
42 RtsOptsEnabled(..),
43 HscTarget(..), isObjectTarget, defaultObjectTarget,
44 targetRetainsAllBindings,
45 GhcMode(..), isOneShot,
46 GhcLink(..), isNoLink,
47 PackageFlag(..), PackageArg(..), ModRenaming(..),
48 PkgConfRef(..),
49 Option(..), showOpt,
50 DynLibLoader(..),
51 fFlags, fWarningFlags, fLangFlags, xFlags,
52 dynFlagDependencies,
53 tablesNextToCode, mkTablesNextToCode,
54 SigOf, getSigOf,
55
56 Way(..), mkBuildTag, wayRTSOnly, addWay', updateWays,
57 wayGeneralFlags, wayUnsetGeneralFlags,
58
59 -- ** Safe Haskell
60 SafeHaskellMode(..),
61 safeHaskellOn, safeImportsOn, safeLanguageOn, safeInferOn,
62 packageTrustOn,
63 safeDirectImpsReq, safeImplicitImpsReq,
64 unsafeFlags, unsafeFlagsForInfer,
65
66 -- ** System tool settings and locations
67 Settings(..),
68 targetPlatform, programName, projectVersion,
69 ghcUsagePath, ghciUsagePath, topDir, tmpDir, rawSettings,
70 versionedAppDir,
71 extraGccViaCFlags, systemPackageConfig,
72 pgm_L, pgm_P, pgm_F, pgm_c, pgm_s, pgm_a, pgm_l, pgm_dll, pgm_T,
73 pgm_sysman, pgm_windres, pgm_libtool, pgm_lo, pgm_lc,
74 opt_L, opt_P, opt_F, opt_c, opt_a, opt_l,
75 opt_windres, opt_lo, opt_lc,
76
77
78 -- ** Manipulating DynFlags
79 defaultDynFlags, -- Settings -> DynFlags
80 defaultWays,
81 interpWays,
82 initDynFlags, -- DynFlags -> IO DynFlags
83 defaultFatalMessager,
84 defaultLogAction,
85 defaultLogActionHPrintDoc,
86 defaultLogActionHPutStrDoc,
87 defaultFlushOut,
88 defaultFlushErr,
89
90 getOpts, -- DynFlags -> (DynFlags -> [a]) -> [a]
91 getVerbFlags,
92 updOptLevel,
93 setTmpDir,
94 setPackageKey,
95 interpretPackageEnv,
96
97 -- ** Parsing DynFlags
98 parseDynamicFlagsCmdLine,
99 parseDynamicFilePragma,
100 parseDynamicFlagsFull,
101
102 -- ** Available DynFlags
103 allFlags,
104 flagsAll,
105 flagsDynamic,
106 flagsPackage,
107 flagsForCompletion,
108
109 supportedLanguagesAndExtensions,
110 languageExtensions,
111
112 -- ** DynFlags C compiler options
113 picCCOpts, picPOpts,
114
115 -- * Configuration of the stg-to-stg passes
116 StgToDo(..),
117 getStgToDo,
118
119 -- * Compiler configuration suitable for display to the user
120 compilerInfo,
121
122 #ifdef GHCI
123 rtsIsProfiled,
124 #endif
125 dynamicGhc,
126
127 #include "../includes/dist-derivedconstants/header/GHCConstantsHaskellExports.hs"
128 bLOCK_SIZE_W,
129 wORD_SIZE_IN_BITS,
130 tAG_MASK,
131 mAX_PTR_TAG,
132 tARGET_MIN_INT, tARGET_MAX_INT, tARGET_MAX_WORD,
133
134 unsafeGlobalDynFlags, setUnsafeGlobalDynFlags,
135
136 -- * SSE and AVX
137 isSseEnabled,
138 isSse2Enabled,
139 isSse4_2Enabled,
140 isAvxEnabled,
141 isAvx2Enabled,
142 isAvx512cdEnabled,
143 isAvx512erEnabled,
144 isAvx512fEnabled,
145 isAvx512pfEnabled,
146
147 -- * Linker/compiler information
148 LinkerInfo(..),
149 CompilerInfo(..),
150 ) where
151
152 #include "HsVersions.h"
153
154 import Platform
155 import PlatformConstants
156 import Module
157 import PackageConfig
158 import {-# SOURCE #-} Hooks
159 import {-# SOURCE #-} PrelNames ( mAIN )
160 import {-# SOURCE #-} Packages (PackageState, emptyPackageState)
161 import DriverPhases ( Phase(..), phaseInputExt )
162 import Config
163 import CmdLineParser
164 import Constants
165 import Panic
166 import Util
167 import Maybes
168 import MonadUtils
169 import qualified Pretty
170 import SrcLoc
171 import BasicTypes ( IntWithInf, treatZeroAsInf )
172 import FastString
173 import Outputable
174 #ifdef GHCI
175 import Foreign.C ( CInt(..) )
176 import System.IO.Unsafe ( unsafeDupablePerformIO )
177 #endif
178 import {-# SOURCE #-} ErrUtils ( Severity(..), MsgDoc, mkLocMessage )
179
180 import System.IO.Unsafe ( unsafePerformIO )
181 import Data.IORef
182 import Control.Arrow ((&&&))
183 import Control.Monad
184 import Control.Exception (throwIO)
185
186 import Data.Bits
187 import Data.Char
188 import Data.Int
189 import Data.List
190 import Data.Map (Map)
191 import qualified Data.Map as Map
192 import Data.Set (Set)
193 import qualified Data.Set as Set
194 import Data.Word
195 import System.FilePath
196 import System.Directory
197 import System.Environment (getEnv)
198 import System.IO
199 import System.IO.Error
200 import Text.ParserCombinators.ReadP hiding (char)
201 import Text.ParserCombinators.ReadP as R
202
203 import Data.IntSet (IntSet)
204 import qualified Data.IntSet as IntSet
205
206 import GHC.Foreign (withCString, peekCString)
207
208 -- Note [Updating flag description in the User's Guide]
209 -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
210 --
211 -- If you modify anything in this file please make sure that your changes are
212 -- described in the User's Guide. Usually at least two sections need to be
213 -- updated:
214 --
215 -- * Flag Reference section in docs/users-guide/flags.xml lists all available
216 -- flags together with a short description
217 --
218 -- * Flag description in docs/users_guide/using.xml provides a detailed
219 -- explanation of flags' usage.
220
221 -- Note [Supporting CLI completion]
222 -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
223 --
224 -- The command line interface completion (in for example bash) is an easy way
225 -- for the developer to learn what flags are available from GHC.
226 -- GHC helps by separating which flags are available when compiling with GHC,
227 -- and which flags are available when using GHCi.
228 -- A flag is assumed to either work in both these modes, or only in one of them.
229 -- When adding or changing a flag, please consider for which mode the flag will
230 -- have effect, and annotate it accordingly. For Flags use defFlag, defGhcFlag,
231 -- defGhciFlag, and for FlagSpec use flagSpec or flagGhciSpec.
232
233 -- -----------------------------------------------------------------------------
234 -- DynFlags
235
236 data DumpFlag
237 -- See Note [Updating flag description in the User's Guide]
238
239 -- debugging flags
240 = Opt_D_dump_cmm
241 | Opt_D_dump_cmm_raw
242 -- All of the cmm subflags (there are a lot!) Automatically
243 -- enabled if you run -ddump-cmm
244 | Opt_D_dump_cmm_cfg
245 | Opt_D_dump_cmm_cbe
246 | Opt_D_dump_cmm_switch
247 | Opt_D_dump_cmm_proc
248 | Opt_D_dump_cmm_sink
249 | Opt_D_dump_cmm_sp
250 | Opt_D_dump_cmm_procmap
251 | Opt_D_dump_cmm_split
252 | Opt_D_dump_cmm_info
253 | Opt_D_dump_cmm_cps
254 -- end cmm subflags
255 | Opt_D_dump_asm
256 | Opt_D_dump_asm_native
257 | Opt_D_dump_asm_liveness
258 | Opt_D_dump_asm_regalloc
259 | Opt_D_dump_asm_regalloc_stages
260 | Opt_D_dump_asm_conflicts
261 | Opt_D_dump_asm_stats
262 | Opt_D_dump_asm_expanded
263 | Opt_D_dump_llvm
264 | Opt_D_dump_core_stats
265 | Opt_D_dump_deriv
266 | Opt_D_dump_ds
267 | Opt_D_dump_foreign
268 | Opt_D_dump_inlinings
269 | Opt_D_dump_rule_firings
270 | Opt_D_dump_rule_rewrites
271 | Opt_D_dump_simpl_trace
272 | Opt_D_dump_occur_anal
273 | Opt_D_dump_parsed
274 | Opt_D_dump_rn
275 | Opt_D_dump_simpl
276 | Opt_D_dump_simpl_iterations
277 | Opt_D_dump_spec
278 | Opt_D_dump_prep
279 | Opt_D_dump_stg
280 | Opt_D_dump_call_arity
281 | Opt_D_dump_stranal
282 | Opt_D_dump_strsigs
283 | Opt_D_dump_tc
284 | Opt_D_dump_types
285 | Opt_D_dump_rules
286 | Opt_D_dump_cse
287 | Opt_D_dump_worker_wrapper
288 | Opt_D_dump_rn_trace
289 | Opt_D_dump_rn_stats
290 | Opt_D_dump_opt_cmm
291 | Opt_D_dump_simpl_stats
292 | Opt_D_dump_cs_trace -- Constraint solver in type checker
293 | Opt_D_dump_tc_trace
294 | Opt_D_dump_if_trace
295 | Opt_D_dump_vt_trace
296 | Opt_D_dump_splices
297 | Opt_D_th_dec_file
298 | Opt_D_dump_BCOs
299 | Opt_D_dump_vect
300 | Opt_D_dump_ticked
301 | Opt_D_dump_rtti
302 | Opt_D_source_stats
303 | Opt_D_verbose_stg2stg
304 | Opt_D_dump_hi
305 | Opt_D_dump_hi_diffs
306 | Opt_D_dump_mod_cycles
307 | Opt_D_dump_mod_map
308 | Opt_D_dump_view_pattern_commoning
309 | Opt_D_verbose_core2core
310 | Opt_D_dump_debug
311
312 deriving (Eq, Show, Enum)
313
314 -- | Enumerates the simple on-or-off dynamic flags
315 data GeneralFlag
316 -- See Note [Updating flag description in the User's Guide]
317
318 = Opt_DumpToFile -- ^ Append dump output to files instead of stdout.
319 | Opt_D_faststring_stats
320 | Opt_D_dump_minimal_imports
321 | Opt_DoCoreLinting
322 | Opt_DoStgLinting
323 | Opt_DoCmmLinting
324 | Opt_DoAsmLinting
325 | Opt_DoAnnotationLinting
326 | Opt_NoLlvmMangler -- hidden flag
327
328 | Opt_WarnIsError -- -Werror; makes warnings fatal
329
330 | Opt_PrintExplicitForalls
331 | Opt_PrintExplicitKinds
332 | Opt_PrintUnicodeSyntax
333
334 -- optimisation opts
335 | Opt_CallArity
336 | Opt_Strictness
337 | Opt_LateDmdAnal
338 | Opt_KillAbsence
339 | Opt_KillOneShot
340 | Opt_FullLaziness
341 | Opt_FloatIn
342 | Opt_Specialise
343 | Opt_SpecialiseAggressively
344 | Opt_StaticArgumentTransformation
345 | Opt_CSE
346 | Opt_LiberateCase
347 | Opt_SpecConstr
348 | Opt_DoLambdaEtaExpansion
349 | Opt_IgnoreAsserts
350 | Opt_DoEtaReduction
351 | Opt_CaseMerge
352 | Opt_UnboxStrictFields
353 | Opt_UnboxSmallStrictFields
354 | Opt_DictsCheap
355 | Opt_EnableRewriteRules -- Apply rewrite rules during simplification
356 | Opt_Vectorise
357 | Opt_VectorisationAvoidance
358 | Opt_RegsGraph -- do graph coloring register allocation
359 | Opt_RegsIterative -- do iterative coalescing graph coloring register allocation
360 | Opt_PedanticBottoms -- Be picky about how we treat bottom
361 | Opt_LlvmTBAA -- Use LLVM TBAA infastructure for improving AA (hidden flag)
362 | Opt_LlvmPassVectorsInRegisters -- Pass SIMD vectors in registers (requires a patched LLVM) (hidden flag)
363 | Opt_IrrefutableTuples
364 | Opt_CmmSink
365 | Opt_CmmElimCommonBlocks
366 | Opt_OmitYields
367 | Opt_SimpleListLiterals
368 | Opt_FunToThunk -- allow WwLib.mkWorkerArgs to remove all value lambdas
369 | Opt_DictsStrict -- be strict in argument dictionaries
370 | Opt_DmdTxDictSel -- use a special demand transformer for dictionary selectors
371 | Opt_Loopification -- See Note [Self-recursive tail calls]
372
373 -- Interface files
374 | Opt_IgnoreInterfacePragmas
375 | Opt_OmitInterfacePragmas
376 | Opt_ExposeAllUnfoldings
377 | Opt_WriteInterface -- forces .hi files to be written even with -fno-code
378
379 -- profiling opts
380 | Opt_AutoSccsOnIndividualCafs
381 | Opt_ProfCountEntries
382
383 -- misc opts
384 | Opt_Pp
385 | Opt_ForceRecomp
386 | Opt_ExcessPrecision
387 | Opt_EagerBlackHoling
388 | Opt_NoHsMain
389 | Opt_SplitObjs
390 | Opt_StgStats
391 | Opt_HideAllPackages
392 | Opt_PrintBindResult
393 | Opt_Haddock
394 | Opt_HaddockOptions
395 | Opt_BreakOnException
396 | Opt_BreakOnError
397 | Opt_PrintEvldWithShow
398 | Opt_PrintBindContents
399 | Opt_GenManifest
400 | Opt_EmbedManifest
401 | Opt_SharedImplib
402 | Opt_BuildingCabalPackage
403 | Opt_IgnoreDotGhci
404 | Opt_GhciSandbox
405 | Opt_GhciHistory
406 | Opt_HelpfulErrors
407 | Opt_DeferTypeErrors
408 | Opt_DeferTypedHoles
409 | Opt_Parallel
410 | Opt_PIC
411 | Opt_SccProfilingOn
412 | Opt_Ticky
413 | Opt_Ticky_Allocd
414 | Opt_Ticky_LNE
415 | Opt_Ticky_Dyn_Thunk
416 | Opt_Static
417 | Opt_RPath
418 | Opt_RelativeDynlibPaths
419 | Opt_Hpc
420 | Opt_FlatCache
421
422 -- PreInlining is on by default. The option is there just to see how
423 -- bad things get if you turn it off!
424 | Opt_SimplPreInlining
425
426 -- output style opts
427 | Opt_ErrorSpans -- Include full span info in error messages,
428 -- instead of just the start position.
429 | Opt_PprCaseAsLet
430 | Opt_PprShowTicks
431
432 -- Suppress all coercions, them replacing with '...'
433 | Opt_SuppressCoercions
434 | Opt_SuppressVarKinds
435 -- Suppress module id prefixes on variables.
436 | Opt_SuppressModulePrefixes
437 -- Suppress type applications.
438 | Opt_SuppressTypeApplications
439 -- Suppress info such as arity and unfoldings on identifiers.
440 | Opt_SuppressIdInfo
441 -- Suppress separate type signatures in core, but leave types on
442 -- lambda bound vars
443 | Opt_SuppressTypeSignatures
444 -- Suppress unique ids on variables.
445 -- Except for uniques, as some simplifier phases introduce new
446 -- variables that have otherwise identical names.
447 | Opt_SuppressUniques
448
449 -- temporary flags
450 | Opt_AutoLinkPackages
451 | Opt_ImplicitImportQualified
452
453 -- keeping stuff
454 | Opt_KeepHiDiffs
455 | Opt_KeepHcFiles
456 | Opt_KeepSFiles
457 | Opt_KeepTmpFiles
458 | Opt_KeepRawTokenStream
459 | Opt_KeepLlvmFiles
460
461 | Opt_BuildDynamicToo
462
463 -- safe haskell flags
464 | Opt_DistrustAllPackages
465 | Opt_PackageTrust
466
467 -- debugging flags
468 | Opt_Debug
469
470 deriving (Eq, Show, Enum)
471
472 data WarningFlag =
473 -- See Note [Updating flag description in the User's Guide]
474 Opt_WarnDuplicateExports
475 | Opt_WarnDuplicateConstraints
476 | Opt_WarnRedundantConstraints
477 | Opt_WarnHiShadows
478 | Opt_WarnImplicitPrelude
479 | Opt_WarnIncompletePatterns
480 | Opt_WarnIncompleteUniPatterns
481 | Opt_WarnIncompletePatternsRecUpd
482 | Opt_WarnOverflowedLiterals
483 | Opt_WarnEmptyEnumerations
484 | Opt_WarnMissingFields
485 | Opt_WarnMissingImportList
486 | Opt_WarnMissingMethods
487 | Opt_WarnMissingSigs
488 | Opt_WarnMissingLocalSigs
489 | Opt_WarnNameShadowing
490 | Opt_WarnOverlappingPatterns
491 | Opt_WarnTypeDefaults
492 | Opt_WarnMonomorphism
493 | Opt_WarnUnusedTopBinds
494 | Opt_WarnUnusedLocalBinds
495 | Opt_WarnUnusedPatternBinds
496 | Opt_WarnUnusedImports
497 | Opt_WarnUnusedMatches
498 | Opt_WarnContextQuantification
499 | Opt_WarnWarningsDeprecations
500 | Opt_WarnDeprecatedFlags
501 | Opt_WarnAMP
502 | Opt_WarnDodgyExports
503 | Opt_WarnDodgyImports
504 | Opt_WarnOrphans
505 | Opt_WarnAutoOrphans
506 | Opt_WarnIdentities
507 | Opt_WarnTabs
508 | Opt_WarnUnrecognisedPragmas
509 | Opt_WarnDodgyForeignImports
510 | Opt_WarnUnusedDoBind
511 | Opt_WarnWrongDoBind
512 | Opt_WarnAlternativeLayoutRuleTransitional
513 | Opt_WarnUnsafe
514 | Opt_WarnSafe
515 | Opt_WarnTrustworthySafe
516 | Opt_WarnPointlessPragmas
517 | Opt_WarnUnsupportedCallingConventions
518 | Opt_WarnUnsupportedLlvmVersion
519 | Opt_WarnInlineRuleShadowing
520 | Opt_WarnTypedHoles
521 | Opt_WarnPartialTypeSignatures
522 | Opt_WarnMissingExportedSigs
523 | Opt_WarnUntickedPromotedConstructors
524 | Opt_WarnDerivingTypeable
525 deriving (Eq, Show, Enum)
526
527 data Language = Haskell98 | Haskell2010
528 deriving Enum
529
530 -- | The various Safe Haskell modes
531 data SafeHaskellMode
532 = Sf_None
533 | Sf_Unsafe
534 | Sf_Trustworthy
535 | Sf_Safe
536 deriving (Eq)
537
538 instance Show SafeHaskellMode where
539 show Sf_None = "None"
540 show Sf_Unsafe = "Unsafe"
541 show Sf_Trustworthy = "Trustworthy"
542 show Sf_Safe = "Safe"
543
544 instance Outputable SafeHaskellMode where
545 ppr = text . show
546
547 data ExtensionFlag
548 -- See Note [Updating flag description in the User's Guide]
549 = Opt_Cpp
550 | Opt_OverlappingInstances
551 | Opt_UndecidableInstances
552 | Opt_IncoherentInstances
553 | Opt_MonomorphismRestriction
554 | Opt_MonoPatBinds
555 | Opt_MonoLocalBinds
556 | Opt_RelaxedPolyRec -- Deprecated
557 | Opt_ExtendedDefaultRules -- Use GHC's extended rules for defaulting
558 | Opt_ForeignFunctionInterface
559 | Opt_UnliftedFFITypes
560 | Opt_InterruptibleFFI
561 | Opt_CApiFFI
562 | Opt_GHCForeignImportPrim
563 | Opt_JavaScriptFFI
564 | Opt_ParallelArrays -- Syntactic support for parallel arrays
565 | Opt_Arrows -- Arrow-notation syntax
566 | Opt_TemplateHaskell
567 | Opt_QuasiQuotes
568 | Opt_ImplicitParams
569 | Opt_ImplicitPrelude
570 | Opt_ScopedTypeVariables
571 | Opt_AllowAmbiguousTypes
572 | Opt_UnboxedTuples
573 | Opt_BangPatterns
574 | Opt_TypeFamilies
575 | Opt_OverloadedStrings
576 | Opt_OverloadedLists
577 | Opt_NumDecimals
578 | Opt_DisambiguateRecordFields
579 | Opt_RecordWildCards
580 | Opt_RecordPuns
581 | Opt_ViewPatterns
582 | Opt_GADTs
583 | Opt_GADTSyntax
584 | Opt_NPlusKPatterns
585 | Opt_DoAndIfThenElse
586 | Opt_RebindableSyntax
587 | Opt_ConstraintKinds
588 | Opt_PolyKinds -- Kind polymorphism
589 | Opt_DataKinds -- Datatype promotion
590 | Opt_InstanceSigs
591
592 | Opt_StandaloneDeriving
593 | Opt_DeriveDataTypeable
594 | Opt_AutoDeriveTypeable -- Automatic derivation of Typeable
595 | Opt_DeriveFunctor
596 | Opt_DeriveTraversable
597 | Opt_DeriveFoldable
598 | Opt_DeriveGeneric -- Allow deriving Generic/1
599 | Opt_DefaultSignatures -- Allow extra signatures for defmeths
600 | Opt_DeriveAnyClass -- Allow deriving any class
601
602 | Opt_TypeSynonymInstances
603 | Opt_FlexibleContexts
604 | Opt_FlexibleInstances
605 | Opt_ConstrainedClassMethods
606 | Opt_MultiParamTypeClasses
607 | Opt_NullaryTypeClasses
608 | Opt_FunctionalDependencies
609 | Opt_UnicodeSyntax
610 | Opt_ExistentialQuantification
611 | Opt_MagicHash
612 | Opt_EmptyDataDecls
613 | Opt_KindSignatures
614 | Opt_RoleAnnotations
615 | Opt_ParallelListComp
616 | Opt_TransformListComp
617 | Opt_MonadComprehensions
618 | Opt_GeneralizedNewtypeDeriving
619 | Opt_RecursiveDo
620 | Opt_PostfixOperators
621 | Opt_TupleSections
622 | Opt_PatternGuards
623 | Opt_LiberalTypeSynonyms
624 | Opt_RankNTypes
625 | Opt_ImpredicativeTypes
626 | Opt_TypeOperators
627 | Opt_ExplicitNamespaces
628 | Opt_PackageImports
629 | Opt_ExplicitForAll
630 | Opt_AlternativeLayoutRule
631 | Opt_AlternativeLayoutRuleTransitional
632 | Opt_DatatypeContexts
633 | Opt_NondecreasingIndentation
634 | Opt_RelaxedLayout
635 | Opt_TraditionalRecordSyntax
636 | Opt_LambdaCase
637 | Opt_MultiWayIf
638 | Opt_BinaryLiterals
639 | Opt_NegativeLiterals
640 | Opt_EmptyCase
641 | Opt_PatternSynonyms
642 | Opt_PartialTypeSignatures
643 | Opt_NamedWildCards
644 | Opt_StaticPointers
645 deriving (Eq, Enum, Show)
646
647 type SigOf = Map ModuleName Module
648
649 getSigOf :: DynFlags -> ModuleName -> Maybe Module
650 getSigOf dflags n = Map.lookup n (sigOf dflags)
651
652 -- | Contains not only a collection of 'GeneralFlag's but also a plethora of
653 -- information relating to the compilation of a single file or GHC session
654 data DynFlags = DynFlags {
655 ghcMode :: GhcMode,
656 ghcLink :: GhcLink,
657 hscTarget :: HscTarget,
658 settings :: Settings,
659 -- See Note [Signature parameters in TcGblEnv and DynFlags]
660 sigOf :: SigOf, -- ^ Compiling an hs-boot against impl.
661 verbosity :: Int, -- ^ Verbosity level: see Note [Verbosity levels]
662 optLevel :: Int, -- ^ Optimisation level
663 simplPhases :: Int, -- ^ Number of simplifier phases
664 maxSimplIterations :: Int, -- ^ Max simplifier iterations
665 ruleCheck :: Maybe String,
666 strictnessBefore :: [Int], -- ^ Additional demand analysis
667
668 parMakeCount :: Maybe Int, -- ^ The number of modules to compile in parallel
669 -- in --make mode, where Nothing ==> compile as
670 -- many in parallel as there are CPUs.
671
672 enableTimeStats :: Bool, -- ^ Enable RTS timing statistics?
673 ghcHeapSize :: Maybe Int, -- ^ The heap size to set.
674
675 maxRelevantBinds :: Maybe Int, -- ^ Maximum number of bindings from the type envt
676 -- to show in type error messages
677 simplTickFactor :: Int, -- ^ Multiplier for simplifier ticks
678 specConstrThreshold :: Maybe Int, -- ^ Threshold for SpecConstr
679 specConstrCount :: Maybe Int, -- ^ Max number of specialisations for any one function
680 specConstrRecursive :: Int, -- ^ Max number of specialisations for recursive types
681 -- Not optional; otherwise ForceSpecConstr can diverge.
682 liberateCaseThreshold :: Maybe Int, -- ^ Threshold for LiberateCase
683 floatLamArgs :: Maybe Int, -- ^ Arg count for lambda floating
684 -- See CoreMonad.FloatOutSwitches
685
686 historySize :: Int,
687
688 cmdlineHcIncludes :: [String], -- ^ @\-\#includes@
689 importPaths :: [FilePath],
690 mainModIs :: Module,
691 mainFunIs :: Maybe String,
692 reductionDepth :: IntWithInf, -- ^ Typechecker maximum stack depth
693
694 thisPackage :: PackageKey, -- ^ name of package currently being compiled
695
696 -- ways
697 ways :: [Way], -- ^ Way flags from the command line
698 buildTag :: String, -- ^ The global \"way\" (e.g. \"p\" for prof)
699 rtsBuildTag :: String, -- ^ The RTS \"way\"
700
701 -- For object splitting
702 splitInfo :: Maybe (String,Int),
703
704 -- paths etc.
705 objectDir :: Maybe String,
706 dylibInstallName :: Maybe String,
707 hiDir :: Maybe String,
708 stubDir :: Maybe String,
709 dumpDir :: Maybe String,
710
711 objectSuf :: String,
712 hcSuf :: String,
713 hiSuf :: String,
714
715 canGenerateDynamicToo :: IORef Bool,
716 dynObjectSuf :: String,
717 dynHiSuf :: String,
718
719 -- Packages.isDllName needs to know whether a call is within a
720 -- single DLL or not. Normally it does this by seeing if the call
721 -- is to the same package, but for the ghc package, we split the
722 -- package between 2 DLLs. The dllSplit tells us which sets of
723 -- modules are in which package.
724 dllSplitFile :: Maybe FilePath,
725 dllSplit :: Maybe [Set String],
726
727 outputFile :: Maybe String,
728 dynOutputFile :: Maybe String,
729 outputHi :: Maybe String,
730 dynLibLoader :: DynLibLoader,
731
732 -- | This is set by 'DriverPipeline.runPipeline' based on where
733 -- its output is going.
734 dumpPrefix :: Maybe FilePath,
735
736 -- | Override the 'dumpPrefix' set by 'DriverPipeline.runPipeline'.
737 -- Set by @-ddump-file-prefix@
738 dumpPrefixForce :: Maybe FilePath,
739
740 ldInputs :: [Option],
741
742 includePaths :: [String],
743 libraryPaths :: [String],
744 frameworkPaths :: [String], -- used on darwin only
745 cmdlineFrameworks :: [String], -- ditto
746
747 rtsOpts :: Maybe String,
748 rtsOptsEnabled :: RtsOptsEnabled,
749 rtsOptsSuggestions :: Bool,
750
751 hpcDir :: String, -- ^ Path to store the .mix files
752
753 -- Plugins
754 pluginModNames :: [ModuleName],
755 pluginModNameOpts :: [(ModuleName,String)],
756
757 -- GHC API hooks
758 hooks :: Hooks,
759
760 -- For ghc -M
761 depMakefile :: FilePath,
762 depIncludePkgDeps :: Bool,
763 depExcludeMods :: [ModuleName],
764 depSuffixes :: [String],
765
766 -- Package flags
767 extraPkgConfs :: [PkgConfRef] -> [PkgConfRef],
768 -- ^ The @-package-db@ flags given on the command line, in the order
769 -- they appeared.
770
771 packageFlags :: [PackageFlag],
772 -- ^ The @-package@ and @-hide-package@ flags from the command-line
773 packageEnv :: Maybe FilePath,
774 -- ^ Filepath to the package environment file (if overriding default)
775
776 -- Package state
777 -- NB. do not modify this field, it is calculated by
778 -- Packages.initPackages
779 pkgDatabase :: Maybe [PackageConfig],
780 pkgState :: PackageState,
781
782 -- Temporary files
783 -- These have to be IORefs, because the defaultCleanupHandler needs to
784 -- know what to clean when an exception happens
785 filesToClean :: IORef [FilePath],
786 dirsToClean :: IORef (Map FilePath FilePath),
787 filesToNotIntermediateClean :: IORef [FilePath],
788 -- The next available suffix to uniquely name a temp file, updated atomically
789 nextTempSuffix :: IORef Int,
790
791 -- Names of files which were generated from -ddump-to-file; used to
792 -- track which ones we need to truncate because it's our first run
793 -- through
794 generatedDumps :: IORef (Set FilePath),
795
796 -- hsc dynamic flags
797 dumpFlags :: IntSet,
798 generalFlags :: IntSet,
799 warningFlags :: IntSet,
800 -- Don't change this without updating extensionFlags:
801 language :: Maybe Language,
802 -- | Safe Haskell mode
803 safeHaskell :: SafeHaskellMode,
804 safeInfer :: Bool,
805 safeInferred :: Bool,
806 -- We store the location of where some extension and flags were turned on so
807 -- we can produce accurate error messages when Safe Haskell fails due to
808 -- them.
809 thOnLoc :: SrcSpan,
810 newDerivOnLoc :: SrcSpan,
811 overlapInstLoc :: SrcSpan,
812 incoherentOnLoc :: SrcSpan,
813 pkgTrustOnLoc :: SrcSpan,
814 warnSafeOnLoc :: SrcSpan,
815 warnUnsafeOnLoc :: SrcSpan,
816 trustworthyOnLoc :: SrcSpan,
817 -- Don't change this without updating extensionFlags:
818 extensions :: [OnOff ExtensionFlag],
819 -- extensionFlags should always be equal to
820 -- flattenExtensionFlags language extensions
821 extensionFlags :: IntSet,
822
823 -- Unfolding control
824 -- See Note [Discounts and thresholds] in CoreUnfold
825 ufCreationThreshold :: Int,
826 ufUseThreshold :: Int,
827 ufFunAppDiscount :: Int,
828 ufDictDiscount :: Int,
829 ufKeenessFactor :: Float,
830 ufDearOp :: Int,
831
832 maxWorkerArgs :: Int,
833
834 ghciHistSize :: Int,
835
836 -- | MsgDoc output action: use "ErrUtils" instead of this if you can
837 log_action :: LogAction,
838 flushOut :: FlushOut,
839 flushErr :: FlushErr,
840
841 haddockOptions :: Maybe String,
842
843 -- | GHCi scripts specified by -ghci-script, in reverse order
844 ghciScripts :: [String],
845
846 -- Output style options
847 pprUserLength :: Int,
848 pprCols :: Int,
849 traceLevel :: Int, -- Standard level is 1. Less verbose is 0.
850
851 useUnicode :: Bool,
852
853 -- | what kind of {-# SCC #-} to add automatically
854 profAuto :: ProfAuto,
855
856 interactivePrint :: Maybe String,
857
858 llvmVersion :: IORef Int,
859
860 nextWrapperNum :: IORef (ModuleEnv Int),
861
862 -- | Machine dependant flags (-m<blah> stuff)
863 sseVersion :: Maybe SseVersion,
864 avx :: Bool,
865 avx2 :: Bool,
866 avx512cd :: Bool, -- Enable AVX-512 Conflict Detection Instructions.
867 avx512er :: Bool, -- Enable AVX-512 Exponential and Reciprocal Instructions.
868 avx512f :: Bool, -- Enable AVX-512 instructions.
869 avx512pf :: Bool, -- Enable AVX-512 PreFetch Instructions.
870
871 -- | Run-time linker information (what options we need, etc.)
872 rtldInfo :: IORef (Maybe LinkerInfo),
873
874 -- | Run-time compiler information
875 rtccInfo :: IORef (Maybe CompilerInfo),
876
877 -- Constants used to control the amount of optimization done.
878
879 -- | Max size, in bytes, of inline array allocations.
880 maxInlineAllocSize :: Int,
881
882 -- | Only inline memcpy if it generates no more than this many
883 -- pseudo (roughly: Cmm) instructions.
884 maxInlineMemcpyInsns :: Int,
885
886 -- | Only inline memset if it generates no more than this many
887 -- pseudo (roughly: Cmm) instructions.
888 maxInlineMemsetInsns :: Int
889 }
890
891 class HasDynFlags m where
892 getDynFlags :: m DynFlags
893
894 class ContainsDynFlags t where
895 extractDynFlags :: t -> DynFlags
896 replaceDynFlags :: t -> DynFlags -> t
897
898 data ProfAuto
899 = NoProfAuto -- ^ no SCC annotations added
900 | ProfAutoAll -- ^ top-level and nested functions are annotated
901 | ProfAutoTop -- ^ top-level functions annotated only
902 | ProfAutoExports -- ^ exported functions annotated only
903 | ProfAutoCalls -- ^ annotate call-sites
904 deriving (Eq,Enum)
905
906 data Settings = Settings {
907 sTargetPlatform :: Platform, -- Filled in by SysTools
908 sGhcUsagePath :: FilePath, -- Filled in by SysTools
909 sGhciUsagePath :: FilePath, -- ditto
910 sTopDir :: FilePath,
911 sTmpDir :: String, -- no trailing '/'
912 sProgramName :: String,
913 sProjectVersion :: String,
914 -- You shouldn't need to look things up in rawSettings directly.
915 -- They should have their own fields instead.
916 sRawSettings :: [(String, String)],
917 sExtraGccViaCFlags :: [String],
918 sSystemPackageConfig :: FilePath,
919 sLdSupportsCompactUnwind :: Bool,
920 sLdSupportsBuildId :: Bool,
921 sLdSupportsFilelist :: Bool,
922 sLdIsGnuLd :: Bool,
923 -- commands for particular phases
924 sPgm_L :: String,
925 sPgm_P :: (String,[Option]),
926 sPgm_F :: String,
927 sPgm_c :: (String,[Option]),
928 sPgm_s :: (String,[Option]),
929 sPgm_a :: (String,[Option]),
930 sPgm_l :: (String,[Option]),
931 sPgm_dll :: (String,[Option]),
932 sPgm_T :: String,
933 sPgm_sysman :: String,
934 sPgm_windres :: String,
935 sPgm_libtool :: String,
936 sPgm_lo :: (String,[Option]), -- LLVM: opt llvm optimiser
937 sPgm_lc :: (String,[Option]), -- LLVM: llc static compiler
938 -- options for particular phases
939 sOpt_L :: [String],
940 sOpt_P :: [String],
941 sOpt_F :: [String],
942 sOpt_c :: [String],
943 sOpt_a :: [String],
944 sOpt_l :: [String],
945 sOpt_windres :: [String],
946 sOpt_lo :: [String], -- LLVM: llvm optimiser
947 sOpt_lc :: [String], -- LLVM: llc static compiler
948
949 sPlatformConstants :: PlatformConstants
950 }
951
952 targetPlatform :: DynFlags -> Platform
953 targetPlatform dflags = sTargetPlatform (settings dflags)
954 programName :: DynFlags -> String
955 programName dflags = sProgramName (settings dflags)
956 projectVersion :: DynFlags -> String
957 projectVersion dflags = sProjectVersion (settings dflags)
958 ghcUsagePath :: DynFlags -> FilePath
959 ghcUsagePath dflags = sGhcUsagePath (settings dflags)
960 ghciUsagePath :: DynFlags -> FilePath
961 ghciUsagePath dflags = sGhciUsagePath (settings dflags)
962 topDir :: DynFlags -> FilePath
963 topDir dflags = sTopDir (settings dflags)
964 tmpDir :: DynFlags -> String
965 tmpDir dflags = sTmpDir (settings dflags)
966 rawSettings :: DynFlags -> [(String, String)]
967 rawSettings dflags = sRawSettings (settings dflags)
968 extraGccViaCFlags :: DynFlags -> [String]
969 extraGccViaCFlags dflags = sExtraGccViaCFlags (settings dflags)
970 systemPackageConfig :: DynFlags -> FilePath
971 systemPackageConfig dflags = sSystemPackageConfig (settings dflags)
972 pgm_L :: DynFlags -> String
973 pgm_L dflags = sPgm_L (settings dflags)
974 pgm_P :: DynFlags -> (String,[Option])
975 pgm_P dflags = sPgm_P (settings dflags)
976 pgm_F :: DynFlags -> String
977 pgm_F dflags = sPgm_F (settings dflags)
978 pgm_c :: DynFlags -> (String,[Option])
979 pgm_c dflags = sPgm_c (settings dflags)
980 pgm_s :: DynFlags -> (String,[Option])
981 pgm_s dflags = sPgm_s (settings dflags)
982 pgm_a :: DynFlags -> (String,[Option])
983 pgm_a dflags = sPgm_a (settings dflags)
984 pgm_l :: DynFlags -> (String,[Option])
985 pgm_l dflags = sPgm_l (settings dflags)
986 pgm_dll :: DynFlags -> (String,[Option])
987 pgm_dll dflags = sPgm_dll (settings dflags)
988 pgm_T :: DynFlags -> String
989 pgm_T dflags = sPgm_T (settings dflags)
990 pgm_sysman :: DynFlags -> String
991 pgm_sysman dflags = sPgm_sysman (settings dflags)
992 pgm_windres :: DynFlags -> String
993 pgm_windres dflags = sPgm_windres (settings dflags)
994 pgm_libtool :: DynFlags -> String
995 pgm_libtool dflags = sPgm_libtool (settings dflags)
996 pgm_lo :: DynFlags -> (String,[Option])
997 pgm_lo dflags = sPgm_lo (settings dflags)
998 pgm_lc :: DynFlags -> (String,[Option])
999 pgm_lc dflags = sPgm_lc (settings dflags)
1000 opt_L :: DynFlags -> [String]
1001 opt_L dflags = sOpt_L (settings dflags)
1002 opt_P :: DynFlags -> [String]
1003 opt_P dflags = concatMap (wayOptP (targetPlatform dflags)) (ways dflags)
1004 ++ sOpt_P (settings dflags)
1005 opt_F :: DynFlags -> [String]
1006 opt_F dflags = sOpt_F (settings dflags)
1007 opt_c :: DynFlags -> [String]
1008 opt_c dflags = concatMap (wayOptc (targetPlatform dflags)) (ways dflags)
1009 ++ sOpt_c (settings dflags)
1010 opt_a :: DynFlags -> [String]
1011 opt_a dflags = sOpt_a (settings dflags)
1012 opt_l :: DynFlags -> [String]
1013 opt_l dflags = concatMap (wayOptl (targetPlatform dflags)) (ways dflags)
1014 ++ sOpt_l (settings dflags)
1015 opt_windres :: DynFlags -> [String]
1016 opt_windres dflags = sOpt_windres (settings dflags)
1017 opt_lo :: DynFlags -> [String]
1018 opt_lo dflags = sOpt_lo (settings dflags)
1019 opt_lc :: DynFlags -> [String]
1020 opt_lc dflags = sOpt_lc (settings dflags)
1021
1022 -- | The directory for this version of ghc in the user's app directory
1023 -- (typically something like @~/.ghc/x86_64-linux-7.6.3@)
1024 --
1025 versionedAppDir :: DynFlags -> IO FilePath
1026 versionedAppDir dflags = do
1027 appdir <- getAppUserDataDirectory (programName dflags)
1028 return $ appdir </> (TARGET_ARCH ++ '-':TARGET_OS ++ '-':projectVersion dflags)
1029
1030 -- | The target code type of the compilation (if any).
1031 --
1032 -- Whenever you change the target, also make sure to set 'ghcLink' to
1033 -- something sensible.
1034 --
1035 -- 'HscNothing' can be used to avoid generating any output, however, note
1036 -- that:
1037 --
1038 -- * If a program uses Template Haskell the typechecker may try to run code
1039 -- from an imported module. This will fail if no code has been generated
1040 -- for this module. You can use 'GHC.needsTemplateHaskell' to detect
1041 -- whether this might be the case and choose to either switch to a
1042 -- different target or avoid typechecking such modules. (The latter may be
1043 -- preferable for security reasons.)
1044 --
1045 data HscTarget
1046 = HscC -- ^ Generate C code.
1047 | HscAsm -- ^ Generate assembly using the native code generator.
1048 | HscLlvm -- ^ Generate assembly using the llvm code generator.
1049 | HscInterpreted -- ^ Generate bytecode. (Requires 'LinkInMemory')
1050 | HscNothing -- ^ Don't generate any code. See notes above.
1051 deriving (Eq, Show)
1052
1053 -- | Will this target result in an object file on the disk?
1054 isObjectTarget :: HscTarget -> Bool
1055 isObjectTarget HscC = True
1056 isObjectTarget HscAsm = True
1057 isObjectTarget HscLlvm = True
1058 isObjectTarget _ = False
1059
1060 -- | Does this target retain *all* top-level bindings for a module,
1061 -- rather than just the exported bindings, in the TypeEnv and compiled
1062 -- code (if any)? In interpreted mode we do this, so that GHCi can
1063 -- call functions inside a module. In HscNothing mode we also do it,
1064 -- so that Haddock can get access to the GlobalRdrEnv for a module
1065 -- after typechecking it.
1066 targetRetainsAllBindings :: HscTarget -> Bool
1067 targetRetainsAllBindings HscInterpreted = True
1068 targetRetainsAllBindings HscNothing = True
1069 targetRetainsAllBindings _ = False
1070
1071 -- | The 'GhcMode' tells us whether we're doing multi-module
1072 -- compilation (controlled via the "GHC" API) or one-shot
1073 -- (single-module) compilation. This makes a difference primarily to
1074 -- the "Finder": in one-shot mode we look for interface files for
1075 -- imported modules, but in multi-module mode we look for source files
1076 -- in order to check whether they need to be recompiled.
1077 data GhcMode
1078 = CompManager -- ^ @\-\-make@, GHCi, etc.
1079 | OneShot -- ^ @ghc -c Foo.hs@
1080 | MkDepend -- ^ @ghc -M@, see "Finder" for why we need this
1081 deriving Eq
1082
1083 instance Outputable GhcMode where
1084 ppr CompManager = ptext (sLit "CompManager")
1085 ppr OneShot = ptext (sLit "OneShot")
1086 ppr MkDepend = ptext (sLit "MkDepend")
1087
1088 isOneShot :: GhcMode -> Bool
1089 isOneShot OneShot = True
1090 isOneShot _other = False
1091
1092 -- | What to do in the link step, if there is one.
1093 data GhcLink
1094 = NoLink -- ^ Don't link at all
1095 | LinkBinary -- ^ Link object code into a binary
1096 | LinkInMemory -- ^ Use the in-memory dynamic linker (works for both
1097 -- bytecode and object code).
1098 | LinkDynLib -- ^ Link objects into a dynamic lib (DLL on Windows, DSO on ELF platforms)
1099 | LinkStaticLib -- ^ Link objects into a static lib
1100 deriving (Eq, Show)
1101
1102 isNoLink :: GhcLink -> Bool
1103 isNoLink NoLink = True
1104 isNoLink _ = False
1105
1106 -- | We accept flags which make packages visible, but how they select
1107 -- the package varies; this data type reflects what selection criterion
1108 -- is used.
1109 data PackageArg =
1110 PackageArg String -- ^ @-package@, by 'PackageName'
1111 | PackageIdArg String -- ^ @-package-id@, by 'SourcePackageId'
1112 | PackageKeyArg String -- ^ @-package-key@, by 'InstalledPackageId'
1113 deriving (Eq, Show)
1114
1115 -- | Represents the renaming that may be associated with an exposed
1116 -- package, e.g. the @rns@ part of @-package "foo (rns)"@.
1117 --
1118 -- Here are some example parsings of the package flags (where
1119 -- a string literal is punned to be a 'ModuleName':
1120 --
1121 -- * @-package foo@ is @ModRenaming True []@
1122 -- * @-package foo ()@ is @ModRenaming False []@
1123 -- * @-package foo (A)@ is @ModRenaming False [("A", "A")]@
1124 -- * @-package foo (A as B)@ is @ModRenaming False [("A", "B")]@
1125 -- * @-package foo with (A as B)@ is @ModRenaming True [("A", "B")]@
1126 data ModRenaming = ModRenaming {
1127 modRenamingWithImplicit :: Bool, -- ^ Bring all exposed modules into scope?
1128 modRenamings :: [(ModuleName, ModuleName)] -- ^ Bring module @m@ into scope
1129 -- under name @n@.
1130 } deriving (Eq)
1131
1132 -- | Flags for manipulating packages.
1133 data PackageFlag
1134 = ExposePackage PackageArg ModRenaming -- ^ @-package@, @-package-id@
1135 -- and @-package-key@
1136 | HidePackage String -- ^ @-hide-package@
1137 | IgnorePackage String -- ^ @-ignore-package@
1138 | TrustPackage String -- ^ @-trust-package@
1139 | DistrustPackage String -- ^ @-distrust-package@
1140 deriving (Eq)
1141
1142 defaultHscTarget :: Platform -> HscTarget
1143 defaultHscTarget = defaultObjectTarget
1144
1145 -- | The 'HscTarget' value corresponding to the default way to create
1146 -- object files on the current platform.
1147 defaultObjectTarget :: Platform -> HscTarget
1148 defaultObjectTarget platform
1149 | platformUnregisterised platform = HscC
1150 | cGhcWithNativeCodeGen == "YES" = HscAsm
1151 | otherwise = HscLlvm
1152
1153 tablesNextToCode :: DynFlags -> Bool
1154 tablesNextToCode dflags
1155 = mkTablesNextToCode (platformUnregisterised (targetPlatform dflags))
1156
1157 -- Determines whether we will be compiling
1158 -- info tables that reside just before the entry code, or with an
1159 -- indirection to the entry code. See TABLES_NEXT_TO_CODE in
1160 -- includes/rts/storage/InfoTables.h.
1161 mkTablesNextToCode :: Bool -> Bool
1162 mkTablesNextToCode unregisterised
1163 = not unregisterised && cGhcEnableTablesNextToCode == "YES"
1164
1165 data DynLibLoader
1166 = Deployable
1167 | SystemDependent
1168 deriving Eq
1169
1170 data RtsOptsEnabled = RtsOptsNone | RtsOptsSafeOnly | RtsOptsAll
1171 deriving (Show)
1172
1173 -----------------------------------------------------------------------------
1174 -- Ways
1175
1176 -- The central concept of a "way" is that all objects in a given
1177 -- program must be compiled in the same "way". Certain options change
1178 -- parameters of the virtual machine, eg. profiling adds an extra word
1179 -- to the object header, so profiling objects cannot be linked with
1180 -- non-profiling objects.
1181
1182 -- After parsing the command-line options, we determine which "way" we
1183 -- are building - this might be a combination way, eg. profiling+threaded.
1184
1185 -- We then find the "build-tag" associated with this way, and this
1186 -- becomes the suffix used to find .hi files and libraries used in
1187 -- this compilation.
1188
1189 data Way
1190 = WayCustom String -- for GHC API clients building custom variants
1191 | WayThreaded
1192 | WayDebug
1193 | WayProf
1194 | WayEventLog
1195 | WayPar
1196 | WayDyn
1197 deriving (Eq, Ord, Show)
1198
1199 allowed_combination :: [Way] -> Bool
1200 allowed_combination way = and [ x `allowedWith` y
1201 | x <- way, y <- way, x < y ]
1202 where
1203 -- Note ordering in these tests: the left argument is
1204 -- <= the right argument, according to the Ord instance
1205 -- on Way above.
1206
1207 -- dyn is allowed with everything
1208 _ `allowedWith` WayDyn = True
1209 WayDyn `allowedWith` _ = True
1210
1211 -- debug is allowed with everything
1212 _ `allowedWith` WayDebug = True
1213 WayDebug `allowedWith` _ = True
1214
1215 (WayCustom {}) `allowedWith` _ = True
1216 WayThreaded `allowedWith` WayProf = True
1217 WayThreaded `allowedWith` WayEventLog = True
1218 _ `allowedWith` _ = False
1219
1220 mkBuildTag :: [Way] -> String
1221 mkBuildTag ways = concat (intersperse "_" (map wayTag ways))
1222
1223 wayTag :: Way -> String
1224 wayTag (WayCustom xs) = xs
1225 wayTag WayThreaded = "thr"
1226 wayTag WayDebug = "debug"
1227 wayTag WayDyn = "dyn"
1228 wayTag WayProf = "p"
1229 wayTag WayEventLog = "l"
1230 wayTag WayPar = "mp"
1231
1232 wayRTSOnly :: Way -> Bool
1233 wayRTSOnly (WayCustom {}) = False
1234 wayRTSOnly WayThreaded = True
1235 wayRTSOnly WayDebug = True
1236 wayRTSOnly WayDyn = False
1237 wayRTSOnly WayProf = False
1238 wayRTSOnly WayEventLog = True
1239 wayRTSOnly WayPar = False
1240
1241 wayDesc :: Way -> String
1242 wayDesc (WayCustom xs) = xs
1243 wayDesc WayThreaded = "Threaded"
1244 wayDesc WayDebug = "Debug"
1245 wayDesc WayDyn = "Dynamic"
1246 wayDesc WayProf = "Profiling"
1247 wayDesc WayEventLog = "RTS Event Logging"
1248 wayDesc WayPar = "Parallel"
1249
1250 -- Turn these flags on when enabling this way
1251 wayGeneralFlags :: Platform -> Way -> [GeneralFlag]
1252 wayGeneralFlags _ (WayCustom {}) = []
1253 wayGeneralFlags _ WayThreaded = []
1254 wayGeneralFlags _ WayDebug = []
1255 wayGeneralFlags _ WayDyn = [Opt_PIC]
1256 -- We could get away without adding -fPIC when compiling the
1257 -- modules of a program that is to be linked with -dynamic; the
1258 -- program itself does not need to be position-independent, only
1259 -- the libraries need to be. HOWEVER, GHCi links objects into a
1260 -- .so before loading the .so using the system linker. Since only
1261 -- PIC objects can be linked into a .so, we have to compile even
1262 -- modules of the main program with -fPIC when using -dynamic.
1263 wayGeneralFlags _ WayProf = [Opt_SccProfilingOn]
1264 wayGeneralFlags _ WayEventLog = []
1265 wayGeneralFlags _ WayPar = [Opt_Parallel]
1266
1267 -- Turn these flags off when enabling this way
1268 wayUnsetGeneralFlags :: Platform -> Way -> [GeneralFlag]
1269 wayUnsetGeneralFlags _ (WayCustom {}) = []
1270 wayUnsetGeneralFlags _ WayThreaded = []
1271 wayUnsetGeneralFlags _ WayDebug = []
1272 wayUnsetGeneralFlags _ WayDyn = [-- There's no point splitting objects
1273 -- when we're going to be dynamically
1274 -- linking. Plus it breaks compilation
1275 -- on OSX x86.
1276 Opt_SplitObjs]
1277 wayUnsetGeneralFlags _ WayProf = []
1278 wayUnsetGeneralFlags _ WayEventLog = []
1279 wayUnsetGeneralFlags _ WayPar = []
1280
1281 wayExtras :: Platform -> Way -> DynFlags -> DynFlags
1282 wayExtras _ (WayCustom {}) dflags = dflags
1283 wayExtras _ WayThreaded dflags = dflags
1284 wayExtras _ WayDebug dflags = dflags
1285 wayExtras _ WayDyn dflags = dflags
1286 wayExtras _ WayProf dflags = dflags
1287 wayExtras _ WayEventLog dflags = dflags
1288 wayExtras _ WayPar dflags = exposePackage' "concurrent" dflags
1289
1290 wayOptc :: Platform -> Way -> [String]
1291 wayOptc _ (WayCustom {}) = []
1292 wayOptc platform WayThreaded = case platformOS platform of
1293 OSOpenBSD -> ["-pthread"]
1294 OSNetBSD -> ["-pthread"]
1295 _ -> []
1296 wayOptc _ WayDebug = []
1297 wayOptc _ WayDyn = []
1298 wayOptc _ WayProf = ["-DPROFILING"]
1299 wayOptc _ WayEventLog = ["-DTRACING"]
1300 wayOptc _ WayPar = ["-DPAR", "-w"]
1301
1302 wayOptl :: Platform -> Way -> [String]
1303 wayOptl _ (WayCustom {}) = []
1304 wayOptl platform WayThreaded =
1305 case platformOS platform of
1306 -- FreeBSD's default threading library is the KSE-based M:N libpthread,
1307 -- which GHC has some problems with. It's currently not clear whether
1308 -- the problems are our fault or theirs, but it seems that using the
1309 -- alternative 1:1 threading library libthr works around it:
1310 OSFreeBSD -> ["-lthr"]
1311 OSOpenBSD -> ["-pthread"]
1312 OSNetBSD -> ["-pthread"]
1313 _ -> []
1314 wayOptl _ WayDebug = []
1315 wayOptl _ WayDyn = []
1316 wayOptl _ WayProf = []
1317 wayOptl _ WayEventLog = []
1318 wayOptl _ WayPar = ["-L${PVM_ROOT}/lib/${PVM_ARCH}",
1319 "-lpvm3",
1320 "-lgpvm3"]
1321
1322 wayOptP :: Platform -> Way -> [String]
1323 wayOptP _ (WayCustom {}) = []
1324 wayOptP _ WayThreaded = []
1325 wayOptP _ WayDebug = []
1326 wayOptP _ WayDyn = []
1327 wayOptP _ WayProf = ["-DPROFILING"]
1328 wayOptP _ WayEventLog = ["-DTRACING"]
1329 wayOptP _ WayPar = ["-D__PARALLEL_HASKELL__"]
1330
1331 whenGeneratingDynamicToo :: MonadIO m => DynFlags -> m () -> m ()
1332 whenGeneratingDynamicToo dflags f = ifGeneratingDynamicToo dflags f (return ())
1333
1334 ifGeneratingDynamicToo :: MonadIO m => DynFlags -> m a -> m a -> m a
1335 ifGeneratingDynamicToo dflags f g = generateDynamicTooConditional dflags f g g
1336
1337 whenCannotGenerateDynamicToo :: MonadIO m => DynFlags -> m () -> m ()
1338 whenCannotGenerateDynamicToo dflags f
1339 = ifCannotGenerateDynamicToo dflags f (return ())
1340
1341 ifCannotGenerateDynamicToo :: MonadIO m => DynFlags -> m a -> m a -> m a
1342 ifCannotGenerateDynamicToo dflags f g
1343 = generateDynamicTooConditional dflags g f g
1344
1345 generateDynamicTooConditional :: MonadIO m
1346 => DynFlags -> m a -> m a -> m a -> m a
1347 generateDynamicTooConditional dflags canGen cannotGen notTryingToGen
1348 = if gopt Opt_BuildDynamicToo dflags
1349 then do let ref = canGenerateDynamicToo dflags
1350 b <- liftIO $ readIORef ref
1351 if b then canGen else cannotGen
1352 else notTryingToGen
1353
1354 dynamicTooMkDynamicDynFlags :: DynFlags -> DynFlags
1355 dynamicTooMkDynamicDynFlags dflags0
1356 = let dflags1 = addWay' WayDyn dflags0
1357 dflags2 = dflags1 {
1358 outputFile = dynOutputFile dflags1,
1359 hiSuf = dynHiSuf dflags1,
1360 objectSuf = dynObjectSuf dflags1
1361 }
1362 dflags3 = updateWays dflags2
1363 dflags4 = gopt_unset dflags3 Opt_BuildDynamicToo
1364 in dflags4
1365
1366 -----------------------------------------------------------------------------
1367
1368 -- | Used by 'GHC.runGhc' to partially initialize a new 'DynFlags' value
1369 initDynFlags :: DynFlags -> IO DynFlags
1370 initDynFlags dflags = do
1371 let -- We can't build with dynamic-too on Windows, as labels before
1372 -- the fork point are different depending on whether we are
1373 -- building dynamically or not.
1374 platformCanGenerateDynamicToo
1375 = platformOS (targetPlatform dflags) /= OSMinGW32
1376 refCanGenerateDynamicToo <- newIORef platformCanGenerateDynamicToo
1377 refNextTempSuffix <- newIORef 0
1378 refFilesToClean <- newIORef []
1379 refDirsToClean <- newIORef Map.empty
1380 refFilesToNotIntermediateClean <- newIORef []
1381 refGeneratedDumps <- newIORef Set.empty
1382 refLlvmVersion <- newIORef 28
1383 refRtldInfo <- newIORef Nothing
1384 refRtccInfo <- newIORef Nothing
1385 wrapperNum <- newIORef emptyModuleEnv
1386 canUseUnicode <- do let enc = localeEncoding
1387 str = "‘’"
1388 (withCString enc str $ \cstr ->
1389 do str' <- peekCString enc cstr
1390 return (str == str'))
1391 `catchIOError` \_ -> return False
1392 return dflags{
1393 canGenerateDynamicToo = refCanGenerateDynamicToo,
1394 nextTempSuffix = refNextTempSuffix,
1395 filesToClean = refFilesToClean,
1396 dirsToClean = refDirsToClean,
1397 filesToNotIntermediateClean = refFilesToNotIntermediateClean,
1398 generatedDumps = refGeneratedDumps,
1399 llvmVersion = refLlvmVersion,
1400 nextWrapperNum = wrapperNum,
1401 useUnicode = canUseUnicode,
1402 rtldInfo = refRtldInfo,
1403 rtccInfo = refRtccInfo
1404 }
1405
1406 -- | The normal 'DynFlags'. Note that they are not suitable for use in this form
1407 -- and must be fully initialized by 'GHC.runGhc' first.
1408 defaultDynFlags :: Settings -> DynFlags
1409 defaultDynFlags mySettings =
1410 -- See Note [Updating flag description in the User's Guide]
1411 DynFlags {
1412 ghcMode = CompManager,
1413 ghcLink = LinkBinary,
1414 hscTarget = defaultHscTarget (sTargetPlatform mySettings),
1415 sigOf = Map.empty,
1416 verbosity = 0,
1417 optLevel = 0,
1418 simplPhases = 2,
1419 maxSimplIterations = 4,
1420 ruleCheck = Nothing,
1421 maxRelevantBinds = Just 6,
1422 simplTickFactor = 100,
1423 specConstrThreshold = Just 2000,
1424 specConstrCount = Just 3,
1425 specConstrRecursive = 3,
1426 liberateCaseThreshold = Just 2000,
1427 floatLamArgs = Just 0, -- Default: float only if no fvs
1428
1429 historySize = 20,
1430 strictnessBefore = [],
1431
1432 parMakeCount = Just 1,
1433
1434 enableTimeStats = False,
1435 ghcHeapSize = Nothing,
1436
1437 cmdlineHcIncludes = [],
1438 importPaths = ["."],
1439 mainModIs = mAIN,
1440 mainFunIs = Nothing,
1441 reductionDepth = treatZeroAsInf mAX_REDUCTION_DEPTH,
1442
1443 thisPackage = mainPackageKey,
1444
1445 objectDir = Nothing,
1446 dylibInstallName = Nothing,
1447 hiDir = Nothing,
1448 stubDir = Nothing,
1449 dumpDir = Nothing,
1450
1451 objectSuf = phaseInputExt StopLn,
1452 hcSuf = phaseInputExt HCc,
1453 hiSuf = "hi",
1454
1455 canGenerateDynamicToo = panic "defaultDynFlags: No canGenerateDynamicToo",
1456 dynObjectSuf = "dyn_" ++ phaseInputExt StopLn,
1457 dynHiSuf = "dyn_hi",
1458
1459 dllSplitFile = Nothing,
1460 dllSplit = Nothing,
1461
1462 pluginModNames = [],
1463 pluginModNameOpts = [],
1464 hooks = emptyHooks,
1465
1466 outputFile = Nothing,
1467 dynOutputFile = Nothing,
1468 outputHi = Nothing,
1469 dynLibLoader = SystemDependent,
1470 dumpPrefix = Nothing,
1471 dumpPrefixForce = Nothing,
1472 ldInputs = [],
1473 includePaths = [],
1474 libraryPaths = [],
1475 frameworkPaths = [],
1476 cmdlineFrameworks = [],
1477 rtsOpts = Nothing,
1478 rtsOptsEnabled = RtsOptsSafeOnly,
1479 rtsOptsSuggestions = True,
1480
1481 hpcDir = ".hpc",
1482
1483 extraPkgConfs = id,
1484 packageFlags = [],
1485 packageEnv = Nothing,
1486 pkgDatabase = Nothing,
1487 -- This gets filled in with GHC.setSessionDynFlags
1488 pkgState = emptyPackageState,
1489 ways = defaultWays mySettings,
1490 buildTag = mkBuildTag (defaultWays mySettings),
1491 rtsBuildTag = mkBuildTag (defaultWays mySettings),
1492 splitInfo = Nothing,
1493 settings = mySettings,
1494 -- ghc -M values
1495 depMakefile = "Makefile",
1496 depIncludePkgDeps = False,
1497 depExcludeMods = [],
1498 depSuffixes = [],
1499 -- end of ghc -M values
1500 nextTempSuffix = panic "defaultDynFlags: No nextTempSuffix",
1501 filesToClean = panic "defaultDynFlags: No filesToClean",
1502 dirsToClean = panic "defaultDynFlags: No dirsToClean",
1503 filesToNotIntermediateClean = panic "defaultDynFlags: No filesToNotIntermediateClean",
1504 generatedDumps = panic "defaultDynFlags: No generatedDumps",
1505 haddockOptions = Nothing,
1506 dumpFlags = IntSet.empty,
1507 generalFlags = IntSet.fromList (map fromEnum (defaultFlags mySettings)),
1508 warningFlags = IntSet.fromList (map fromEnum standardWarnings),
1509 ghciScripts = [],
1510 language = Nothing,
1511 safeHaskell = Sf_None,
1512 safeInfer = True,
1513 safeInferred = True,
1514 thOnLoc = noSrcSpan,
1515 newDerivOnLoc = noSrcSpan,
1516 overlapInstLoc = noSrcSpan,
1517 incoherentOnLoc = noSrcSpan,
1518 pkgTrustOnLoc = noSrcSpan,
1519 warnSafeOnLoc = noSrcSpan,
1520 warnUnsafeOnLoc = noSrcSpan,
1521 trustworthyOnLoc = noSrcSpan,
1522 extensions = [],
1523 extensionFlags = flattenExtensionFlags Nothing [],
1524
1525 -- The ufCreationThreshold threshold must be reasonably high to
1526 -- take account of possible discounts.
1527 -- E.g. 450 is not enough in 'fulsom' for Interval.sqr to inline
1528 -- into Csg.calc (The unfolding for sqr never makes it into the
1529 -- interface file.)
1530 ufCreationThreshold = 750,
1531 ufUseThreshold = 60,
1532 ufFunAppDiscount = 60,
1533 -- Be fairly keen to inline a fuction if that means
1534 -- we'll be able to pick the right method from a dictionary
1535 ufDictDiscount = 30,
1536 ufKeenessFactor = 1.5,
1537 ufDearOp = 40,
1538
1539 maxWorkerArgs = 10,
1540
1541 ghciHistSize = 50, -- keep a log of length 50 by default
1542
1543 log_action = defaultLogAction,
1544 flushOut = defaultFlushOut,
1545 flushErr = defaultFlushErr,
1546 pprUserLength = 5,
1547 pprCols = 100,
1548 useUnicode = False,
1549 traceLevel = 1,
1550 profAuto = NoProfAuto,
1551 llvmVersion = panic "defaultDynFlags: No llvmVersion",
1552 interactivePrint = Nothing,
1553 nextWrapperNum = panic "defaultDynFlags: No nextWrapperNum",
1554 sseVersion = Nothing,
1555 avx = False,
1556 avx2 = False,
1557 avx512cd = False,
1558 avx512er = False,
1559 avx512f = False,
1560 avx512pf = False,
1561 rtldInfo = panic "defaultDynFlags: no rtldInfo",
1562 rtccInfo = panic "defaultDynFlags: no rtccInfo",
1563
1564 maxInlineAllocSize = 128,
1565 maxInlineMemcpyInsns = 32,
1566 maxInlineMemsetInsns = 32
1567 }
1568
1569 defaultWays :: Settings -> [Way]
1570 defaultWays settings = if pc_DYNAMIC_BY_DEFAULT (sPlatformConstants settings)
1571 then [WayDyn]
1572 else []
1573
1574 interpWays :: [Way]
1575 interpWays = if dynamicGhc
1576 then [WayDyn]
1577 else []
1578
1579 --------------------------------------------------------------------------
1580
1581 type FatalMessager = String -> IO ()
1582 type LogAction = DynFlags -> Severity -> SrcSpan -> PprStyle -> MsgDoc -> IO ()
1583
1584 defaultFatalMessager :: FatalMessager
1585 defaultFatalMessager = hPutStrLn stderr
1586
1587 defaultLogAction :: LogAction
1588 defaultLogAction dflags severity srcSpan style msg
1589 = case severity of
1590 SevOutput -> printSDoc msg style
1591 SevDump -> printSDoc (msg $$ blankLine) style
1592 SevInteractive -> putStrSDoc msg style
1593 SevInfo -> printErrs msg style
1594 SevFatal -> printErrs msg style
1595 _ -> do hPutChar stderr '\n'
1596 printErrs (mkLocMessage severity srcSpan msg) style
1597 -- careful (#2302): printErrs prints in UTF-8,
1598 -- whereas converting to string first and using
1599 -- hPutStr would just emit the low 8 bits of
1600 -- each unicode char.
1601 where printSDoc = defaultLogActionHPrintDoc dflags stdout
1602 printErrs = defaultLogActionHPrintDoc dflags stderr
1603 putStrSDoc = defaultLogActionHPutStrDoc dflags stdout
1604
1605 defaultLogActionHPrintDoc :: DynFlags -> Handle -> SDoc -> PprStyle -> IO ()
1606 defaultLogActionHPrintDoc dflags h d sty
1607 = defaultLogActionHPutStrDoc dflags h (d $$ text "") sty
1608 -- Adds a newline
1609
1610 defaultLogActionHPutStrDoc :: DynFlags -> Handle -> SDoc -> PprStyle -> IO ()
1611 defaultLogActionHPutStrDoc dflags h d sty
1612 = Pretty.printDoc_ Pretty.PageMode (pprCols dflags) h doc
1613 where -- Don't add a newline at the end, so that successive
1614 -- calls to this log-action can output all on the same line
1615 doc = runSDoc d (initSDocContext dflags sty)
1616
1617 newtype FlushOut = FlushOut (IO ())
1618
1619 defaultFlushOut :: FlushOut
1620 defaultFlushOut = FlushOut $ hFlush stdout
1621
1622 newtype FlushErr = FlushErr (IO ())
1623
1624 defaultFlushErr :: FlushErr
1625 defaultFlushErr = FlushErr $ hFlush stderr
1626
1627 {-
1628 Note [Verbosity levels]
1629 ~~~~~~~~~~~~~~~~~~~~~~~
1630 0 | print errors & warnings only
1631 1 | minimal verbosity: print "compiling M ... done." for each module.
1632 2 | equivalent to -dshow-passes
1633 3 | equivalent to existing "ghc -v"
1634 4 | "ghc -v -ddump-most"
1635 5 | "ghc -v -ddump-all"
1636 -}
1637
1638 data OnOff a = On a
1639 | Off a
1640
1641 -- OnOffs accumulate in reverse order, so we use foldr in order to
1642 -- process them in the right order
1643 flattenExtensionFlags :: Maybe Language -> [OnOff ExtensionFlag] -> IntSet
1644 flattenExtensionFlags ml = foldr f defaultExtensionFlags
1645 where f (On f) flags = IntSet.insert (fromEnum f) flags
1646 f (Off f) flags = IntSet.delete (fromEnum f) flags
1647 defaultExtensionFlags = IntSet.fromList (map fromEnum (languageExtensions ml))
1648
1649 languageExtensions :: Maybe Language -> [ExtensionFlag]
1650
1651 languageExtensions Nothing
1652 -- Nothing => the default case
1653 = Opt_NondecreasingIndentation -- This has been on by default for some time
1654 : delete Opt_DatatypeContexts -- The Haskell' committee decided to
1655 -- remove datatype contexts from the
1656 -- language:
1657 -- http://www.haskell.org/pipermail/haskell-prime/2011-January/003335.html
1658 (languageExtensions (Just Haskell2010))
1659
1660 -- NB: MonoPatBinds is no longer the default
1661
1662 languageExtensions (Just Haskell98)
1663 = [Opt_ImplicitPrelude,
1664 Opt_MonomorphismRestriction,
1665 Opt_NPlusKPatterns,
1666 Opt_DatatypeContexts,
1667 Opt_TraditionalRecordSyntax,
1668 Opt_NondecreasingIndentation
1669 -- strictly speaking non-standard, but we always had this
1670 -- on implicitly before the option was added in 7.1, and
1671 -- turning it off breaks code, so we're keeping it on for
1672 -- backwards compatibility. Cabal uses -XHaskell98 by
1673 -- default unless you specify another language.
1674 ]
1675
1676 languageExtensions (Just Haskell2010)
1677 = [Opt_ImplicitPrelude,
1678 Opt_MonomorphismRestriction,
1679 Opt_DatatypeContexts,
1680 Opt_TraditionalRecordSyntax,
1681 Opt_EmptyDataDecls,
1682 Opt_ForeignFunctionInterface,
1683 Opt_PatternGuards,
1684 Opt_DoAndIfThenElse,
1685 Opt_RelaxedPolyRec]
1686
1687 -- | Test whether a 'DumpFlag' is set
1688 dopt :: DumpFlag -> DynFlags -> Bool
1689 dopt f dflags = (fromEnum f `IntSet.member` dumpFlags dflags)
1690 || (verbosity dflags >= 4 && enableIfVerbose f)
1691 where enableIfVerbose Opt_D_dump_tc_trace = False
1692 enableIfVerbose Opt_D_dump_rn_trace = False
1693 enableIfVerbose Opt_D_dump_cs_trace = False
1694 enableIfVerbose Opt_D_dump_if_trace = False
1695 enableIfVerbose Opt_D_dump_vt_trace = False
1696 enableIfVerbose Opt_D_dump_tc = False
1697 enableIfVerbose Opt_D_dump_rn = False
1698 enableIfVerbose Opt_D_dump_rn_stats = False
1699 enableIfVerbose Opt_D_dump_hi_diffs = False
1700 enableIfVerbose Opt_D_verbose_core2core = False
1701 enableIfVerbose Opt_D_verbose_stg2stg = False
1702 enableIfVerbose Opt_D_dump_splices = False
1703 enableIfVerbose Opt_D_th_dec_file = False
1704 enableIfVerbose Opt_D_dump_rule_firings = False
1705 enableIfVerbose Opt_D_dump_rule_rewrites = False
1706 enableIfVerbose Opt_D_dump_simpl_trace = False
1707 enableIfVerbose Opt_D_dump_rtti = False
1708 enableIfVerbose Opt_D_dump_inlinings = False
1709 enableIfVerbose Opt_D_dump_core_stats = False
1710 enableIfVerbose Opt_D_dump_asm_stats = False
1711 enableIfVerbose Opt_D_dump_types = False
1712 enableIfVerbose Opt_D_dump_simpl_iterations = False
1713 enableIfVerbose Opt_D_dump_ticked = False
1714 enableIfVerbose Opt_D_dump_view_pattern_commoning = False
1715 enableIfVerbose Opt_D_dump_mod_cycles = False
1716 enableIfVerbose Opt_D_dump_mod_map = False
1717 enableIfVerbose _ = True
1718
1719 -- | Set a 'DumpFlag'
1720 dopt_set :: DynFlags -> DumpFlag -> DynFlags
1721 dopt_set dfs f = dfs{ dumpFlags = IntSet.insert (fromEnum f) (dumpFlags dfs) }
1722
1723 -- | Unset a 'DumpFlag'
1724 dopt_unset :: DynFlags -> DumpFlag -> DynFlags
1725 dopt_unset dfs f = dfs{ dumpFlags = IntSet.delete (fromEnum f) (dumpFlags dfs) }
1726
1727 -- | Test whether a 'GeneralFlag' is set
1728 gopt :: GeneralFlag -> DynFlags -> Bool
1729 gopt f dflags = fromEnum f `IntSet.member` generalFlags dflags
1730
1731 -- | Set a 'GeneralFlag'
1732 gopt_set :: DynFlags -> GeneralFlag -> DynFlags
1733 gopt_set dfs f = dfs{ generalFlags = IntSet.insert (fromEnum f) (generalFlags dfs) }
1734
1735 -- | Unset a 'GeneralFlag'
1736 gopt_unset :: DynFlags -> GeneralFlag -> DynFlags
1737 gopt_unset dfs f = dfs{ generalFlags = IntSet.delete (fromEnum f) (generalFlags dfs) }
1738
1739 -- | Test whether a 'WarningFlag' is set
1740 wopt :: WarningFlag -> DynFlags -> Bool
1741 wopt f dflags = fromEnum f `IntSet.member` warningFlags dflags
1742
1743 -- | Set a 'WarningFlag'
1744 wopt_set :: DynFlags -> WarningFlag -> DynFlags
1745 wopt_set dfs f = dfs{ warningFlags = IntSet.insert (fromEnum f) (warningFlags dfs) }
1746
1747 -- | Unset a 'WarningFlag'
1748 wopt_unset :: DynFlags -> WarningFlag -> DynFlags
1749 wopt_unset dfs f = dfs{ warningFlags = IntSet.delete (fromEnum f) (warningFlags dfs) }
1750
1751 -- | Test whether a 'ExtensionFlag' is set
1752 xopt :: ExtensionFlag -> DynFlags -> Bool
1753 xopt f dflags = fromEnum f `IntSet.member` extensionFlags dflags
1754
1755 -- | Set a 'ExtensionFlag'
1756 xopt_set :: DynFlags -> ExtensionFlag -> DynFlags
1757 xopt_set dfs f
1758 = let onoffs = On f : extensions dfs
1759 in dfs { extensions = onoffs,
1760 extensionFlags = flattenExtensionFlags (language dfs) onoffs }
1761
1762 -- | Unset a 'ExtensionFlag'
1763 xopt_unset :: DynFlags -> ExtensionFlag -> DynFlags
1764 xopt_unset dfs f
1765 = let onoffs = Off f : extensions dfs
1766 in dfs { extensions = onoffs,
1767 extensionFlags = flattenExtensionFlags (language dfs) onoffs }
1768
1769 lang_set :: DynFlags -> Maybe Language -> DynFlags
1770 lang_set dflags lang =
1771 dflags {
1772 language = lang,
1773 extensionFlags = flattenExtensionFlags lang (extensions dflags)
1774 }
1775
1776 -- | Check whether to use unicode syntax for output
1777 useUnicodeSyntax :: DynFlags -> Bool
1778 useUnicodeSyntax = gopt Opt_PrintUnicodeSyntax
1779
1780 -- | Set the Haskell language standard to use
1781 setLanguage :: Language -> DynP ()
1782 setLanguage l = upd (`lang_set` Just l)
1783
1784 -- | Some modules have dependencies on others through the DynFlags rather than textual imports
1785 dynFlagDependencies :: DynFlags -> [ModuleName]
1786 dynFlagDependencies = pluginModNames
1787
1788 -- | Is the -fpackage-trust mode on
1789 packageTrustOn :: DynFlags -> Bool
1790 packageTrustOn = gopt Opt_PackageTrust
1791
1792 -- | Is Safe Haskell on in some way (including inference mode)
1793 safeHaskellOn :: DynFlags -> Bool
1794 safeHaskellOn dflags = safeHaskell dflags /= Sf_None || safeInferOn dflags
1795
1796 -- | Is the Safe Haskell safe language in use
1797 safeLanguageOn :: DynFlags -> Bool
1798 safeLanguageOn dflags = safeHaskell dflags == Sf_Safe
1799
1800 -- | Is the Safe Haskell safe inference mode active
1801 safeInferOn :: DynFlags -> Bool
1802 safeInferOn = safeInfer
1803
1804 -- | Test if Safe Imports are on in some form
1805 safeImportsOn :: DynFlags -> Bool
1806 safeImportsOn dflags = safeHaskell dflags == Sf_Unsafe ||
1807 safeHaskell dflags == Sf_Trustworthy ||
1808 safeHaskell dflags == Sf_Safe
1809
1810 -- | Set a 'Safe Haskell' flag
1811 setSafeHaskell :: SafeHaskellMode -> DynP ()
1812 setSafeHaskell s = updM f
1813 where f dfs = do
1814 let sf = safeHaskell dfs
1815 safeM <- combineSafeFlags sf s
1816 case s of
1817 Sf_Safe -> return $ dfs { safeHaskell = safeM, safeInfer = False }
1818 -- leave safe inferrence on in Trustworthy mode so we can warn
1819 -- if it could have been inferred safe.
1820 Sf_Trustworthy -> do
1821 l <- getCurLoc
1822 return $ dfs { safeHaskell = safeM, trustworthyOnLoc = l }
1823 -- leave safe inference on in Unsafe mode as well.
1824 _ -> return $ dfs { safeHaskell = safeM }
1825
1826 -- | Are all direct imports required to be safe for this Safe Haskell mode?
1827 -- Direct imports are when the code explicitly imports a module
1828 safeDirectImpsReq :: DynFlags -> Bool
1829 safeDirectImpsReq d = safeLanguageOn d
1830
1831 -- | Are all implicit imports required to be safe for this Safe Haskell mode?
1832 -- Implicit imports are things in the prelude. e.g System.IO when print is used.
1833 safeImplicitImpsReq :: DynFlags -> Bool
1834 safeImplicitImpsReq d = safeLanguageOn d
1835
1836 -- | Combine two Safe Haskell modes correctly. Used for dealing with multiple flags.
1837 -- This makes Safe Haskell very much a monoid but for now I prefer this as I don't
1838 -- want to export this functionality from the module but do want to export the
1839 -- type constructors.
1840 combineSafeFlags :: SafeHaskellMode -> SafeHaskellMode -> DynP SafeHaskellMode
1841 combineSafeFlags a b | a == Sf_None = return b
1842 | b == Sf_None = return a
1843 | a == b = return a
1844 | otherwise = addErr errm >> return (panic errm)
1845 where errm = "Incompatible Safe Haskell flags! ("
1846 ++ show a ++ ", " ++ show b ++ ")"
1847
1848 -- | A list of unsafe flags under Safe Haskell. Tuple elements are:
1849 -- * name of the flag
1850 -- * function to get srcspan that enabled the flag
1851 -- * function to test if the flag is on
1852 -- * function to turn the flag off
1853 unsafeFlags, unsafeFlagsForInfer
1854 :: [(String, DynFlags -> SrcSpan, DynFlags -> Bool, DynFlags -> DynFlags)]
1855 unsafeFlags = [ ("-XGeneralizedNewtypeDeriving", newDerivOnLoc,
1856 xopt Opt_GeneralizedNewtypeDeriving,
1857 flip xopt_unset Opt_GeneralizedNewtypeDeriving)
1858 , ("-XTemplateHaskell", thOnLoc,
1859 xopt Opt_TemplateHaskell,
1860 flip xopt_unset Opt_TemplateHaskell)
1861 ]
1862 unsafeFlagsForInfer = unsafeFlags
1863
1864
1865 -- | Retrieve the options corresponding to a particular @opt_*@ field in the correct order
1866 getOpts :: DynFlags -- ^ 'DynFlags' to retrieve the options from
1867 -> (DynFlags -> [a]) -- ^ Relevant record accessor: one of the @opt_*@ accessors
1868 -> [a] -- ^ Correctly ordered extracted options
1869 getOpts dflags opts = reverse (opts dflags)
1870 -- We add to the options from the front, so we need to reverse the list
1871
1872 -- | Gets the verbosity flag for the current verbosity level. This is fed to
1873 -- other tools, so GHC-specific verbosity flags like @-ddump-most@ are not included
1874 getVerbFlags :: DynFlags -> [String]
1875 getVerbFlags dflags
1876 | verbosity dflags >= 4 = ["-v"]
1877 | otherwise = []
1878
1879 setObjectDir, setHiDir, setStubDir, setDumpDir, setOutputDir,
1880 setDynObjectSuf, setDynHiSuf,
1881 setDylibInstallName,
1882 setObjectSuf, setHiSuf, setHcSuf, parseDynLibLoaderMode,
1883 setPgmP, addOptl, addOptc, addOptP,
1884 addCmdlineFramework, addHaddockOpts, addGhciScript,
1885 setInteractivePrint
1886 :: String -> DynFlags -> DynFlags
1887 setOutputFile, setDynOutputFile, setOutputHi, setDumpPrefixForce
1888 :: Maybe String -> DynFlags -> DynFlags
1889
1890 setObjectDir f d = d{ objectDir = Just f}
1891 setHiDir f d = d{ hiDir = Just f}
1892 setStubDir f d = d{ stubDir = Just f, includePaths = f : includePaths d }
1893 -- -stubdir D adds an implicit -I D, so that gcc can find the _stub.h file
1894 -- \#included from the .hc file when compiling via C (i.e. unregisterised
1895 -- builds).
1896 setDumpDir f d = d{ dumpDir = Just f}
1897 setOutputDir f = setObjectDir f . setHiDir f . setStubDir f . setDumpDir f
1898 setDylibInstallName f d = d{ dylibInstallName = Just f}
1899
1900 setObjectSuf f d = d{ objectSuf = f}
1901 setDynObjectSuf f d = d{ dynObjectSuf = f}
1902 setHiSuf f d = d{ hiSuf = f}
1903 setDynHiSuf f d = d{ dynHiSuf = f}
1904 setHcSuf f d = d{ hcSuf = f}
1905
1906 setOutputFile f d = d{ outputFile = f}
1907 setDynOutputFile f d = d{ dynOutputFile = f}
1908 setOutputHi f d = d{ outputHi = f}
1909
1910 parseSigOf :: String -> SigOf
1911 parseSigOf str = case filter ((=="").snd) (readP_to_S parse str) of
1912 [(r, "")] -> r
1913 _ -> throwGhcException $ CmdLineError ("Can't parse -sig-of: " ++ str)
1914 where parse = Map.fromList <$> sepBy parseEntry (R.char ',')
1915 parseEntry = do
1916 n <- tok $ parseModuleName
1917 -- ToDo: deprecate this 'is' syntax?
1918 tok $ ((string "is" >> return ()) +++ (R.char '=' >> return ()))
1919 m <- tok $ parseModule
1920 return (n, m)
1921 parseModule = do
1922 pk <- munch1 (\c -> isAlphaNum c || c `elem` "-_")
1923 _ <- R.char ':'
1924 m <- parseModuleName
1925 return (mkModule (stringToPackageKey pk) m)
1926 tok m = skipSpaces >> m
1927
1928 setSigOf :: String -> DynFlags -> DynFlags
1929 setSigOf s d = d { sigOf = parseSigOf s }
1930
1931 addPluginModuleName :: String -> DynFlags -> DynFlags
1932 addPluginModuleName name d = d { pluginModNames = (mkModuleName name) : (pluginModNames d) }
1933
1934 addPluginModuleNameOption :: String -> DynFlags -> DynFlags
1935 addPluginModuleNameOption optflag d = d { pluginModNameOpts = (mkModuleName m, option) : (pluginModNameOpts d) }
1936 where (m, rest) = break (== ':') optflag
1937 option = case rest of
1938 [] -> "" -- should probably signal an error
1939 (_:plug_opt) -> plug_opt -- ignore the ':' from break
1940
1941 parseDynLibLoaderMode f d =
1942 case splitAt 8 f of
1943 ("deploy", "") -> d{ dynLibLoader = Deployable }
1944 ("sysdep", "") -> d{ dynLibLoader = SystemDependent }
1945 _ -> throwGhcException (CmdLineError ("Unknown dynlib loader: " ++ f))
1946
1947 setDumpPrefixForce f d = d { dumpPrefixForce = f}
1948
1949 -- XXX HACK: Prelude> words "'does not' work" ===> ["'does","not'","work"]
1950 -- Config.hs should really use Option.
1951 setPgmP f = let (pgm:args) = words f in alterSettings (\s -> s { sPgm_P = (pgm, map Option args)})
1952 addOptl f = alterSettings (\s -> s { sOpt_l = f : sOpt_l s})
1953 addOptc f = alterSettings (\s -> s { sOpt_c = f : sOpt_c s})
1954 addOptP f = alterSettings (\s -> s { sOpt_P = f : sOpt_P s})
1955
1956
1957 setDepMakefile :: FilePath -> DynFlags -> DynFlags
1958 setDepMakefile f d = d { depMakefile = f }
1959
1960 setDepIncludePkgDeps :: Bool -> DynFlags -> DynFlags
1961 setDepIncludePkgDeps b d = d { depIncludePkgDeps = b }
1962
1963 addDepExcludeMod :: String -> DynFlags -> DynFlags
1964 addDepExcludeMod m d
1965 = d { depExcludeMods = mkModuleName m : depExcludeMods d }
1966
1967 addDepSuffix :: FilePath -> DynFlags -> DynFlags
1968 addDepSuffix s d = d { depSuffixes = s : depSuffixes d }
1969
1970 addCmdlineFramework f d = d{ cmdlineFrameworks = f : cmdlineFrameworks d}
1971
1972 addHaddockOpts f d = d{ haddockOptions = Just f}
1973
1974 addGhciScript f d = d{ ghciScripts = f : ghciScripts d}
1975
1976 setInteractivePrint f d = d{ interactivePrint = Just f}
1977
1978 -- -----------------------------------------------------------------------------
1979 -- Command-line options
1980
1981 -- | When invoking external tools as part of the compilation pipeline, we
1982 -- pass these a sequence of options on the command-line. Rather than
1983 -- just using a list of Strings, we use a type that allows us to distinguish
1984 -- between filepaths and 'other stuff'. The reason for this is that
1985 -- this type gives us a handle on transforming filenames, and filenames only,
1986 -- to whatever format they're expected to be on a particular platform.
1987 data Option
1988 = FileOption -- an entry that _contains_ filename(s) / filepaths.
1989 String -- a non-filepath prefix that shouldn't be
1990 -- transformed (e.g., "/out=")
1991 String -- the filepath/filename portion
1992 | Option String
1993 deriving ( Eq )
1994
1995 showOpt :: Option -> String
1996 showOpt (FileOption pre f) = pre ++ f
1997 showOpt (Option s) = s
1998
1999 -----------------------------------------------------------------------------
2000 -- Setting the optimisation level
2001
2002 updOptLevel :: Int -> DynFlags -> DynFlags
2003 -- ^ Sets the 'DynFlags' to be appropriate to the optimisation level
2004 updOptLevel n dfs
2005 = dfs2{ optLevel = final_n }
2006 where
2007 final_n = max 0 (min 2 n) -- Clamp to 0 <= n <= 2
2008 dfs1 = foldr (flip gopt_unset) dfs remove_gopts
2009 dfs2 = foldr (flip gopt_set) dfs1 extra_gopts
2010
2011 extra_gopts = [ f | (ns,f) <- optLevelFlags, final_n `elem` ns ]
2012 remove_gopts = [ f | (ns,f) <- optLevelFlags, final_n `notElem` ns ]
2013
2014 -- -----------------------------------------------------------------------------
2015 -- StgToDo: abstraction of stg-to-stg passes to run.
2016
2017 data StgToDo
2018 = StgDoMassageForProfiling -- should be (next to) last
2019 -- There's also setStgVarInfo, but its absolute "lastness"
2020 -- is so critical that it is hardwired in (no flag).
2021 | D_stg_stats
2022
2023 getStgToDo :: DynFlags -> [StgToDo]
2024 getStgToDo dflags
2025 = todo2
2026 where
2027 stg_stats = gopt Opt_StgStats dflags
2028
2029 todo1 = if stg_stats then [D_stg_stats] else []
2030
2031 todo2 | WayProf `elem` ways dflags
2032 = StgDoMassageForProfiling : todo1
2033 | otherwise
2034 = todo1
2035
2036 {- **********************************************************************
2037 %* *
2038 DynFlags parser
2039 %* *
2040 %********************************************************************* -}
2041
2042 -- -----------------------------------------------------------------------------
2043 -- Parsing the dynamic flags.
2044
2045
2046 -- | Parse dynamic flags from a list of command line arguments. Returns the
2047 -- the parsed 'DynFlags', the left-over arguments, and a list of warnings.
2048 -- Throws a 'UsageError' if errors occurred during parsing (such as unknown
2049 -- flags or missing arguments).
2050 parseDynamicFlagsCmdLine :: MonadIO m => DynFlags -> [Located String]
2051 -> m (DynFlags, [Located String], [Located String])
2052 -- ^ Updated 'DynFlags', left-over arguments, and
2053 -- list of warnings.
2054 parseDynamicFlagsCmdLine = parseDynamicFlagsFull flagsAll True
2055
2056
2057 -- | Like 'parseDynamicFlagsCmdLine' but does not allow the package flags
2058 -- (-package, -hide-package, -ignore-package, -hide-all-packages, -package-db).
2059 -- Used to parse flags set in a modules pragma.
2060 parseDynamicFilePragma :: MonadIO m => DynFlags -> [Located String]
2061 -> m (DynFlags, [Located String], [Located String])
2062 -- ^ Updated 'DynFlags', left-over arguments, and
2063 -- list of warnings.
2064 parseDynamicFilePragma = parseDynamicFlagsFull flagsDynamic False
2065
2066
2067 -- | Parses the dynamically set flags for GHC. This is the most general form of
2068 -- the dynamic flag parser that the other methods simply wrap. It allows
2069 -- saying which flags are valid flags and indicating if we are parsing
2070 -- arguments from the command line or from a file pragma.
2071 parseDynamicFlagsFull :: MonadIO m
2072 => [Flag (CmdLineP DynFlags)] -- ^ valid flags to match against
2073 -> Bool -- ^ are the arguments from the command line?
2074 -> DynFlags -- ^ current dynamic flags
2075 -> [Located String] -- ^ arguments to parse
2076 -> m (DynFlags, [Located String], [Located String])
2077 parseDynamicFlagsFull activeFlags cmdline dflags0 args = do
2078 let ((leftover, errs, warns), dflags1)
2079 = runCmdLine (processArgs activeFlags args) dflags0
2080
2081 -- See Note [Handling errors when parsing commandline flags]
2082 unless (null errs) $ liftIO $ throwGhcExceptionIO $
2083 errorsToGhcException . map (showPpr dflags0 . getLoc &&& unLoc) $ errs
2084
2085 -- check for disabled flags in safe haskell
2086 let (dflags2, sh_warns) = safeFlagCheck cmdline dflags1
2087 dflags3 = updateWays dflags2
2088 theWays = ways dflags3
2089
2090 unless (allowed_combination theWays) $ liftIO $
2091 throwGhcExceptionIO (CmdLineError ("combination not supported: " ++
2092 intercalate "/" (map wayDesc theWays)))
2093
2094 let chooseOutput
2095 | isJust (outputFile dflags3) -- Only iff user specified -o ...
2096 , not (isJust (dynOutputFile dflags3)) -- but not -dyno
2097 = return $ dflags3 { dynOutputFile = Just $ dynOut (fromJust $ outputFile dflags3) }
2098 | otherwise
2099 = return dflags3
2100 where
2101 dynOut = flip addExtension (dynObjectSuf dflags3) . dropExtension
2102 dflags4 <- ifGeneratingDynamicToo dflags3 chooseOutput (return dflags3)
2103
2104 let (dflags5, consistency_warnings) = makeDynFlagsConsistent dflags4
2105
2106 dflags6 <- case dllSplitFile dflags5 of
2107 Nothing -> return (dflags5 { dllSplit = Nothing })
2108 Just f ->
2109 case dllSplit dflags5 of
2110 Just _ ->
2111 -- If dllSplit is out of date then it would have
2112 -- been set to Nothing. As it's a Just, it must be
2113 -- up-to-date.
2114 return dflags5
2115 Nothing ->
2116 do xs <- liftIO $ readFile f
2117 let ss = map (Set.fromList . words) (lines xs)
2118 return $ dflags5 { dllSplit = Just ss }
2119
2120 -- Set timer stats & heap size
2121 when (enableTimeStats dflags6) $ liftIO enableTimingStats
2122 case (ghcHeapSize dflags6) of
2123 Just x -> liftIO (setHeapSize x)
2124 _ -> return ()
2125
2126 liftIO $ setUnsafeGlobalDynFlags dflags6
2127
2128 return (dflags6, leftover, consistency_warnings ++ sh_warns ++ warns)
2129
2130 updateWays :: DynFlags -> DynFlags
2131 updateWays dflags
2132 = let theWays = sort $ nub $ ways dflags
2133 f = if WayDyn `elem` theWays then unSetGeneralFlag'
2134 else setGeneralFlag'
2135 in f Opt_Static
2136 $ dflags {
2137 ways = theWays,
2138 buildTag = mkBuildTag (filter (not . wayRTSOnly) theWays),
2139 rtsBuildTag = mkBuildTag theWays
2140 }
2141
2142 -- | Check (and potentially disable) any extensions that aren't allowed
2143 -- in safe mode.
2144 --
2145 -- The bool is to indicate if we are parsing command line flags (false means
2146 -- file pragma). This allows us to generate better warnings.
2147 safeFlagCheck :: Bool -> DynFlags -> (DynFlags, [Located String])
2148 safeFlagCheck _ dflags | safeLanguageOn dflags = (dflagsUnset, warns)
2149 where
2150 -- Handle illegal flags under safe language.
2151 (dflagsUnset, warns) = foldl check_method (dflags, []) unsafeFlags
2152
2153 check_method (df, warns) (str,loc,test,fix)
2154 | test df = (fix df, warns ++ safeFailure (loc df) str)
2155 | otherwise = (df, warns)
2156
2157 safeFailure loc str
2158 = [L loc $ str ++ " is not allowed in Safe Haskell; ignoring "
2159 ++ str]
2160
2161 safeFlagCheck cmdl dflags =
2162 case (safeInferOn dflags) of
2163 True | safeFlags -> (dflags', warn)
2164 True -> (dflags' { safeInferred = False }, warn)
2165 False -> (dflags', warn)
2166
2167 where
2168 -- dynflags and warn for when -fpackage-trust by itself with no safe
2169 -- haskell flag
2170 (dflags', warn)
2171 | safeHaskell dflags == Sf_None && not cmdl && packageTrustOn dflags
2172 = (gopt_unset dflags Opt_PackageTrust, pkgWarnMsg)
2173 | otherwise = (dflags, [])
2174
2175 pkgWarnMsg = [L (pkgTrustOnLoc dflags') $
2176 "-fpackage-trust ignored;" ++
2177 " must be specified with a Safe Haskell flag"]
2178
2179 -- Have we inferred Unsafe? See Note [HscMain . Safe Haskell Inference]
2180 safeFlags = all (\(_,_,t,_) -> not $ t dflags) unsafeFlagsForInfer
2181
2182
2183 {- **********************************************************************
2184 %* *
2185 DynFlags specifications
2186 %* *
2187 %********************************************************************* -}
2188
2189 -- | All dynamic flags option strings. These are the user facing strings for
2190 -- enabling and disabling options.
2191 allFlags :: [String]
2192 allFlags = [ '-':flagName flag
2193 | flag <- flagsAll
2194 , ok (flagOptKind flag) ]
2195 where ok (PrefixPred _ _) = False
2196 ok _ = True
2197
2198 {-
2199 - Below we export user facing symbols for GHC dynamic flags for use with the
2200 - GHC API.
2201 -}
2202
2203 -- All dynamic flags present in GHC.
2204 flagsAll :: [Flag (CmdLineP DynFlags)]
2205 flagsAll = package_flags ++ dynamic_flags
2206
2207 -- All dynamic flags, minus package flags, present in GHC.
2208 flagsDynamic :: [Flag (CmdLineP DynFlags)]
2209 flagsDynamic = dynamic_flags
2210
2211 -- ALl package flags present in GHC.
2212 flagsPackage :: [Flag (CmdLineP DynFlags)]
2213 flagsPackage = package_flags
2214
2215 --------------- The main flags themselves ------------------
2216 -- See Note [Updating flag description in the User's Guide]
2217 -- See Note [Supporting CLI completion]
2218 dynamic_flags :: [Flag (CmdLineP DynFlags)]
2219 dynamic_flags = [
2220 defFlag "n"
2221 (NoArg (addWarn "The -n flag is deprecated and no longer has any effect"))
2222 , defFlag "cpp" (NoArg (setExtensionFlag Opt_Cpp))
2223 , defFlag "F" (NoArg (setGeneralFlag Opt_Pp))
2224 , defFlag "#include"
2225 (HasArg (\s -> do
2226 addCmdlineHCInclude s
2227 addWarn ("-#include and INCLUDE pragmas are " ++
2228 "deprecated: They no longer have any effect")))
2229 , defFlag "v" (OptIntSuffix setVerbosity)
2230
2231 , defGhcFlag "j" (OptIntSuffix (\n -> upd (\d -> d {parMakeCount = n})))
2232 , defFlag "sig-of" (sepArg setSigOf)
2233
2234 -- RTS options -------------------------------------------------------------
2235 , defFlag "H" (HasArg (\s -> upd (\d ->
2236 d { ghcHeapSize = Just $ fromIntegral (decodeSize s)})))
2237
2238 , defFlag "Rghc-timing" (NoArg (upd (\d -> d { enableTimeStats = True })))
2239
2240 ------- ways ---------------------------------------------------------------
2241 , defGhcFlag "prof" (NoArg (addWay WayProf))
2242 , defGhcFlag "eventlog" (NoArg (addWay WayEventLog))
2243 , defGhcFlag "parallel" (NoArg (addWay WayPar))
2244 , defGhcFlag "smp"
2245 (NoArg (addWay WayThreaded >> deprecate "Use -threaded instead"))
2246 , defGhcFlag "debug" (NoArg (addWay WayDebug))
2247 , defGhcFlag "threaded" (NoArg (addWay WayThreaded))
2248
2249 , defGhcFlag "ticky"
2250 (NoArg (setGeneralFlag Opt_Ticky >> addWay WayDebug))
2251
2252 -- -ticky enables ticky-ticky code generation, and also implies -debug which
2253 -- is required to get the RTS ticky support.
2254
2255 ----- Linker --------------------------------------------------------
2256 , defGhcFlag "static" (NoArg removeWayDyn)
2257 , defGhcFlag "dynamic" (NoArg (addWay WayDyn))
2258 , defGhcFlag "rdynamic" $ noArg $
2259 #ifdef linux_HOST_OS
2260 addOptl "-rdynamic"
2261 #elif defined (mingw32_HOST_OS)
2262 addOptl "-export-all-symbols"
2263 #else
2264 -- ignored for compat w/ gcc:
2265 id
2266 #endif
2267 , defGhcFlag "relative-dynlib-paths"
2268 (NoArg (setGeneralFlag Opt_RelativeDynlibPaths))
2269
2270 ------- Specific phases --------------------------------------------
2271 -- need to appear before -pgmL to be parsed as LLVM flags.
2272 , defFlag "pgmlo"
2273 (hasArg (\f -> alterSettings (\s -> s { sPgm_lo = (f,[])})))
2274 , defFlag "pgmlc"
2275 (hasArg (\f -> alterSettings (\s -> s { sPgm_lc = (f,[])})))
2276 , defFlag "pgmL"
2277 (hasArg (\f -> alterSettings (\s -> s { sPgm_L = f})))
2278 , defFlag "pgmP"
2279 (hasArg setPgmP)
2280 , defFlag "pgmF"
2281 (hasArg (\f -> alterSettings (\s -> s { sPgm_F = f})))
2282 , defFlag "pgmc"
2283 (hasArg (\f -> alterSettings (\s -> s { sPgm_c = (f,[])})))
2284 , defFlag "pgms"
2285 (hasArg (\f -> alterSettings (\s -> s { sPgm_s = (f,[])})))
2286 , defFlag "pgma"
2287 (hasArg (\f -> alterSettings (\s -> s { sPgm_a = (f,[])})))
2288 , defFlag "pgml"
2289 (hasArg (\f -> alterSettings (\s -> s { sPgm_l = (f,[])})))
2290 , defFlag "pgmdll"
2291 (hasArg (\f -> alterSettings (\s -> s { sPgm_dll = (f,[])})))
2292 , defFlag "pgmwindres"
2293 (hasArg (\f -> alterSettings (\s -> s { sPgm_windres = f})))
2294 , defFlag "pgmlibtool"
2295 (hasArg (\f -> alterSettings (\s -> s { sPgm_libtool = f})))
2296
2297 -- need to appear before -optl/-opta to be parsed as LLVM flags.
2298 , defFlag "optlo"
2299 (hasArg (\f -> alterSettings (\s -> s { sOpt_lo = f : sOpt_lo s})))
2300 , defFlag "optlc"
2301 (hasArg (\f -> alterSettings (\s -> s { sOpt_lc = f : sOpt_lc s})))
2302 , defFlag "optL"
2303 (hasArg (\f -> alterSettings (\s -> s { sOpt_L = f : sOpt_L s})))
2304 , defFlag "optP"
2305 (hasArg addOptP)
2306 , defFlag "optF"
2307 (hasArg (\f -> alterSettings (\s -> s { sOpt_F = f : sOpt_F s})))
2308 , defFlag "optc"
2309 (hasArg addOptc)
2310 , defFlag "opta"
2311 (hasArg (\f -> alterSettings (\s -> s { sOpt_a = f : sOpt_a s})))
2312 , defFlag "optl"
2313 (hasArg addOptl)
2314 , defFlag "optwindres"
2315 (hasArg (\f ->
2316 alterSettings (\s -> s { sOpt_windres = f : sOpt_windres s})))
2317
2318 , defGhcFlag "split-objs"
2319 (NoArg (if can_split
2320 then setGeneralFlag Opt_SplitObjs
2321 else addWarn "ignoring -fsplit-objs"))
2322
2323 -------- ghc -M -----------------------------------------------------
2324 , defGhcFlag "dep-suffix" (hasArg addDepSuffix)
2325 , defGhcFlag "dep-makefile" (hasArg setDepMakefile)
2326 , defGhcFlag "include-pkg-deps" (noArg (setDepIncludePkgDeps True))
2327 , defGhcFlag "exclude-module" (hasArg addDepExcludeMod)
2328
2329 -------- Linking ----------------------------------------------------
2330 , defGhcFlag "no-link" (noArg (\d -> d{ ghcLink=NoLink }))
2331 , defGhcFlag "shared" (noArg (\d -> d{ ghcLink=LinkDynLib }))
2332 , defGhcFlag "staticlib" (noArg (\d -> d{ ghcLink=LinkStaticLib }))
2333 , defGhcFlag "dynload" (hasArg parseDynLibLoaderMode)
2334 , defGhcFlag "dylib-install-name" (hasArg setDylibInstallName)
2335 -- -dll-split is an internal flag, used only during the GHC build
2336 , defHiddenFlag "dll-split"
2337 (hasArg (\f d -> d{ dllSplitFile = Just f, dllSplit = Nothing }))
2338
2339 ------- Libraries ---------------------------------------------------
2340 , defFlag "L" (Prefix addLibraryPath)
2341 , defFlag "l" (hasArg (addLdInputs . Option . ("-l" ++)))
2342
2343 ------- Frameworks --------------------------------------------------
2344 -- -framework-path should really be -F ...
2345 , defFlag "framework-path" (HasArg addFrameworkPath)
2346 , defFlag "framework" (hasArg addCmdlineFramework)
2347
2348 ------- Output Redirection ------------------------------------------
2349 , defGhcFlag "odir" (hasArg setObjectDir)
2350 , defGhcFlag "o" (sepArg (setOutputFile . Just))
2351 , defGhcFlag "dyno" (sepArg (setDynOutputFile . Just))
2352 , defGhcFlag "ohi" (hasArg (setOutputHi . Just ))
2353 , defGhcFlag "osuf" (hasArg setObjectSuf)
2354 , defGhcFlag "dynosuf" (hasArg setDynObjectSuf)
2355 , defGhcFlag "hcsuf" (hasArg setHcSuf)
2356 , defGhcFlag "hisuf" (hasArg setHiSuf)
2357 , defGhcFlag "dynhisuf" (hasArg setDynHiSuf)
2358 , defGhcFlag "hidir" (hasArg setHiDir)
2359 , defGhcFlag "tmpdir" (hasArg setTmpDir)
2360 , defGhcFlag "stubdir" (hasArg setStubDir)
2361 , defGhcFlag "dumpdir" (hasArg setDumpDir)
2362 , defGhcFlag "outputdir" (hasArg setOutputDir)
2363 , defGhcFlag "ddump-file-prefix" (hasArg (setDumpPrefixForce . Just))
2364
2365 , defGhcFlag "dynamic-too" (NoArg (setGeneralFlag Opt_BuildDynamicToo))
2366
2367 ------- Keeping temporary files -------------------------------------
2368 -- These can be singular (think ghc -c) or plural (think ghc --make)
2369 , defGhcFlag "keep-hc-file" (NoArg (setGeneralFlag Opt_KeepHcFiles))
2370 , defGhcFlag "keep-hc-files" (NoArg (setGeneralFlag Opt_KeepHcFiles))
2371 , defGhcFlag "keep-s-file" (NoArg (setGeneralFlag Opt_KeepSFiles))
2372 , defGhcFlag "keep-s-files" (NoArg (setGeneralFlag Opt_KeepSFiles))
2373 , defGhcFlag "keep-llvm-file" (NoArg (do setObjTarget HscLlvm
2374 setGeneralFlag Opt_KeepLlvmFiles))
2375 , defGhcFlag "keep-llvm-files" (NoArg (do setObjTarget HscLlvm
2376 setGeneralFlag Opt_KeepLlvmFiles))
2377 -- This only makes sense as plural
2378 , defGhcFlag "keep-tmp-files" (NoArg (setGeneralFlag Opt_KeepTmpFiles))
2379
2380 ------- Miscellaneous ----------------------------------------------
2381 , defGhcFlag "no-auto-link-packages"
2382 (NoArg (unSetGeneralFlag Opt_AutoLinkPackages))
2383 , defGhcFlag "no-hs-main" (NoArg (setGeneralFlag Opt_NoHsMain))
2384 , defGhcFlag "with-rtsopts" (HasArg setRtsOpts)
2385 , defGhcFlag "rtsopts" (NoArg (setRtsOptsEnabled RtsOptsAll))
2386 , defGhcFlag "rtsopts=all" (NoArg (setRtsOptsEnabled RtsOptsAll))
2387 , defGhcFlag "rtsopts=some" (NoArg (setRtsOptsEnabled RtsOptsSafeOnly))
2388 , defGhcFlag "rtsopts=none" (NoArg (setRtsOptsEnabled RtsOptsNone))
2389 , defGhcFlag "no-rtsopts" (NoArg (setRtsOptsEnabled RtsOptsNone))
2390 , defGhcFlag "no-rtsopts-suggestions"
2391 (noArg (\d -> d {rtsOptsSuggestions = False} ))
2392 , defGhcFlag "main-is" (SepArg setMainIs)
2393 , defGhcFlag "haddock" (NoArg (setGeneralFlag Opt_Haddock))
2394 , defGhcFlag "haddock-opts" (hasArg addHaddockOpts)
2395 , defGhcFlag "hpcdir" (SepArg setOptHpcDir)
2396 , defGhciFlag "ghci-script" (hasArg addGhciScript)
2397 , defGhciFlag "interactive-print" (hasArg setInteractivePrint)
2398 , defGhcFlag "ticky-allocd" (NoArg (setGeneralFlag Opt_Ticky_Allocd))
2399 , defGhcFlag "ticky-LNE" (NoArg (setGeneralFlag Opt_Ticky_LNE))
2400 , defGhcFlag "ticky-dyn-thunk" (NoArg (setGeneralFlag Opt_Ticky_Dyn_Thunk))
2401 ------- recompilation checker --------------------------------------
2402 , defGhcFlag "recomp" (NoArg (do unSetGeneralFlag Opt_ForceRecomp
2403 deprecate "Use -fno-force-recomp instead"))
2404 , defGhcFlag "no-recomp" (NoArg (do setGeneralFlag Opt_ForceRecomp
2405 deprecate "Use -fforce-recomp instead"))
2406
2407 ------ HsCpp opts ---------------------------------------------------
2408 , defFlag "D" (AnySuffix (upd . addOptP))
2409 , defFlag "U" (AnySuffix (upd . addOptP))
2410
2411 ------- Include/Import Paths ----------------------------------------
2412 , defFlag "I" (Prefix addIncludePath)
2413 , defFlag "i" (OptPrefix addImportPath)
2414
2415 ------ Output style options -----------------------------------------
2416 , defFlag "dppr-user-length" (intSuffix (\n d -> d{ pprUserLength = n }))
2417 , defFlag "dppr-cols" (intSuffix (\n d -> d{ pprCols = n }))
2418 , defGhcFlag "dtrace-level" (intSuffix (\n d -> d{ traceLevel = n }))
2419 -- Suppress all that is suppressable in core dumps.
2420 -- Except for uniques, as some simplifier phases introduce new varibles that
2421 -- have otherwise identical names.
2422 , defGhcFlag "dsuppress-all"
2423 (NoArg $ do setGeneralFlag Opt_SuppressCoercions
2424 setGeneralFlag Opt_SuppressVarKinds
2425 setGeneralFlag Opt_SuppressModulePrefixes
2426 setGeneralFlag Opt_SuppressTypeApplications
2427 setGeneralFlag Opt_SuppressIdInfo
2428 setGeneralFlag Opt_SuppressTypeSignatures)
2429
2430 ------ Debugging ----------------------------------------------------
2431 , defGhcFlag "dstg-stats" (NoArg (setGeneralFlag Opt_StgStats))
2432
2433 , defGhcFlag "ddump-cmm" (setDumpFlag Opt_D_dump_cmm)
2434 , defGhcFlag "ddump-cmm-raw" (setDumpFlag Opt_D_dump_cmm_raw)
2435 , defGhcFlag "ddump-cmm-cfg" (setDumpFlag Opt_D_dump_cmm_cfg)
2436 , defGhcFlag "ddump-cmm-cbe" (setDumpFlag Opt_D_dump_cmm_cbe)
2437 , defGhcFlag "ddump-cmm-switch" (setDumpFlag Opt_D_dump_cmm_switch)
2438 , defGhcFlag "ddump-cmm-proc" (setDumpFlag Opt_D_dump_cmm_proc)
2439 , defGhcFlag "ddump-cmm-sink" (setDumpFlag Opt_D_dump_cmm_sink)
2440 , defGhcFlag "ddump-cmm-sp" (setDumpFlag Opt_D_dump_cmm_sp)
2441 , defGhcFlag "ddump-cmm-procmap" (setDumpFlag Opt_D_dump_cmm_procmap)
2442 , defGhcFlag "ddump-cmm-split" (setDumpFlag Opt_D_dump_cmm_split)
2443 , defGhcFlag "ddump-cmm-info" (setDumpFlag Opt_D_dump_cmm_info)
2444 , defGhcFlag "ddump-cmm-cps" (setDumpFlag Opt_D_dump_cmm_cps)
2445 , defGhcFlag "ddump-core-stats" (setDumpFlag Opt_D_dump_core_stats)
2446 , defGhcFlag "ddump-asm" (setDumpFlag Opt_D_dump_asm)
2447 , defGhcFlag "ddump-asm-native" (setDumpFlag Opt_D_dump_asm_native)
2448 , defGhcFlag "ddump-asm-liveness" (setDumpFlag Opt_D_dump_asm_liveness)
2449 , defGhcFlag "ddump-asm-regalloc" (setDumpFlag Opt_D_dump_asm_regalloc)
2450 , defGhcFlag "ddump-asm-conflicts" (setDumpFlag Opt_D_dump_asm_conflicts)
2451 , defGhcFlag "ddump-asm-regalloc-stages"
2452 (setDumpFlag Opt_D_dump_asm_regalloc_stages)
2453 , defGhcFlag "ddump-asm-stats" (setDumpFlag Opt_D_dump_asm_stats)
2454 , defGhcFlag "ddump-asm-expanded" (setDumpFlag Opt_D_dump_asm_expanded)
2455 , defGhcFlag "ddump-llvm" (NoArg (do setObjTarget HscLlvm
2456 setDumpFlag' Opt_D_dump_llvm))
2457 , defGhcFlag "ddump-deriv" (setDumpFlag Opt_D_dump_deriv)
2458 , defGhcFlag "ddump-ds" (setDumpFlag Opt_D_dump_ds)
2459 , defGhcFlag "ddump-foreign" (setDumpFlag Opt_D_dump_foreign)
2460 , defGhcFlag "ddump-inlinings" (setDumpFlag Opt_D_dump_inlinings)
2461 , defGhcFlag "ddump-rule-firings" (setDumpFlag Opt_D_dump_rule_firings)
2462 , defGhcFlag "ddump-rule-rewrites" (setDumpFlag Opt_D_dump_rule_rewrites)
2463 , defGhcFlag "ddump-simpl-trace" (setDumpFlag Opt_D_dump_simpl_trace)
2464 , defGhcFlag "ddump-occur-anal" (setDumpFlag Opt_D_dump_occur_anal)
2465 , defGhcFlag "ddump-parsed" (setDumpFlag Opt_D_dump_parsed)
2466 , defGhcFlag "ddump-rn" (setDumpFlag Opt_D_dump_rn)
2467 , defGhcFlag "ddump-simpl" (setDumpFlag Opt_D_dump_simpl)
2468 , defGhcFlag "ddump-simpl-iterations"
2469 (setDumpFlag Opt_D_dump_simpl_iterations)
2470 , defGhcFlag "ddump-spec" (setDumpFlag Opt_D_dump_spec)
2471 , defGhcFlag "ddump-prep" (setDumpFlag Opt_D_dump_prep)
2472 , defGhcFlag "ddump-stg" (setDumpFlag Opt_D_dump_stg)
2473 , defGhcFlag "ddump-call-arity" (setDumpFlag Opt_D_dump_call_arity)
2474 , defGhcFlag "ddump-stranal" (setDumpFlag Opt_D_dump_stranal)
2475 , defGhcFlag "ddump-strsigs" (setDumpFlag Opt_D_dump_strsigs)
2476 , defGhcFlag "ddump-tc" (setDumpFlag Opt_D_dump_tc)
2477 , defGhcFlag "ddump-types" (setDumpFlag Opt_D_dump_types)
2478 , defGhcFlag "ddump-rules" (setDumpFlag Opt_D_dump_rules)
2479 , defGhcFlag "ddump-cse" (setDumpFlag Opt_D_dump_cse)
2480 , defGhcFlag "ddump-worker-wrapper" (setDumpFlag Opt_D_dump_worker_wrapper)
2481 , defGhcFlag "ddump-rn-trace" (setDumpFlag Opt_D_dump_rn_trace)
2482 , defGhcFlag "ddump-if-trace" (setDumpFlag Opt_D_dump_if_trace)
2483 , defGhcFlag "ddump-cs-trace" (setDumpFlag Opt_D_dump_cs_trace)
2484 , defGhcFlag "ddump-tc-trace" (NoArg (do
2485 setDumpFlag' Opt_D_dump_tc_trace
2486 setDumpFlag' Opt_D_dump_cs_trace))
2487 , defGhcFlag "ddump-vt-trace" (setDumpFlag Opt_D_dump_vt_trace)
2488 , defGhcFlag "ddump-splices" (setDumpFlag Opt_D_dump_splices)
2489 , defGhcFlag "dth-dec-file" (setDumpFlag Opt_D_th_dec_file)
2490
2491 , defGhcFlag "ddump-rn-stats" (setDumpFlag Opt_D_dump_rn_stats)
2492 , defGhcFlag "ddump-opt-cmm" (setDumpFlag Opt_D_dump_opt_cmm)
2493 , defGhcFlag "ddump-simpl-stats" (setDumpFlag Opt_D_dump_simpl_stats)
2494 , defGhcFlag "ddump-bcos" (setDumpFlag Opt_D_dump_BCOs)
2495 , defGhcFlag "dsource-stats" (setDumpFlag Opt_D_source_stats)
2496 , defGhcFlag "dverbose-core2core" (NoArg (do setVerbosity (Just 2)
2497 setVerboseCore2Core))
2498 , defGhcFlag "dverbose-stg2stg" (setDumpFlag Opt_D_verbose_stg2stg)
2499 , defGhcFlag "ddump-hi" (setDumpFlag Opt_D_dump_hi)
2500 , defGhcFlag "ddump-minimal-imports"
2501 (NoArg (setGeneralFlag Opt_D_dump_minimal_imports))
2502 , defGhcFlag "ddump-vect" (setDumpFlag Opt_D_dump_vect)
2503 , defGhcFlag "ddump-hpc"
2504 (setDumpFlag Opt_D_dump_ticked) -- back compat
2505 , defGhcFlag "ddump-ticked" (setDumpFlag Opt_D_dump_ticked)
2506 , defGhcFlag "ddump-mod-cycles" (setDumpFlag Opt_D_dump_mod_cycles)
2507 , defGhcFlag "ddump-mod-map" (setDumpFlag Opt_D_dump_mod_map)
2508 , defGhcFlag "ddump-view-pattern-commoning"
2509 (setDumpFlag Opt_D_dump_view_pattern_commoning)
2510 , defGhcFlag "ddump-to-file" (NoArg (setGeneralFlag Opt_DumpToFile))
2511 , defGhcFlag "ddump-hi-diffs" (setDumpFlag Opt_D_dump_hi_diffs)
2512 , defGhcFlag "ddump-rtti" (setDumpFlag Opt_D_dump_rtti)
2513 , defGhcFlag "dcore-lint"
2514 (NoArg (setGeneralFlag Opt_DoCoreLinting))
2515 , defGhcFlag "dstg-lint"
2516 (NoArg (setGeneralFlag Opt_DoStgLinting))
2517 , defGhcFlag "dcmm-lint"
2518 (NoArg (setGeneralFlag Opt_DoCmmLinting))
2519 , defGhcFlag "dasm-lint"
2520 (NoArg (setGeneralFlag Opt_DoAsmLinting))
2521 , defGhcFlag "dannot-lint"
2522 (NoArg (setGeneralFlag Opt_DoAnnotationLinting))
2523 , defGhcFlag "dshow-passes" (NoArg (do forceRecompile
2524 setVerbosity $ Just 2))
2525 , defGhcFlag "dfaststring-stats"
2526 (NoArg (setGeneralFlag Opt_D_faststring_stats))
2527 , defGhcFlag "dno-llvm-mangler"
2528 (NoArg (setGeneralFlag Opt_NoLlvmMangler)) -- hidden flag
2529 , defGhcFlag "ddump-debug" (setDumpFlag Opt_D_dump_debug)
2530
2531 ------ Machine dependant (-m<blah>) stuff ---------------------------
2532
2533 , defGhcFlag "msse" (noArg (\d -> d{ sseVersion = Just SSE1 }))
2534 , defGhcFlag "msse2" (noArg (\d -> d{ sseVersion = Just SSE2 }))
2535 , defGhcFlag "msse3" (noArg (\d -> d{ sseVersion = Just SSE3 }))
2536 , defGhcFlag "msse4" (noArg (\d -> d{ sseVersion = Just SSE4 }))
2537 , defGhcFlag "msse4.2" (noArg (\d -> d{ sseVersion = Just SSE42 }))
2538 , defGhcFlag "mavx" (noArg (\d -> d{ avx = True }))
2539 , defGhcFlag "mavx2" (noArg (\d -> d{ avx2 = True }))
2540 , defGhcFlag "mavx512cd" (noArg (\d -> d{ avx512cd = True }))
2541 , defGhcFlag "mavx512er" (noArg (\d -> d{ avx512er = True }))
2542 , defGhcFlag "mavx512f" (noArg (\d -> d{ avx512f = True }))
2543 , defGhcFlag "mavx512pf" (noArg (\d -> d{ avx512pf = True }))
2544
2545 ------ Warning opts -------------------------------------------------
2546 , defFlag "W" (NoArg (mapM_ setWarningFlag minusWOpts))
2547 , defFlag "Werror" (NoArg (setGeneralFlag Opt_WarnIsError))
2548 , defFlag "Wwarn" (NoArg (unSetGeneralFlag Opt_WarnIsError))
2549 , defFlag "Wall" (NoArg (mapM_ setWarningFlag minusWallOpts))
2550 , defFlag "Wnot" (NoArg (do upd (\dfs -> dfs {warningFlags = IntSet.empty})
2551 deprecate "Use -w instead"))
2552 , defFlag "w" (NoArg (upd (\dfs -> dfs {warningFlags = IntSet.empty})))
2553
2554 ------ Plugin flags ------------------------------------------------
2555 , defGhcFlag "fplugin-opt" (hasArg addPluginModuleNameOption)
2556 , defGhcFlag "fplugin" (hasArg addPluginModuleName)
2557
2558 ------ Optimisation flags ------------------------------------------
2559 , defGhcFlag "O" (noArgM (setOptLevel 1))
2560 , defGhcFlag "Onot" (noArgM (\dflags -> do deprecate "Use -O0 instead"
2561 setOptLevel 0 dflags))
2562 , defGhcFlag "Odph" (noArgM setDPHOpt)
2563 , defGhcFlag "O" (optIntSuffixM (\mb_n -> setOptLevel (mb_n `orElse` 1)))
2564 -- If the number is missing, use 1
2565
2566
2567 , defFlag "fmax-relevant-binds"
2568 (intSuffix (\n d -> d{ maxRelevantBinds = Just n }))
2569 , defFlag "fno-max-relevant-binds"
2570 (noArg (\d -> d{ maxRelevantBinds = Nothing }))
2571 , defFlag "fsimplifier-phases"
2572 (intSuffix (\n d -> d{ simplPhases = n }))
2573 , defFlag "fmax-simplifier-iterations"
2574 (intSuffix (\n d -> d{ maxSimplIterations = n }))
2575 , defFlag "fsimpl-tick-factor"
2576 (intSuffix (\n d -> d{ simplTickFactor = n }))
2577 , defFlag "fspec-constr-threshold"
2578 (intSuffix (\n d -> d{ specConstrThreshold = Just n }))
2579 , defFlag "fno-spec-constr-threshold"
2580 (noArg (\d -> d{ specConstrThreshold = Nothing }))
2581 , defFlag "fspec-constr-count"
2582 (intSuffix (\n d -> d{ specConstrCount = Just n }))
2583 , defFlag "fno-spec-constr-count"
2584 (noArg (\d -> d{ specConstrCount = Nothing }))
2585 , defFlag "fspec-constr-recursive"
2586 (intSuffix (\n d -> d{ specConstrRecursive = n }))
2587 , defFlag "fliberate-case-threshold"
2588 (intSuffix (\n d -> d{ liberateCaseThreshold = Just n }))
2589 , defFlag "fno-liberate-case-threshold"
2590 (noArg (\d -> d{ liberateCaseThreshold = Nothing }))
2591 , defFlag "frule-check"
2592 (sepArg (\s d -> d{ ruleCheck = Just s }))
2593 , defFlag "freduction-depth"
2594 (intSuffix (\n d -> d{ reductionDepth = treatZeroAsInf n }))
2595 , defFlag "fcontext-stack"
2596 (intSuffixM (\n d ->
2597 do { deprecate $ "use -freduction-depth=" ++ show n ++ " instead"
2598 ; return $ d{ reductionDepth = treatZeroAsInf n } }))
2599 , defFlag "ftype-function-depth"
2600 (intSuffixM (\n d ->
2601 do { deprecate $ "use -freduction-depth=" ++ show n ++ " instead"
2602 ; return $ d{ reductionDepth = treatZeroAsInf n } }))
2603 , defFlag "fstrictness-before"
2604 (intSuffix (\n d -> d{ strictnessBefore = n : strictnessBefore d }))
2605 , defFlag "ffloat-lam-args"
2606 (intSuffix (\n d -> d{ floatLamArgs = Just n }))
2607 , defFlag "ffloat-all-lams"
2608 (noArg (\d -> d{ floatLamArgs = Nothing }))
2609
2610 , defFlag "fhistory-size" (intSuffix (\n d -> d{ historySize = n }))
2611
2612 , defFlag "funfolding-creation-threshold"
2613 (intSuffix (\n d -> d {ufCreationThreshold = n}))
2614 , defFlag "funfolding-use-threshold"
2615 (intSuffix (\n d -> d {ufUseThreshold = n}))
2616 , defFlag "funfolding-fun-discount"
2617 (intSuffix (\n d -> d {ufFunAppDiscount = n}))
2618 , defFlag "funfolding-dict-discount"
2619 (intSuffix (\n d -> d {ufDictDiscount = n}))
2620 , defFlag "funfolding-keeness-factor"
2621 (floatSuffix (\n d -> d {ufKeenessFactor = n}))
2622
2623 , defFlag "fmax-worker-args" (intSuffix (\n d -> d {maxWorkerArgs = n}))
2624
2625 , defGhciFlag "fghci-hist-size" (intSuffix (\n d -> d {ghciHistSize = n}))
2626 , defGhcFlag "fmax-inline-alloc-size"
2627 (intSuffix (\n d -> d{ maxInlineAllocSize = n }))
2628 , defGhcFlag "fmax-inline-memcpy-insns"
2629 (intSuffix (\n d -> d{ maxInlineMemcpyInsns = n }))
2630 , defGhcFlag "fmax-inline-memset-insns"
2631 (intSuffix (\n d -> d{ maxInlineMemsetInsns = n }))
2632
2633 ------ Profiling ----------------------------------------------------
2634
2635 -- OLD profiling flags
2636 , defGhcFlag "auto-all" (noArg (\d -> d { profAuto = ProfAutoAll } ))
2637 , defGhcFlag "no-auto-all" (noArg (\d -> d { profAuto = NoProfAuto } ))
2638 , defGhcFlag "auto" (noArg (\d -> d { profAuto = ProfAutoExports } ))
2639 , defGhcFlag "no-auto" (noArg (\d -> d { profAuto = NoProfAuto } ))
2640 , defGhcFlag "caf-all"
2641 (NoArg (setGeneralFlag Opt_AutoSccsOnIndividualCafs))
2642 , defGhcFlag "no-caf-all"
2643 (NoArg (unSetGeneralFlag Opt_AutoSccsOnIndividualCafs))
2644
2645 -- NEW profiling flags
2646 , defGhcFlag "fprof-auto"
2647 (noArg (\d -> d { profAuto = ProfAutoAll } ))
2648 , defGhcFlag "fprof-auto-top"
2649 (noArg (\d -> d { profAuto = ProfAutoTop } ))
2650 , defGhcFlag "fprof-auto-exported"
2651 (noArg (\d -> d { profAuto = ProfAutoExports } ))
2652 , defGhcFlag "fprof-auto-calls"
2653 (noArg (\d -> d { profAuto = ProfAutoCalls } ))
2654 , defGhcFlag "fno-prof-auto"
2655 (noArg (\d -> d { profAuto = NoProfAuto } ))
2656
2657 ------ Compiler flags -----------------------------------------------
2658
2659 , defGhcFlag "fasm" (NoArg (setObjTarget HscAsm))
2660 , defGhcFlag "fvia-c" (NoArg
2661 (addWarn $ "The -fvia-c flag does nothing; " ++
2662 "it will be removed in a future GHC release"))
2663 , defGhcFlag "fvia-C" (NoArg
2664 (addWarn $ "The -fvia-C flag does nothing; " ++
2665 "it will be removed in a future GHC release"))
2666 , defGhcFlag "fllvm" (NoArg (setObjTarget HscLlvm))
2667
2668 , defFlag "fno-code" (NoArg (do upd $ \d -> d{ ghcLink=NoLink }
2669 setTarget HscNothing))
2670 , defFlag "fbyte-code" (NoArg (setTarget HscInterpreted))
2671 , defFlag "fobject-code" (NoArg (setTargetWithPlatform defaultHscTarget))
2672 , defFlag "fglasgow-exts"
2673 (NoArg (do enableGlasgowExts
2674 deprecate "Use individual extensions instead"))
2675 , defFlag "fno-glasgow-exts"
2676 (NoArg (do disableGlasgowExts
2677 deprecate "Use individual extensions instead"))
2678 , defFlag "fwarn-unused-binds" (NoArg enableUnusedBinds)
2679 , defFlag "fno-warn-unused-binds" (NoArg disableUnusedBinds)
2680
2681 ------ Safe Haskell flags -------------------------------------------
2682 , defFlag "fpackage-trust" (NoArg setPackageTrust)
2683 , defFlag "fno-safe-infer" (noArg (\d -> d { safeInfer = False } ))
2684 , defGhcFlag "fPIC" (NoArg (setGeneralFlag Opt_PIC))
2685 , defGhcFlag "fno-PIC" (NoArg (unSetGeneralFlag Opt_PIC))
2686
2687 ------ Debugging flags ----------------------------------------------
2688 , defGhcFlag "g" (NoArg (setGeneralFlag Opt_Debug))
2689 ]
2690 ++ map (mkFlag turnOn "" setGeneralFlag ) negatableFlags
2691 ++ map (mkFlag turnOff "no-" unSetGeneralFlag) negatableFlags
2692 ++ map (mkFlag turnOn "d" setGeneralFlag ) dFlags
2693 ++ map (mkFlag turnOff "dno-" unSetGeneralFlag) dFlags
2694 ++ map (mkFlag turnOn "f" setGeneralFlag ) fFlags
2695 ++ map (mkFlag turnOff "fno-" unSetGeneralFlag) fFlags
2696 ++ map (mkFlag turnOn "f" setWarningFlag ) fWarningFlags
2697 ++ map (mkFlag turnOff "fno-" unSetWarningFlag) fWarningFlags
2698 ++ map (mkFlag turnOn "f" setExtensionFlag ) fLangFlags
2699 ++ map (mkFlag turnOff "fno-" unSetExtensionFlag) fLangFlags
2700 ++ map (mkFlag turnOn "X" setExtensionFlag ) xFlags
2701 ++ map (mkFlag turnOff "XNo" unSetExtensionFlag) xFlags
2702 ++ map (mkFlag turnOn "X" setLanguage) languageFlags
2703 ++ map (mkFlag turnOn "X" setSafeHaskell) safeHaskellFlags
2704 ++ [ defFlag "XGenerics"
2705 (NoArg (deprecate $
2706 "it does nothing; look into -XDefaultSignatures " ++
2707 "and -XDeriveGeneric for generic programming support."))
2708 , defFlag "XNoGenerics"
2709 (NoArg (deprecate $
2710 "it does nothing; look into -XDefaultSignatures and " ++
2711 "-XDeriveGeneric for generic programming support.")) ]
2712
2713 -- See Note [Supporting CLI completion]
2714 package_flags :: [Flag (CmdLineP DynFlags)]
2715 package_flags = [
2716 ------- Packages ----------------------------------------------------
2717 defFlag "package-db" (HasArg (addPkgConfRef . PkgConfFile))
2718 , defFlag "clear-package-db" (NoArg clearPkgConf)
2719 , defFlag "no-global-package-db" (NoArg removeGlobalPkgConf)
2720 , defFlag "no-user-package-db" (NoArg removeUserPkgConf)
2721 , defFlag "global-package-db" (NoArg (addPkgConfRef GlobalPkgConf))
2722 , defFlag "user-package-db" (NoArg (addPkgConfRef UserPkgConf))
2723
2724 -- backwards compat with GHC<=7.4 :
2725 , defFlag "package-conf" (HasArg $ \path -> do
2726 addPkgConfRef (PkgConfFile path)
2727 deprecate "Use -package-db instead")
2728 , defFlag "no-user-package-conf"
2729 (NoArg $ do removeUserPkgConf
2730 deprecate "Use -no-user-package-db instead")
2731
2732 , defGhcFlag "package-name" (HasArg $ \name -> do
2733 upd (setPackageKey name)
2734 deprecate "Use -this-package-key instead")
2735 , defGhcFlag "this-package-key" (hasArg setPackageKey)
2736 , defFlag "package-id" (HasArg exposePackageId)
2737 , defFlag "package" (HasArg exposePackage)
2738 , defFlag "package-key" (HasArg exposePackageKey)
2739 , defFlag "hide-package" (HasArg hidePackage)
2740 , defFlag "hide-all-packages" (NoArg (setGeneralFlag Opt_HideAllPackages))
2741 , defFlag "package-env" (HasArg setPackageEnv)
2742 , defFlag "ignore-package" (HasArg ignorePackage)
2743 , defFlag "syslib"
2744 (HasArg (\s -> do exposePackage s
2745 deprecate "Use -package instead"))
2746 , defFlag "distrust-all-packages"
2747 (NoArg (setGeneralFlag Opt_DistrustAllPackages))
2748 , defFlag "trust" (HasArg trustPackage)
2749 , defFlag "distrust" (HasArg distrustPackage)
2750 ]
2751 where
2752 setPackageEnv env = upd $ \s -> s { packageEnv = Just env }
2753
2754 -- | Make a list of flags for shell completion.
2755 -- Filter all available flags into two groups, for interactive GHC vs all other.
2756 flagsForCompletion :: Bool -> [String]
2757 flagsForCompletion isInteractive
2758 = [ '-':flagName flag
2759 | flag <- flagsAll
2760 , modeFilter (flagGhcMode flag)
2761 ]
2762 where
2763 modeFilter AllModes = True
2764 modeFilter OnlyGhci = isInteractive
2765 modeFilter OnlyGhc = not isInteractive
2766 modeFilter HiddenFlag = False
2767
2768 type TurnOnFlag = Bool -- True <=> we are turning the flag on
2769 -- False <=> we are turning the flag off
2770 turnOn :: TurnOnFlag; turnOn = True
2771 turnOff :: TurnOnFlag; turnOff = False
2772
2773 data FlagSpec flag
2774 = FlagSpec
2775 { flagSpecName :: String -- ^ Flag in string form
2776 , flagSpecFlag :: flag -- ^ Flag in internal form
2777 , flagSpecAction :: (TurnOnFlag -> DynP ())
2778 -- ^ Extra action to run when the flag is found
2779 -- Typically, emit a warning or error
2780 , flagSpecGhcMode :: GhcFlagMode
2781 -- ^ In which ghc mode the flag has effect
2782 }
2783
2784 -- | Define a new flag.
2785 flagSpec :: String -> flag -> FlagSpec flag
2786 flagSpec name flag = flagSpec' name flag nop
2787
2788 -- | Define a new flag with an effect.
2789 flagSpec' :: String -> flag -> (TurnOnFlag -> DynP ()) -> FlagSpec flag
2790 flagSpec' name flag act = FlagSpec name flag act AllModes
2791
2792 -- | Define a new flag for GHCi.
2793 flagGhciSpec :: String -> flag -> FlagSpec flag
2794 flagGhciSpec name flag = flagGhciSpec' name flag nop
2795
2796 -- | Define a new flag for GHCi with an effect.
2797 flagGhciSpec' :: String -> flag -> (TurnOnFlag -> DynP ()) -> FlagSpec flag
2798 flagGhciSpec' name flag act = FlagSpec name flag act OnlyGhci
2799
2800 -- | Define a new flag invisible to CLI completion.
2801 flagHiddenSpec :: String -> flag -> FlagSpec flag
2802 flagHiddenSpec name flag = flagHiddenSpec' name flag nop
2803
2804 -- | Define a new flag invisible to CLI completion with an effect.
2805 flagHiddenSpec' :: String -> flag -> (TurnOnFlag -> DynP ()) -> FlagSpec flag
2806 flagHiddenSpec' name flag act = FlagSpec name flag act HiddenFlag
2807
2808 mkFlag :: TurnOnFlag -- ^ True <=> it should be turned on
2809 -> String -- ^ The flag prefix
2810 -> (flag -> DynP ()) -- ^ What to do when the flag is found
2811 -> FlagSpec flag -- ^ Specification of this particular flag
2812 -> Flag (CmdLineP DynFlags)
2813 mkFlag turn_on flagPrefix f (FlagSpec name flag extra_action mode)
2814 = Flag (flagPrefix ++ name) (NoArg (f flag >> extra_action turn_on)) mode
2815
2816 deprecatedForExtension :: String -> TurnOnFlag -> DynP ()
2817 deprecatedForExtension lang turn_on
2818 = deprecate ("use -X" ++ flag ++
2819 " or pragma {-# LANGUAGE " ++ flag ++ " #-} instead")
2820 where
2821 flag | turn_on = lang
2822 | otherwise = "No"++lang
2823
2824 useInstead :: String -> TurnOnFlag -> DynP ()
2825 useInstead flag turn_on
2826 = deprecate ("Use -f" ++ no ++ flag ++ " instead")
2827 where
2828 no = if turn_on then "" else "no-"
2829
2830 nop :: TurnOnFlag -> DynP ()
2831 nop _ = return ()
2832
2833 -- | These @-f\<blah\>@ flags can all be reversed with @-fno-\<blah\>@
2834 fWarningFlags :: [FlagSpec WarningFlag]
2835 fWarningFlags = [
2836 -- See Note [Updating flag description in the User's Guide]
2837 -- See Note [Supporting CLI completion]
2838 -- Please keep the list of flags below sorted alphabetically
2839 flagSpec "warn-alternative-layout-rule-transitional"
2840 Opt_WarnAlternativeLayoutRuleTransitional,
2841 flagSpec' "warn-amp" Opt_WarnAMP
2842 (\_ -> deprecate "it has no effect, and will be removed in GHC 7.12"),
2843 flagSpec "warn-auto-orphans" Opt_WarnAutoOrphans,
2844 flagSpec "warn-deprecations" Opt_WarnWarningsDeprecations,
2845 flagSpec "warn-deprecated-flags" Opt_WarnDeprecatedFlags,
2846 flagSpec "warn-deriving-typeable" Opt_WarnDerivingTypeable,
2847 flagSpec "warn-dodgy-exports" Opt_WarnDodgyExports,
2848 flagSpec "warn-dodgy-foreign-imports" Opt_WarnDodgyForeignImports,
2849 flagSpec "warn-dodgy-imports" Opt_WarnDodgyImports,
2850 flagSpec "warn-empty-enumerations" Opt_WarnEmptyEnumerations,
2851 flagSpec "warn-context-quantification" Opt_WarnContextQuantification,
2852 flagSpec' "warn-duplicate-constraints" Opt_WarnDuplicateConstraints
2853 (\_ -> deprecate "it is subsumed by -fwarn-redundant-constraints"),
2854 flagSpec "warn-redundant-constraints" Opt_WarnRedundantConstraints,
2855 flagSpec "warn-duplicate-exports" Opt_WarnDuplicateExports,
2856 flagSpec "warn-hi-shadowing" Opt_WarnHiShadows,
2857 flagSpec "warn-implicit-prelude" Opt_WarnImplicitPrelude,
2858 flagSpec "warn-incomplete-patterns" Opt_WarnIncompletePatterns,
2859 flagSpec "warn-incomplete-record-updates" Opt_WarnIncompletePatternsRecUpd,
2860 flagSpec "warn-incomplete-uni-patterns" Opt_WarnIncompleteUniPatterns,
2861 flagSpec "warn-inline-rule-shadowing" Opt_WarnInlineRuleShadowing,
2862 flagSpec "warn-identities" Opt_WarnIdentities,
2863 flagSpec "warn-missing-fields" Opt_WarnMissingFields,
2864 flagSpec "warn-missing-import-lists" Opt_WarnMissingImportList,
2865 flagSpec "warn-missing-local-sigs" Opt_WarnMissingLocalSigs,
2866 flagSpec "warn-missing-methods" Opt_WarnMissingMethods,
2867 flagSpec "warn-missing-signatures" Opt_WarnMissingSigs,
2868 flagSpec "warn-missing-exported-sigs" Opt_WarnMissingExportedSigs,
2869 flagSpec "warn-monomorphism-restriction" Opt_WarnMonomorphism,
2870 flagSpec "warn-name-shadowing" Opt_WarnNameShadowing,
2871 flagSpec "warn-orphans" Opt_WarnOrphans,
2872 flagSpec "warn-overflowed-literals" Opt_WarnOverflowedLiterals,
2873 flagSpec "warn-overlapping-patterns" Opt_WarnOverlappingPatterns,
2874 flagSpec "warn-pointless-pragmas" Opt_WarnPointlessPragmas,
2875 flagSpec' "warn-safe" Opt_WarnSafe setWarnSafe,
2876 flagSpec "warn-trustworthy-safe" Opt_WarnTrustworthySafe,
2877 flagSpec "warn-tabs" Opt_WarnTabs,
2878 flagSpec "warn-type-defaults" Opt_WarnTypeDefaults,
2879 flagSpec "warn-typed-holes" Opt_WarnTypedHoles,
2880 flagSpec "warn-partial-type-signatures" Opt_WarnPartialTypeSignatures,
2881 flagSpec "warn-unrecognised-pragmas" Opt_WarnUnrecognisedPragmas,
2882 flagSpec' "warn-unsafe" Opt_WarnUnsafe setWarnUnsafe,
2883 flagSpec "warn-unsupported-calling-conventions"
2884 Opt_WarnUnsupportedCallingConventions,
2885 flagSpec "warn-unsupported-llvm-version" Opt_WarnUnsupportedLlvmVersion,
2886 flagSpec "warn-unticked-promoted-constructors"
2887 Opt_WarnUntickedPromotedConstructors,
2888 flagSpec "warn-unused-do-bind" Opt_WarnUnusedDoBind,
2889 flagSpec "warn-unused-imports" Opt_WarnUnusedImports,
2890 flagSpec "warn-unused-local-binds" Opt_WarnUnusedLocalBinds,
2891 flagSpec "warn-unused-matches" Opt_WarnUnusedMatches,
2892 flagSpec "warn-unused-pattern-binds" Opt_WarnUnusedPatternBinds,
2893 flagSpec "warn-unused-top-binds" Opt_WarnUnusedTopBinds,
2894 flagSpec "warn-warnings-deprecations" Opt_WarnWarningsDeprecations,
2895 flagSpec "warn-wrong-do-bind" Opt_WarnWrongDoBind]
2896
2897 -- | These @-\<blah\>@ flags can all be reversed with @-no-\<blah\>@
2898 negatableFlags :: [FlagSpec GeneralFlag]
2899 negatableFlags = [
2900 flagGhciSpec "ignore-dot-ghci" Opt_IgnoreDotGhci ]
2901
2902 -- | These @-d\<blah\>@ flags can all be reversed with @-dno-\<blah\>@
2903 dFlags :: [FlagSpec GeneralFlag]
2904 dFlags = [
2905 -- See Note [Updating flag description in the User's Guide]
2906 -- See Note [Supporting CLI completion]
2907 -- Please keep the list of flags below sorted alphabetically
2908 flagSpec "ppr-case-as-let" Opt_PprCaseAsLet,
2909 flagSpec "ppr-ticks" Opt_PprShowTicks,
2910 flagSpec "suppress-coercions" Opt_SuppressCoercions,
2911 flagSpec "suppress-idinfo" Opt_SuppressIdInfo,
2912 flagSpec "suppress-module-prefixes" Opt_SuppressModulePrefixes,
2913 flagSpec "suppress-type-applications" Opt_SuppressTypeApplications,
2914 flagSpec "suppress-type-signatures" Opt_SuppressTypeSignatures,
2915 flagSpec "suppress-uniques" Opt_SuppressUniques,
2916 flagSpec "suppress-var-kinds" Opt_SuppressVarKinds]
2917
2918 -- | These @-f\<blah\>@ flags can all be reversed with @-fno-\<blah\>@
2919 fFlags :: [FlagSpec GeneralFlag]
2920 fFlags = [
2921 -- See Note [Updating flag description in the User's Guide]
2922 -- See Note [Supporting CLI completion]
2923 -- Please keep the list of flags below sorted alphabetically
2924 flagGhciSpec "break-on-error" Opt_BreakOnError,
2925 flagGhciSpec "break-on-exception" Opt_BreakOnException,
2926 flagSpec "building-cabal-package" Opt_BuildingCabalPackage,
2927 flagSpec "call-arity" Opt_CallArity,
2928 flagSpec "case-merge" Opt_CaseMerge,
2929 flagSpec "cmm-elim-common-blocks" Opt_CmmElimCommonBlocks,
2930 flagSpec "cmm-sink" Opt_CmmSink,
2931 flagSpec "cse" Opt_CSE,
2932 flagSpec "defer-type-errors" Opt_DeferTypeErrors,
2933 flagSpec "defer-typed-holes" Opt_DeferTypedHoles,
2934 flagSpec "dicts-cheap" Opt_DictsCheap,
2935 flagSpec "dicts-strict" Opt_DictsStrict,
2936 flagSpec "dmd-tx-dict-sel" Opt_DmdTxDictSel,
2937 flagSpec "do-eta-reduction" Opt_DoEtaReduction,
2938 flagSpec "do-lambda-eta-expansion" Opt_DoLambdaEtaExpansion,
2939 flagSpec "eager-blackholing" Opt_EagerBlackHoling,
2940 flagSpec "embed-manifest" Opt_EmbedManifest,
2941 flagSpec "enable-rewrite-rules" Opt_EnableRewriteRules,
2942 flagSpec "error-spans" Opt_ErrorSpans,
2943 flagSpec "excess-precision" Opt_ExcessPrecision,
2944 flagSpec "expose-all-unfoldings" Opt_ExposeAllUnfoldings,
2945 flagSpec "flat-cache" Opt_FlatCache,
2946 flagSpec "float-in" Opt_FloatIn,
2947 flagSpec "force-recomp" Opt_ForceRecomp,
2948 flagSpec "full-laziness" Opt_FullLaziness,
2949 flagSpec "fun-to-thunk" Opt_FunToThunk,
2950 flagSpec "gen-manifest" Opt_GenManifest,
2951 flagSpec "ghci-history" Opt_GhciHistory,
2952 flagSpec "ghci-sandbox" Opt_GhciSandbox,
2953 flagSpec "helpful-errors" Opt_HelpfulErrors,
2954 flagSpec "hpc" Opt_Hpc,
2955 flagSpec "ignore-asserts" Opt_IgnoreAsserts,
2956 flagSpec "ignore-interface-pragmas" Opt_IgnoreInterfacePragmas,
2957 flagGhciSpec "implicit-import-qualified" Opt_ImplicitImportQualified,
2958 flagSpec "irrefutable-tuples" Opt_IrrefutableTuples,
2959 flagSpec "kill-absence" Opt_KillAbsence,
2960 flagSpec "kill-one-shot" Opt_KillOneShot,
2961 flagSpec "late-dmd-anal" Opt_LateDmdAnal,
2962 flagSpec "liberate-case" Opt_LiberateCase,
2963 flagHiddenSpec "llvm-pass-vectors-in-regs" Opt_LlvmPassVectorsInRegisters,
2964 flagHiddenSpec "llvm-tbaa" Opt_LlvmTBAA,
2965 flagSpec "loopification" Opt_Loopification,
2966 flagSpec "omit-interface-pragmas" Opt_OmitInterfacePragmas,
2967 flagSpec "omit-yields" Opt_OmitYields,
2968 flagSpec "pedantic-bottoms" Opt_PedanticBottoms,
2969 flagSpec "pre-inlining" Opt_SimplPreInlining,
2970 flagGhciSpec "print-bind-contents" Opt_PrintBindContents,
2971 flagGhciSpec "print-bind-result" Opt_PrintBindResult,
2972 flagGhciSpec "print-evld-with-show" Opt_PrintEvldWithShow,
2973 flagSpec "print-explicit-foralls" Opt_PrintExplicitForalls,
2974 flagSpec "print-explicit-kinds" Opt_PrintExplicitKinds,
2975 flagSpec "print-unicode-syntax" Opt_PrintUnicodeSyntax,
2976 flagSpec "prof-cafs" Opt_AutoSccsOnIndividualCafs,
2977 flagSpec "prof-count-entries" Opt_ProfCountEntries,
2978 flagSpec "regs-graph" Opt_RegsGraph,
2979 flagSpec "regs-iterative" Opt_RegsIterative,
2980 flagSpec' "rewrite-rules" Opt_EnableRewriteRules
2981 (useInstead "enable-rewrite-rules"),
2982 flagSpec "shared-implib" Opt_SharedImplib,
2983 flagSpec "simple-list-literals" Opt_SimpleListLiterals,
2984 flagSpec "spec-constr" Opt_SpecConstr,
2985 flagSpec "specialise" Opt_Specialise,
2986 flagSpec "specialise-aggressively" Opt_SpecialiseAggressively,
2987 flagSpec "static-argument-transformation" Opt_StaticArgumentTransformation,
2988 flagSpec "strictness" Opt_Strictness,
2989 flagSpec "use-rpaths" Opt_RPath,
2990 flagSpec "write-interface" Opt_WriteInterface,
2991 flagSpec "unbox-small-strict-fields" Opt_UnboxSmallStrictFields,
2992 flagSpec "unbox-strict-fields" Opt_UnboxStrictFields,
2993 flagSpec "vectorisation-avoidance" Opt_VectorisationAvoidance,
2994 flagSpec "vectorise" Opt_Vectorise
2995 ]
2996
2997 -- | These @-f\<blah\>@ flags can all be reversed with @-fno-\<blah\>@
2998 fLangFlags :: [FlagSpec ExtensionFlag]
2999 fLangFlags = [
3000 -- See Note [Updating flag description in the User's Guide]
3001 -- See Note [Supporting CLI completion]
3002 flagSpec' "th" Opt_TemplateHaskell
3003 (\on -> deprecatedForExtension "TemplateHaskell" on
3004 >> setTemplateHaskellLoc on),
3005 flagSpec' "fi" Opt_ForeignFunctionInterface
3006 (deprecatedForExtension "ForeignFunctionInterface"),
3007 flagSpec' "ffi" Opt_ForeignFunctionInterface
3008 (deprecatedForExtension "ForeignFunctionInterface"),
3009 flagSpec' "arrows" Opt_Arrows
3010 (deprecatedForExtension "Arrows"),
3011 flagSpec' "implicit-prelude" Opt_ImplicitPrelude
3012 (deprecatedForExtension "ImplicitPrelude"),
3013 flagSpec' "bang-patterns" Opt_BangPatterns
3014 (deprecatedForExtension "BangPatterns"),
3015 flagSpec' "monomorphism-restriction" Opt_MonomorphismRestriction
3016 (deprecatedForExtension "MonomorphismRestriction"),
3017 flagSpec' "mono-pat-binds" Opt_MonoPatBinds
3018 (deprecatedForExtension "MonoPatBinds"),
3019 flagSpec' "extended-default-rules" Opt_ExtendedDefaultRules
3020 (deprecatedForExtension "ExtendedDefaultRules"),
3021 flagSpec' "implicit-params" Opt_ImplicitParams
3022 (deprecatedForExtension "ImplicitParams"),
3023 flagSpec' "scoped-type-variables" Opt_ScopedTypeVariables
3024 (deprecatedForExtension "ScopedTypeVariables"),
3025 flagSpec' "parr" Opt_ParallelArrays
3026 (deprecatedForExtension "ParallelArrays"),
3027 flagSpec' "PArr" Opt_ParallelArrays
3028 (deprecatedForExtension "ParallelArrays"),
3029 flagSpec' "allow-overlapping-instances" Opt_OverlappingInstances
3030 (deprecatedForExtension "OverlappingInstances"),
3031 flagSpec' "allow-undecidable-instances" Opt_UndecidableInstances
3032 (deprecatedForExtension "UndecidableInstances"),
3033 flagSpec' "allow-incoherent-instances" Opt_IncoherentInstances
3034 (deprecatedForExtension "IncoherentInstances")
3035 ]
3036
3037 supportedLanguages :: [String]
3038 supportedLanguages = map flagSpecName languageFlags
3039
3040 supportedLanguageOverlays :: [String]
3041 supportedLanguageOverlays = map flagSpecName safeHaskellFlags
3042
3043 supportedExtensions :: [String]
3044 supportedExtensions
3045 = concatMap (\name -> [name, "No" ++ name]) (map flagSpecName xFlags)
3046
3047 supportedLanguagesAndExtensions :: [String]
3048 supportedLanguagesAndExtensions =
3049 supportedLanguages ++ supportedLanguageOverlays ++ supportedExtensions
3050
3051 -- | These -X<blah> flags cannot be reversed with -XNo<blah>
3052 languageFlags :: [FlagSpec Language]
3053 languageFlags = [
3054 flagSpec "Haskell98" Haskell98,
3055 flagSpec "Haskell2010" Haskell2010
3056 ]
3057
3058 -- | These -X<blah> flags cannot be reversed with -XNo<blah>
3059 -- They are used to place hard requirements on what GHC Haskell language
3060 -- features can be used.
3061 safeHaskellFlags :: [FlagSpec SafeHaskellMode]
3062 safeHaskellFlags = [mkF Sf_Unsafe, mkF Sf_Trustworthy, mkF Sf_Safe]
3063 where mkF flag = flagSpec (show flag) flag
3064
3065 -- | These -X<blah> flags can all be reversed with -XNo<blah>
3066 xFlags :: [FlagSpec ExtensionFlag]
3067 xFlags = [
3068 -- See Note [Updating flag description in the User's Guide]
3069 -- See Note [Supporting CLI completion]
3070 -- Please keep the list of flags below sorted alphabetically
3071 flagSpec "AllowAmbiguousTypes" Opt_AllowAmbiguousTypes,
3072 flagSpec "AlternativeLayoutRule" Opt_AlternativeLayoutRule,
3073 flagSpec "AlternativeLayoutRuleTransitional"
3074 Opt_AlternativeLayoutRuleTransitional,
3075 flagSpec "Arrows" Opt_Arrows,
3076 flagSpec "AutoDeriveTypeable" Opt_AutoDeriveTypeable,
3077 flagSpec "BangPatterns" Opt_BangPatterns,
3078 flagSpec "BinaryLiterals" Opt_BinaryLiterals,
3079 flagSpec "CApiFFI" Opt_CApiFFI,
3080 flagSpec "CPP" Opt_Cpp,
3081 flagSpec "ConstrainedClassMethods" Opt_ConstrainedClassMethods,
3082 flagSpec "ConstraintKinds" Opt_ConstraintKinds,
3083 flagSpec "DataKinds" Opt_DataKinds,
3084 flagSpec' "DatatypeContexts" Opt_DatatypeContexts
3085 (\ turn_on -> when turn_on $
3086 deprecate $ "It was widely considered a misfeature, " ++
3087 "and has been removed from the Haskell language."),
3088 flagSpec "DefaultSignatures" Opt_DefaultSignatures,
3089 flagSpec "DeriveAnyClass" Opt_DeriveAnyClass,
3090 flagSpec "DeriveDataTypeable" Opt_DeriveDataTypeable,
3091 flagSpec "DeriveFoldable" Opt_DeriveFoldable,
3092 flagSpec "DeriveFunctor" Opt_DeriveFunctor,
3093 flagSpec "DeriveGeneric" Opt_DeriveGeneric,
3094 flagSpec "DeriveTraversable" Opt_DeriveTraversable,
3095 flagSpec "DisambiguateRecordFields" Opt_DisambiguateRecordFields,
3096 flagSpec "DoAndIfThenElse" Opt_DoAndIfThenElse,
3097 flagSpec' "DoRec" Opt_RecursiveDo
3098 (deprecatedForExtension "RecursiveDo"),
3099 flagSpec "EmptyCase" Opt_EmptyCase,
3100 flagSpec "EmptyDataDecls" Opt_EmptyDataDecls,
3101 flagSpec "ExistentialQuantification" Opt_ExistentialQuantification,
3102 flagSpec "ExplicitForAll" Opt_ExplicitForAll,
3103 flagSpec "ExplicitNamespaces" Opt_ExplicitNamespaces,
3104 flagSpec "ExtendedDefaultRules" Opt_ExtendedDefaultRules,
3105 flagSpec "FlexibleContexts" Opt_FlexibleContexts,
3106 flagSpec "FlexibleInstances" Opt_FlexibleInstances,
3107 flagSpec "ForeignFunctionInterface" Opt_ForeignFunctionInterface,
3108 flagSpec "FunctionalDependencies" Opt_FunctionalDependencies,
3109 flagSpec "GADTSyntax" Opt_GADTSyntax,
3110 flagSpec "GADTs" Opt_GADTs,
3111 flagSpec "GHCForeignImportPrim" Opt_GHCForeignImportPrim,
3112 flagSpec' "GeneralizedNewtypeDeriving" Opt_GeneralizedNewtypeDeriving
3113 setGenDeriving,
3114 flagSpec "ImplicitParams" Opt_ImplicitParams,
3115 flagSpec "ImplicitPrelude" Opt_ImplicitPrelude,
3116 flagSpec "ImpredicativeTypes" Opt_ImpredicativeTypes,
3117 flagSpec' "IncoherentInstances" Opt_IncoherentInstances
3118 setIncoherentInsts,
3119 flagSpec "InstanceSigs" Opt_InstanceSigs,
3120 flagSpec "InterruptibleFFI" Opt_InterruptibleFFI,
3121 flagSpec "JavaScriptFFI" Opt_JavaScriptFFI,
3122 flagSpec "KindSignatures" Opt_KindSignatures,
3123 flagSpec "LambdaCase" Opt_LambdaCase,
3124 flagSpec "LiberalTypeSynonyms" Opt_LiberalTypeSynonyms,
3125 flagSpec "MagicHash" Opt_MagicHash,
3126 flagSpec "MonadComprehensions" Opt_MonadComprehensions,
3127 flagSpec "MonoLocalBinds" Opt_MonoLocalBinds,
3128 flagSpec' "MonoPatBinds" Opt_MonoPatBinds
3129 (\ turn_on -> when turn_on $
3130 deprecate "Experimental feature now removed; has no effect"),
3131 flagSpec "MonomorphismRestriction" Opt_MonomorphismRestriction,
3132 flagSpec "MultiParamTypeClasses" Opt_MultiParamTypeClasses,
3133 flagSpec "MultiWayIf" Opt_MultiWayIf,
3134 flagSpec "NPlusKPatterns" Opt_NPlusKPatterns,
3135 flagSpec "NamedFieldPuns" Opt_RecordPuns,
3136 flagSpec "NamedWildCards" Opt_NamedWildCards,
3137 flagSpec "NegativeLiterals" Opt_NegativeLiterals,
3138 flagSpec "NondecreasingIndentation" Opt_NondecreasingIndentation,
3139 flagSpec' "NullaryTypeClasses" Opt_NullaryTypeClasses
3140 (deprecatedForExtension "MultiParamTypeClasses"),
3141 flagSpec "NumDecimals" Opt_NumDecimals,
3142 flagSpec' "OverlappingInstances" Opt_OverlappingInstances
3143 setOverlappingInsts,
3144 flagSpec "OverloadedLists" Opt_OverloadedLists,
3145 flagSpec "OverloadedStrings" Opt_OverloadedStrings,
3146 flagSpec "PackageImports" Opt_PackageImports,
3147 flagSpec "ParallelArrays" Opt_ParallelArrays,
3148 flagSpec "ParallelListComp" Opt_ParallelListComp,
3149 flagSpec "PartialTypeSignatures" Opt_PartialTypeSignatures,
3150 flagSpec "PatternGuards" Opt_PatternGuards,
3151 flagSpec' "PatternSignatures" Opt_ScopedTypeVariables
3152 (deprecatedForExtension "ScopedTypeVariables"),
3153 flagSpec "PatternSynonyms" Opt_PatternSynonyms,
3154 flagSpec "PolyKinds" Opt_PolyKinds,
3155 flagSpec "PolymorphicComponents" Opt_RankNTypes,
3156 flagSpec "PostfixOperators" Opt_PostfixOperators,
3157 flagSpec "QuasiQuotes" Opt_QuasiQuotes,
3158 flagSpec "Rank2Types" Opt_RankNTypes,
3159 flagSpec "RankNTypes" Opt_RankNTypes,
3160 flagSpec "RebindableSyntax" Opt_RebindableSyntax,
3161 flagSpec' "RecordPuns" Opt_RecordPuns
3162 (deprecatedForExtension "NamedFieldPuns"),
3163 flagSpec "RecordWildCards" Opt_RecordWildCards,
3164 flagSpec "RecursiveDo" Opt_RecursiveDo,
3165 flagSpec "RelaxedLayout" Opt_RelaxedLayout,
3166 flagSpec' "RelaxedPolyRec" Opt_RelaxedPolyRec
3167 (\ turn_on -> unless turn_on $
3168 deprecate "You can't turn off RelaxedPolyRec any more"),
3169 flagSpec "RoleAnnotations" Opt_RoleAnnotations,
3170 flagSpec "ScopedTypeVariables" Opt_ScopedTypeVariables,
3171 flagSpec "StandaloneDeriving" Opt_StandaloneDeriving,
3172 flagSpec "StaticPointers" Opt_StaticPointers,
3173 flagSpec' "TemplateHaskell" Opt_TemplateHaskell
3174 setTemplateHaskellLoc,
3175 flagSpec "TraditionalRecordSyntax" Opt_TraditionalRecordSyntax,
3176 flagSpec "TransformListComp" Opt_TransformListComp,
3177 flagSpec "TupleSections" Opt_TupleSections,
3178 flagSpec "TypeFamilies" Opt_TypeFamilies,
3179 flagSpec "TypeOperators" Opt_TypeOperators,
3180 flagSpec "TypeSynonymInstances" Opt_TypeSynonymInstances,
3181 flagSpec "UnboxedTuples" Opt_UnboxedTuples,
3182 flagSpec "UndecidableInstances" Opt_UndecidableInstances,
3183 flagSpec "UnicodeSyntax" Opt_UnicodeSyntax,
3184 flagSpec "UnliftedFFITypes" Opt_UnliftedFFITypes,
3185 flagSpec "ViewPatterns" Opt_ViewPatterns
3186 ]
3187
3188 defaultFlags :: Settings -> [GeneralFlag]
3189 defaultFlags settings
3190 -- See Note [Updating flag description in the User's Guide]
3191 = [ Opt_AutoLinkPackages,
3192 Opt_EmbedManifest,
3193 Opt_FlatCache,
3194 Opt_GenManifest,
3195 Opt_GhciHistory,
3196 Opt_GhciSandbox,
3197 Opt_HelpfulErrors,
3198 Opt_OmitYields,
3199 Opt_PrintBindContents,
3200 Opt_ProfCountEntries,
3201 Opt_RPath,
3202 Opt_SharedImplib,
3203 Opt_SimplPreInlining
3204 ]
3205
3206 ++ [f | (ns,f) <- optLevelFlags, 0 `elem` ns]
3207 -- The default -O0 options
3208
3209 ++ default_PIC platform
3210
3211 ++ (if pc_DYNAMIC_BY_DEFAULT (sPlatformConstants settings)
3212 then wayGeneralFlags platform WayDyn
3213 else [])
3214
3215 where platform = sTargetPlatform settings
3216
3217 default_PIC :: Platform -> [GeneralFlag]
3218 default_PIC platform =
3219 case (platformOS platform, platformArch platform) of
3220 (OSDarwin, ArchX86_64) -> [Opt_PIC]
3221 _ -> []
3222
3223 impliedGFlags :: [(GeneralFlag, TurnOnFlag, GeneralFlag)]
3224 impliedGFlags = [(Opt_DeferTypeErrors, turnOn, Opt_DeferTypedHoles)]
3225
3226 impliedXFlags :: [(ExtensionFlag, TurnOnFlag, ExtensionFlag)]
3227 impliedXFlags
3228 -- See Note [Updating flag description in the User's Guide]
3229 = [ (Opt_RankNTypes, turnOn, Opt_ExplicitForAll)
3230 , (Opt_ScopedTypeVariables, turnOn, Opt_ExplicitForAll)
3231 , (Opt_LiberalTypeSynonyms, turnOn, Opt_ExplicitForAll)
3232 , (Opt_ExistentialQuantification, turnOn, Opt_ExplicitForAll)
3233 , (Opt_FlexibleInstances, turnOn, Opt_TypeSynonymInstances)
3234 , (Opt_FunctionalDependencies, turnOn, Opt_MultiParamTypeClasses)
3235 , (Opt_MultiParamTypeClasses, turnOn, Opt_ConstrainedClassMethods) -- c.f. Trac #7854
3236
3237 , (Opt_RebindableSyntax, turnOff, Opt_ImplicitPrelude) -- NB: turn off!
3238
3239 , (Opt_GADTs, turnOn, Opt_GADTSyntax)
3240 , (Opt_GADTs, turnOn, Opt_MonoLocalBinds)
3241 , (Opt_TypeFamilies, turnOn, Opt_MonoLocalBinds)
3242
3243 , (Opt_TypeFamilies, turnOn, Opt_KindSignatures) -- Type families use kind signatures
3244 , (Opt_PolyKinds, turnOn, Opt_KindSignatures) -- Ditto polymorphic kinds
3245
3246 -- AutoDeriveTypeable is not very useful without DeriveDataTypeable
3247 , (Opt_AutoDeriveTypeable, turnOn, Opt_DeriveDataTypeable)
3248
3249 -- We turn this on so that we can export associated type
3250 -- type synonyms in subordinates (e.g. MyClass(type AssocType))
3251 , (Opt_TypeFamilies, turnOn, Opt_ExplicitNamespaces)
3252 , (Opt_TypeOperators, turnOn, Opt_ExplicitNamespaces)
3253
3254 , (Opt_ImpredicativeTypes, turnOn, Opt_RankNTypes)
3255
3256 -- Record wild-cards implies field disambiguation
3257 -- Otherwise if you write (C {..}) you may well get
3258 -- stuff like " 'a' not in scope ", which is a bit silly
3259 -- if the compiler has just filled in field 'a' of constructor 'C'
3260 , (Opt_RecordWildCards, turnOn, Opt_DisambiguateRecordFields)
3261
3262 , (Opt_ParallelArrays, turnOn, Opt_ParallelListComp)
3263
3264 , (Opt_JavaScriptFFI, turnOn, Opt_InterruptibleFFI)
3265
3266 , (Opt_DeriveTraversable, turnOn, Opt_DeriveFunctor)
3267 , (Opt_DeriveTraversable, turnOn, Opt_DeriveFoldable)
3268 ]
3269
3270 -- Note [Documenting optimisation flags]
3271 -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
3272 --
3273 -- If you change the list of flags enabled for particular optimisation levels
3274 -- please remember to update the User's Guide. The relevant files are:
3275 --
3276 -- * docs/users_guide/flags.xml
3277 -- * docs/users_guide/using.xml
3278 --
3279 -- The first contains the Flag Refrence section, which breifly lists all
3280 -- available flags. The second contains a detailed description of the
3281 -- flags. Both places should contain information whether a flag is implied by
3282 -- -O0, -O or -O2.
3283
3284 optLevelFlags :: [([Int], GeneralFlag)]
3285 optLevelFlags -- see Note [Documenting optimisation flags]
3286 = [ ([0,1,2], Opt_DoLambdaEtaExpansion)
3287 , ([0,1,2], Opt_DmdTxDictSel)
3288 , ([0,1,2], Opt_LlvmTBAA)
3289 , ([0,1,2], Opt_VectorisationAvoidance)
3290 -- This one is important for a tiresome reason:
3291 -- we want to make sure that the bindings for data
3292 -- constructors are eta-expanded. This is probably
3293 -- a good thing anyway, but it seems fragile.
3294
3295 , ([0], Opt_IgnoreInterfacePragmas)
3296 , ([0], Opt_OmitInterfacePragmas)
3297
3298 , ([1,2], Opt_CallArity)
3299 , ([1,2], Opt_CaseMerge)
3300 , ([1,2], Opt_CmmElimCommonBlocks)
3301 , ([1,2], Opt_CmmSink)
3302 , ([1,2], Opt_CSE)
3303 , ([1,2], Opt_DoEtaReduction)
3304 , ([1,2], Opt_EnableRewriteRules) -- Off for -O0; see Note [Scoping for Builtin rules]
3305 -- in PrelRules
3306 , ([1,2], Opt_FloatIn)
3307 , ([1,2], Opt_FullLaziness)
3308 , ([1,2], Opt_IgnoreAsserts)
3309 , ([1,2], Opt_Loopification)
3310 , ([1,2], Opt_Specialise)
3311 , ([1,2], Opt_Strictness)
3312 , ([1,2], Opt_UnboxSmallStrictFields)
3313
3314 , ([2], Opt_LiberateCase)
3315 , ([2], Opt_SpecConstr)
3316 -- , ([2], Opt_RegsGraph)
3317 -- RegsGraph suffers performance regression. See #7679
3318 -- , ([2], Opt_StaticArgumentTransformation)
3319 -- Static Argument Transformation needs investigation. See #9374
3320 ]
3321
3322 -- -----------------------------------------------------------------------------
3323 -- Standard sets of warning options
3324
3325 -- Note [Documenting warning flags]
3326 -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
3327 --
3328 -- If you change the list of warning enabled by default
3329 -- please remember to update the User's Guide. The relevant file is:
3330 --
3331 -- * docs/users_guide/using.xml
3332
3333 standardWarnings :: [WarningFlag]
3334 standardWarnings -- see Note [Documenting warning flags]
3335 = [ Opt_WarnOverlappingPatterns,
3336 Opt_WarnWarningsDeprecations,
3337 Opt_WarnDeprecatedFlags,
3338 Opt_WarnTypedHoles,
3339 Opt_WarnPartialTypeSignatures,
3340 Opt_WarnUnrecognisedPragmas,
3341 Opt_WarnPointlessPragmas,
3342 Opt_WarnRedundantConstraints,
3343 Opt_WarnDuplicateExports,
3344 Opt_WarnOverflowedLiterals,
3345 Opt_WarnEmptyEnumerations,
3346 Opt_WarnMissingFields,
3347 Opt_WarnMissingMethods,
3348 Opt_WarnWrongDoBind,
3349 Opt_WarnUnsupportedCallingConventions,
3350 Opt_WarnDodgyForeignImports,
3351 Opt_WarnInlineRuleShadowing,
3352 Opt_WarnAlternativeLayoutRuleTransitional,
3353 Opt_WarnUnsupportedLlvmVersion,
3354 Opt_WarnContextQuantification,
3355 Opt_WarnTabs
3356 ]
3357
3358 minusWOpts :: [WarningFlag]
3359 -- Things you get with -W
3360 minusWOpts
3361 = standardWarnings ++
3362 [ Opt_WarnUnusedTopBinds,
3363 Opt_WarnUnusedLocalBinds,
3364 Opt_WarnUnusedPatternBinds,
3365 Opt_WarnUnusedMatches,
3366 Opt_WarnUnusedImports,
3367 Opt_WarnIncompletePatterns,
3368 Opt_WarnDodgyExports,
3369 Opt_WarnDodgyImports
3370 ]
3371
3372 minusWallOpts :: [WarningFlag]
3373 -- Things you get with -Wall
3374 minusWallOpts
3375 = minusWOpts ++
3376 [ Opt_WarnTypeDefaults,
3377 Opt_WarnNameShadowing,
3378 Opt_WarnMissingSigs,
3379 Opt_WarnHiShadows,
3380 Opt_WarnOrphans,
3381 Opt_WarnUnusedDoBind,
3382 Opt_WarnTrustworthySafe,
3383 Opt_WarnUntickedPromotedConstructors
3384 ]
3385
3386 enableUnusedBinds :: DynP ()
3387 enableUnusedBinds = mapM_ setWarningFlag unusedBindsFlags
3388
3389 disableUnusedBinds :: DynP ()
3390 disableUnusedBinds = mapM_ unSetWarningFlag unusedBindsFlags
3391
3392 -- Things you get with -fwarn-unused-binds
3393 unusedBindsFlags :: [WarningFlag]
3394 unusedBindsFlags = [ Opt_WarnUnusedTopBinds
3395 , Opt_WarnUnusedLocalBinds
3396 , Opt_WarnUnusedPatternBinds
3397 ]
3398
3399 enableGlasgowExts :: DynP ()
3400 enableGlasgowExts = do setGeneralFlag Opt_PrintExplicitForalls
3401 mapM_ setExtensionFlag glasgowExtsFlags
3402
3403 disableGlasgowExts :: DynP ()
3404 disableGlasgowExts = do unSetGeneralFlag Opt_PrintExplicitForalls
3405 mapM_ unSetExtensionFlag glasgowExtsFlags
3406
3407 glasgowExtsFlags :: [ExtensionFlag]
3408 glasgowExtsFlags = [
3409 Opt_ConstrainedClassMethods
3410 , Opt_DeriveDataTypeable
3411 , Opt_DeriveFoldable
3412 , Opt_DeriveFunctor
3413 , Opt_DeriveGeneric
3414 , Opt_DeriveTraversable
3415 , Opt_EmptyDataDecls
3416 , Opt_ExistentialQuantification
3417 , Opt_ExplicitNamespaces
3418 , Opt_FlexibleContexts
3419 , Opt_FlexibleInstances
3420 , Opt_ForeignFunctionInterface
3421 , Opt_FunctionalDependencies
3422 , Opt_GeneralizedNewtypeDeriving
3423 , Opt_ImplicitParams
3424 , Opt_KindSignatures
3425 , Opt_LiberalTypeSynonyms
3426 , Opt_MagicHash
3427 , Opt_MultiParamTypeClasses
3428 , Opt_ParallelListComp
3429 , Opt_PatternGuards
3430 , Opt_PostfixOperators
3431 , Opt_RankNTypes
3432 , Opt_RecursiveDo
3433 , Opt_ScopedTypeVariables
3434 , Opt_StandaloneDeriving
3435 , Opt_TypeOperators
3436 , Opt_TypeSynonymInstances
3437 , Opt_UnboxedTuples
3438 , Opt_UnicodeSyntax
3439 , Opt_UnliftedFFITypes ]
3440
3441 #ifdef GHCI
3442 -- Consult the RTS to find whether GHC itself has been built profiled
3443 -- If so, you can't use Template Haskell
3444 foreign import ccall unsafe "rts_isProfiled" rtsIsProfiledIO :: IO CInt
3445
3446 rtsIsProfiled :: Bool
3447 rtsIsProfiled = unsafeDupablePerformIO rtsIsProfiledIO /= 0
3448 #endif
3449
3450 #ifdef GHCI
3451 -- Consult the RTS to find whether GHC itself has been built with
3452 -- dynamic linking. This can't be statically known at compile-time,
3453 -- because we build both the static and dynamic versions together with
3454 -- -dynamic-too.
3455 foreign import ccall unsafe "rts_isDynamic" rtsIsDynamicIO :: IO CInt
3456
3457 dynamicGhc :: Bool
3458 dynamicGhc = unsafeDupablePerformIO rtsIsDynamicIO /= 0
3459 #else
3460 dynamicGhc :: Bool
3461 dynamicGhc = False
3462 #endif
3463
3464 setWarnSafe :: Bool -> DynP ()
3465 setWarnSafe True = getCurLoc >>= \l -> upd (\d -> d { warnSafeOnLoc = l })
3466 setWarnSafe False = return ()
3467
3468 setWarnUnsafe :: Bool -> DynP ()
3469 setWarnUnsafe True = getCurLoc >>= \l -> upd (\d -> d { warnUnsafeOnLoc = l })
3470 setWarnUnsafe False = return ()
3471
3472 setPackageTrust :: DynP ()
3473 setPackageTrust = do
3474 setGeneralFlag Opt_PackageTrust
3475 l <- getCurLoc
3476 upd $ \d -> d { pkgTrustOnLoc = l }
3477
3478 setGenDeriving :: TurnOnFlag -> DynP ()
3479 setGenDeriving True = getCurLoc >>= \l -> upd (\d -> d { newDerivOnLoc = l })
3480 setGenDeriving False = return ()
3481
3482 setOverlappingInsts :: TurnOnFlag -> DynP ()
3483 setOverlappingInsts False = return ()
3484 setOverlappingInsts True = do
3485 l <- getCurLoc
3486 upd (\d -> d { overlapInstLoc = l })
3487 deprecate "instead use per-instance pragmas OVERLAPPING/OVERLAPPABLE/OVERLAPS"
3488
3489 setIncoherentInsts :: TurnOnFlag -> DynP ()
3490 setIncoherentInsts False = return ()
3491 setIncoherentInsts True = do
3492 l <- getCurLoc
3493 upd (\d -> d { incoherentOnLoc = l })
3494
3495 setTemplateHaskellLoc :: TurnOnFlag -> DynP ()
3496 setTemplateHaskellLoc _
3497 = getCurLoc >>= \l -> upd (\d -> d { thOnLoc = l })
3498
3499 {- **********************************************************************
3500 %* *
3501 DynFlags constructors
3502 %* *
3503 %********************************************************************* -}
3504
3505 type DynP = EwM (CmdLineP DynFlags)
3506
3507 upd :: (DynFlags -> DynFlags) -> DynP ()
3508 upd f = liftEwM (do dflags <- getCmdLineState
3509 putCmdLineState $! f dflags)
3510
3511 updM :: (DynFlags -> DynP DynFlags) -> DynP ()
3512 updM f = do dflags <- liftEwM getCmdLineState
3513 dflags' <- f dflags
3514 liftEwM $ putCmdLineState $! dflags'
3515
3516 --------------- Constructor functions for OptKind -----------------
3517 noArg :: (DynFlags -> DynFlags) -> OptKind (CmdLineP DynFlags)
3518 noArg fn = NoArg (upd fn)
3519
3520 noArgM :: (DynFlags -> DynP DynFlags) -> OptKind (CmdLineP DynFlags)
3521 noArgM fn = NoArg (updM fn)
3522
3523 hasArg :: (String -> DynFlags -> DynFlags) -> OptKind (CmdLineP DynFlags)
3524 hasArg fn = HasArg (upd . fn)
3525
3526 sepArg :: (String -> DynFlags -> DynFlags) -> OptKind (CmdLineP DynFlags)
3527 sepArg fn = SepArg (upd . fn)
3528
3529 intSuffix :: (Int -> DynFlags -> DynFlags) -> OptKind (CmdLineP DynFlags)
3530 intSuffix fn = IntSuffix (\n -> upd (fn n))
3531
3532 intSuffixM :: (Int -> DynFlags -> DynP DynFlags) -> OptKind (CmdLineP DynFlags)
3533 intSuffixM fn = IntSuffix (\n -> updM (fn n))
3534
3535 floatSuffix :: (Float -> DynFlags -> DynFlags) -> OptKind (CmdLineP DynFlags)
3536 floatSuffix fn = FloatSuffix (\n -> upd (fn n))
3537
3538 optIntSuffixM :: (Maybe Int -> DynFlags -> DynP DynFlags)
3539 -> OptKind (CmdLineP DynFlags)
3540 optIntSuffixM fn = OptIntSuffix (\mi -> updM (fn mi))
3541
3542 setDumpFlag :: DumpFlag -> OptKind (CmdLineP DynFlags)
3543 setDumpFlag dump_flag = NoArg (setDumpFlag' dump_flag)
3544
3545 --------------------------
3546 addWay :: Way -> DynP ()
3547 addWay w = upd (addWay' w)
3548
3549 addWay' :: Way -> DynFlags -> DynFlags
3550 addWay' w dflags0 = let platform = targetPlatform dflags0
3551 dflags1 = dflags0 { ways = w : ways dflags0 }
3552 dflags2 = wayExtras platform w dflags1
3553 dflags3 = foldr setGeneralFlag' dflags2
3554 (wayGeneralFlags platform w)
3555 dflags4 = foldr unSetGeneralFlag' dflags3
3556 (wayUnsetGeneralFlags platform w)
3557 in dflags4
3558
3559 removeWayDyn :: DynP ()
3560 removeWayDyn = upd (\dfs -> dfs { ways = filter (WayDyn /=) (ways dfs) })
3561
3562 --------------------------
3563 setGeneralFlag, unSetGeneralFlag :: GeneralFlag -> DynP ()
3564 setGeneralFlag f = upd (setGeneralFlag' f)
3565 unSetGeneralFlag f = upd (unSetGeneralFlag' f)
3566
3567 setGeneralFlag' :: GeneralFlag -> DynFlags -> DynFlags
3568 setGeneralFlag' f dflags = foldr ($) (gopt_set dflags f) deps
3569 where
3570 deps = [ if turn_on then setGeneralFlag' d
3571 else unSetGeneralFlag' d
3572 | (f', turn_on, d) <- impliedGFlags, f' == f ]
3573 -- When you set f, set the ones it implies
3574 -- NB: use setGeneralFlag recursively, in case the implied flags
3575 -- implies further flags
3576
3577 unSetGeneralFlag' :: GeneralFlag -> DynFlags -> DynFlags
3578 unSetGeneralFlag' f dflags = gopt_unset dflags f
3579 -- When you un-set f, however, we don't un-set the things it implies
3580
3581 --------------------------
3582 setWarningFlag, unSetWarningFlag :: WarningFlag -> DynP ()
3583 setWarningFlag f = upd (\dfs -> wopt_set dfs f)
3584 unSetWarningFlag f = upd (\dfs -> wopt_unset dfs f)
3585
3586 --------------------------
3587 setExtensionFlag, unSetExtensionFlag :: ExtensionFlag -> DynP ()
3588 setExtensionFlag f = upd (setExtensionFlag' f)
3589 unSetExtensionFlag f = upd (unSetExtensionFlag' f)
3590
3591 setExtensionFlag', unSetExtensionFlag' :: ExtensionFlag -> DynFlags -> DynFlags
3592 setExtensionFlag' f dflags = foldr ($) (xopt_set dflags f) deps
3593 where
3594 deps = [ if turn_on then setExtensionFlag' d
3595 else unSetExtensionFlag' d
3596 | (f', turn_on, d) <- impliedXFlags, f' == f ]
3597 -- When you set f, set the ones it implies
3598 -- NB: use setExtensionFlag recursively, in case the implied flags
3599 -- implies further flags
3600
3601 unSetExtensionFlag' f dflags = xopt_unset dflags f
3602 -- When you un-set f, however, we don't un-set the things it implies
3603 -- (except for -fno-glasgow-exts, which is treated specially)
3604
3605 --------------------------
3606 alterSettings :: (Settings -> Settings) -> DynFlags -> DynFlags
3607 alterSettings f dflags = dflags { settings = f (settings dflags) }
3608
3609 --------------------------
3610 setDumpFlag' :: DumpFlag -> DynP ()
3611 setDumpFlag' dump_flag
3612 = do upd (\dfs -> dopt_set dfs dump_flag)
3613 when want_recomp forceRecompile
3614 where -- Certain dumpy-things are really interested in what's going
3615 -- on during recompilation checking, so in those cases we
3616 -- don't want to turn it off.
3617 want_recomp = dump_flag `notElem` [Opt_D_dump_if_trace,
3618 Opt_D_dump_hi_diffs]
3619
3620 forceRecompile :: DynP ()
3621 -- Whenver we -ddump, force recompilation (by switching off the
3622 -- recompilation checker), else you don't see the dump! However,
3623 -- don't switch it off in --make mode, else *everything* gets
3624 -- recompiled which probably isn't what you want
3625 forceRecompile = do dfs <- liftEwM getCmdLineState
3626 when (force_recomp dfs) (setGeneralFlag Opt_ForceRecomp)
3627 where
3628 force_recomp dfs = isOneShot (ghcMode dfs)
3629
3630
3631 setVerboseCore2Core :: DynP ()
3632 setVerboseCore2Core = setDumpFlag' Opt_D_verbose_core2core
3633
3634 setVerbosity :: Maybe Int -> DynP ()
3635 setVerbosity mb_n = upd (\dfs -> dfs{ verbosity = mb_n `orElse` 3 })
3636
3637 addCmdlineHCInclude :: String -> DynP ()
3638 addCmdlineHCInclude a = upd (\s -> s{cmdlineHcIncludes = a : cmdlineHcIncludes s})
3639
3640 data PkgConfRef
3641 = GlobalPkgConf
3642 | UserPkgConf
3643 | PkgConfFile FilePath
3644
3645 addPkgConfRef :: PkgConfRef -> DynP ()
3646 addPkgConfRef p = upd $ \s -> s { extraPkgConfs = (p:) . extraPkgConfs s }
3647
3648 removeUserPkgConf :: DynP ()
3649 removeUserPkgConf = upd $ \s -> s { extraPkgConfs = filter isNotUser . extraPkgConfs s }
3650 where
3651 isNotUser UserPkgConf = False
3652 isNotUser _ = True
3653
3654 removeGlobalPkgConf :: DynP ()
3655 removeGlobalPkgConf = upd $ \s -> s { extraPkgConfs = filter isNotGlobal . extraPkgConfs s }
3656 where
3657 isNotGlobal GlobalPkgConf = False
3658 isNotGlobal _ = True
3659
3660 clearPkgConf :: DynP ()
3661 clearPkgConf = upd $ \s -> s { extraPkgConfs = const [] }
3662
3663 parseModuleName :: ReadP ModuleName
3664 parseModuleName = fmap mkModuleName
3665 $ munch1 (\c -> isAlphaNum c || c `elem` ".")
3666
3667 parsePackageFlag :: (String -> PackageArg) -- type of argument
3668 -> String -- string to parse
3669 -> PackageFlag
3670 parsePackageFlag constr str = case filter ((=="").snd) (readP_to_S parse str) of
3671 [(r, "")] -> r
3672 _ -> throwGhcException $ CmdLineError ("Can't parse package flag: " ++ str)
3673 where parse = do
3674 pkg <- tok $ munch1 (\c -> isAlphaNum c || c `elem` ":-_.")
3675 ( do _ <- tok $ string "with"
3676 fmap (ExposePackage (constr pkg) . ModRenaming True) parseRns
3677 <++ fmap (ExposePackage (constr pkg) . ModRenaming False) parseRns
3678 <++ return (ExposePackage (constr pkg) (ModRenaming True [])))
3679 parseRns = do _ <- tok $ R.char '('
3680 rns <- tok $ sepBy parseItem (tok $ R.char ',')
3681 _ <- tok $ R.char ')'
3682 return rns
3683 parseItem = do
3684 orig <- tok $ parseModuleName
3685 (do _ <- tok $ string "as"
3686 new <- tok $ parseModuleName
3687 return (orig, new)
3688 +++
3689 return (orig, orig))
3690 tok m = m >>= \x -> skipSpaces >> return x
3691
3692 exposePackage, exposePackageId, exposePackageKey, hidePackage, ignorePackage,
3693 trustPackage, distrustPackage :: String -> DynP ()
3694 exposePackage p = upd (exposePackage' p)
3695 exposePackageId p =
3696 upd (\s -> s{ packageFlags =
3697 parsePackageFlag PackageIdArg p : packageFlags s })
3698 exposePackageKey p =
3699 upd (\s -> s{ packageFlags =
3700 parsePackageFlag PackageKeyArg p : packageFlags s })
3701 hidePackage p =
3702 upd (\s -> s{ packageFlags = HidePackage p : packageFlags s })
3703 ignorePackage p =
3704 upd (\s -> s{ packageFlags = IgnorePackage p : packageFlags s })
3705 trustPackage p = exposePackage p >> -- both trust and distrust also expose a package
3706 upd (\s -> s{ packageFlags = TrustPackage p : packageFlags s })
3707 distrustPackage p = exposePackage p >>
3708 upd (\s -> s{ packageFlags = DistrustPackage p : packageFlags s })
3709
3710 exposePackage' :: String -> DynFlags -> DynFlags
3711 exposePackage' p dflags
3712 = dflags { packageFlags =
3713 parsePackageFlag PackageArg p : packageFlags dflags }
3714
3715 setPackageKey :: String -> DynFlags -> DynFlags
3716 setPackageKey p s = s{ thisPackage = stringToPackageKey p }
3717
3718 -- -----------------------------------------------------------------------------
3719 -- | Find the package environment (if one exists)
3720 --
3721 -- We interpret the package environment as a set of package flags; to be
3722 -- specific, if we find a package environment
3723 --
3724 -- > id1
3725 -- > id2
3726 -- > ..
3727 -- > idn
3728 --
3729 -- we interpret this as
3730 --
3731 -- > [ -hide-all-packages
3732 -- > , -package-id id1
3733 -- > , -package-id id2
3734 -- > , ..
3735 -- > , -package-id idn
3736 -- > ]
3737 interpretPackageEnv :: DynFlags -> IO DynFlags
3738 interpretPackageEnv dflags = do
3739 mPkgEnv <- runMaybeT $ msum $ [
3740 getCmdLineArg >>= \env -> msum [
3741 loadEnvFile env
3742 , loadEnvName env
3743 , cmdLineError env
3744 ]
3745 , getEnvVar >>= \env -> msum [
3746 loadEnvFile env
3747 , loadEnvName env
3748 , envError env
3749 ]
3750 , loadEnvFile localEnvFile
3751 , loadEnvName defaultEnvName
3752 ]
3753 case mPkgEnv of
3754 Nothing ->
3755 -- No environment found. Leave DynFlags unchanged.
3756 return dflags
3757 Just ids -> do
3758 let setFlags :: DynP ()
3759 setFlags = do
3760 setGeneralFlag Opt_HideAllPackages
3761 mapM_ exposePackageId (lines ids)
3762
3763 (_, dflags') = runCmdLine (runEwM setFlags) dflags
3764
3765 return dflags'
3766 where
3767 -- Loading environments (by name or by location)
3768
3769 namedEnvPath :: String -> MaybeT IO FilePath
3770 namedEnvPath name = do
3771 appdir <- liftMaybeT $ versionedAppDir dflags
3772 return $ appdir </> "environments" </> name
3773
3774 loadEnvName :: String -> MaybeT IO String
3775 loadEnvName name = loadEnvFile =<< namedEnvPath name
3776
3777 loadEnvFile :: String -> MaybeT IO String
3778 loadEnvFile path = do
3779 guard =<< liftMaybeT (doesFileExist path)
3780 liftMaybeT $ readFile path
3781
3782 -- Various ways to define which environment to use
3783
3784 getCmdLineArg :: MaybeT IO String
3785 getCmdLineArg = MaybeT $ return $ packageEnv dflags
3786
3787 getEnvVar :: MaybeT IO String
3788 getEnvVar = do
3789 mvar <- liftMaybeT $ try $ getEnv "GHC_ENVIRONMENT"
3790 case mvar of
3791 Right var -> return var
3792 Left err -> if isDoesNotExistError err then mzero
3793 else liftMaybeT $ throwIO err
3794
3795 defaultEnvName :: String
3796 defaultEnvName = "default"
3797
3798 localEnvFile :: FilePath
3799 localEnvFile = "./.ghc.environment"
3800
3801 -- Error reporting
3802
3803 cmdLineError :: String -> MaybeT IO a
3804 cmdLineError env = liftMaybeT . throwGhcExceptionIO . CmdLineError $
3805 "Package environment " ++ show env ++ " not found"
3806
3807 envError :: String -> MaybeT IO a