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