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