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