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