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