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