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