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