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