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