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