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