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