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