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