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