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