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