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