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