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