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