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