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