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