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