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