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