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