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