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