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