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