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