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