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