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