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