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