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