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