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