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