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