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