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