More updates to Safe Haskell to implement new design (done!).
[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 -- | Turn off Safe Haskell inference mode (set module to unsafe)
1041 setSafeInferOff :: DynFlags -> DynFlags
1042 setSafeInferOff dflags
1043 | safeHaskell dflags == Sf_SafeInfered = dflags { safeHaskell = Sf_None }
1044 | otherwise = dflags
1045
1046 -- | Test if Safe Imports are on in some form
1047 safeImportsOn :: DynFlags -> Bool
1048 safeImportsOn dflags = safeHaskell dflags == Sf_Unsafe ||
1049 safeHaskell dflags == Sf_Trustworthy ||
1050 safeHaskell dflags == Sf_Safe
1051
1052 -- | Set a 'Safe Haskell' flag
1053 setSafeHaskell :: SafeHaskellMode -> DynP ()
1054 setSafeHaskell s = updM f
1055 where f dfs = do
1056 let sf = safeHaskell dfs
1057 safeM <- combineSafeFlags sf s
1058 return $ dfs { safeHaskell = safeM }
1059
1060 -- | Are all direct imports required to be safe for this Safe Haskell mode?
1061 -- Direct imports are when the code explicitly imports a module
1062 safeDirectImpsReq :: DynFlags -> Bool
1063 safeDirectImpsReq d = safeLanguageOn d || safeInferOn d
1064
1065 -- | Are all implicit imports required to be safe for this Safe Haskell mode?
1066 -- Implicit imports are things in the prelude. e.g System.IO when print is used.
1067 safeImplicitImpsReq :: DynFlags -> Bool
1068 safeImplicitImpsReq d = safeLanguageOn d || safeInferOn d
1069
1070 -- | Combine two Safe Haskell modes correctly. Used for dealing with multiple flags.
1071 -- This makes Safe Haskell very much a monoid but for now I prefer this as I don't
1072 -- want to export this functionality from the module but do want to export the
1073 -- type constructors.
1074 combineSafeFlags :: SafeHaskellMode -> SafeHaskellMode -> DynP SafeHaskellMode
1075 combineSafeFlags a b | a `elem` [Sf_None, Sf_SafeInfered] = return b
1076 | b `elem` [Sf_None, Sf_SafeInfered] = return a
1077 | a == b = return a
1078 | otherwise = addErr errm >> return (panic errm)
1079 where errm = "Incompatible Safe Haskell flags! ("
1080 ++ showPpr a ++ ", " ++ showPpr b ++ ")"
1081
1082 -- | Retrieve the options corresponding to a particular @opt_*@ field in the correct order
1083 getOpts :: DynFlags -- ^ 'DynFlags' to retrieve the options from
1084 -> (DynFlags -> [a]) -- ^ Relevant record accessor: one of the @opt_*@ accessors
1085 -> [a] -- ^ Correctly ordered extracted options
1086 getOpts dflags opts = reverse (opts dflags)
1087 -- We add to the options from the front, so we need to reverse the list
1088
1089 -- | Gets the verbosity flag for the current verbosity level. This is fed to
1090 -- other tools, so GHC-specific verbosity flags like @-ddump-most@ are not included
1091 getVerbFlags :: DynFlags -> [String]
1092 getVerbFlags dflags
1093 | verbosity dflags >= 4 = ["-v"]
1094 | otherwise = []
1095
1096 setObjectDir, setHiDir, setStubDir, setOutputDir, setDylibInstallName,
1097 setObjectSuf, setHiSuf, setHcSuf, parseDynLibLoaderMode,
1098 setPgmP, addOptl, addOptP,
1099 addCmdlineFramework, addHaddockOpts
1100 :: String -> DynFlags -> DynFlags
1101 setOutputFile, setOutputHi, setDumpPrefixForce
1102 :: Maybe String -> DynFlags -> DynFlags
1103
1104 setObjectDir f d = d{ objectDir = Just f}
1105 setHiDir f d = d{ hiDir = Just f}
1106 setStubDir f d = d{ stubDir = Just f, includePaths = f : includePaths d }
1107 -- -stubdir D adds an implicit -I D, so that gcc can find the _stub.h file
1108 -- \#included from the .hc file when compiling via C (i.e. unregisterised
1109 -- builds).
1110 setOutputDir f = setObjectDir f . setHiDir f . setStubDir f
1111 setDylibInstallName f d = d{ dylibInstallName = Just f}
1112
1113 setObjectSuf f d = d{ objectSuf = f}
1114 setHiSuf f d = d{ hiSuf = f}
1115 setHcSuf f d = d{ hcSuf = f}
1116
1117 setOutputFile f d = d{ outputFile = f}
1118 setOutputHi f d = d{ outputHi = f}
1119
1120 addPluginModuleName :: String -> DynFlags -> DynFlags
1121 addPluginModuleName name d = d { pluginModNames = (mkModuleName name) : (pluginModNames d) }
1122
1123 addPluginModuleNameOption :: String -> DynFlags -> DynFlags
1124 addPluginModuleNameOption optflag d = d { pluginModNameOpts = (mkModuleName m, option) : (pluginModNameOpts d) }
1125 where (m, rest) = break (== ':') optflag
1126 option = case rest of
1127 [] -> "" -- should probably signal an error
1128 (_:plug_opt) -> plug_opt -- ignore the ':' from break
1129
1130 parseDynLibLoaderMode f d =
1131 case splitAt 8 f of
1132 ("deploy", "") -> d{ dynLibLoader = Deployable }
1133 ("sysdep", "") -> d{ dynLibLoader = SystemDependent }
1134 _ -> ghcError (CmdLineError ("Unknown dynlib loader: " ++ f))
1135
1136 setDumpPrefixForce f d = d { dumpPrefixForce = f}
1137
1138 -- XXX HACK: Prelude> words "'does not' work" ===> ["'does","not'","work"]
1139 -- Config.hs should really use Option.
1140 setPgmP f = let (pgm:args) = words f in alterSettings (\s -> s { sPgm_P = (pgm, map Option args)})
1141 addOptl f = alterSettings (\s -> s { sOpt_l = f : sOpt_l s})
1142 addOptP f = alterSettings (\s -> s { sOpt_P = f : sOpt_P s})
1143
1144
1145 setDepMakefile :: FilePath -> DynFlags -> DynFlags
1146 setDepMakefile f d = d { depMakefile = deOptDep f }
1147
1148 setDepIncludePkgDeps :: Bool -> DynFlags -> DynFlags
1149 setDepIncludePkgDeps b d = d { depIncludePkgDeps = b }
1150
1151 addDepExcludeMod :: String -> DynFlags -> DynFlags
1152 addDepExcludeMod m d
1153 = d { depExcludeMods = mkModuleName (deOptDep m) : depExcludeMods d }
1154
1155 addDepSuffix :: FilePath -> DynFlags -> DynFlags
1156 addDepSuffix s d = d { depSuffixes = deOptDep s : depSuffixes d }
1157
1158 -- XXX Legacy code:
1159 -- We used to use "-optdep-flag -optdeparg", so for legacy applications
1160 -- we need to strip the "-optdep" off of the arg
1161 deOptDep :: String -> String
1162 deOptDep x = case stripPrefix "-optdep" x of
1163 Just rest -> rest
1164 Nothing -> x
1165
1166 addCmdlineFramework f d = d{ cmdlineFrameworks = f : cmdlineFrameworks d}
1167
1168 addHaddockOpts f d = d{ haddockOptions = Just f}
1169
1170 -- -----------------------------------------------------------------------------
1171 -- Command-line options
1172
1173 -- | When invoking external tools as part of the compilation pipeline, we
1174 -- pass these a sequence of options on the command-line. Rather than
1175 -- just using a list of Strings, we use a type that allows us to distinguish
1176 -- between filepaths and 'other stuff'. The reason for this is that
1177 -- this type gives us a handle on transforming filenames, and filenames only,
1178 -- to whatever format they're expected to be on a particular platform.
1179 data Option
1180 = FileOption -- an entry that _contains_ filename(s) / filepaths.
1181 String -- a non-filepath prefix that shouldn't be
1182 -- transformed (e.g., "/out=")
1183 String -- the filepath/filename portion
1184 | Option String
1185 deriving ( Eq )
1186
1187 showOpt :: Option -> String
1188 showOpt (FileOption pre f) = pre ++ f
1189 showOpt (Option s) = s
1190
1191 -----------------------------------------------------------------------------
1192 -- Setting the optimisation level
1193
1194 updOptLevel :: Int -> DynFlags -> DynFlags
1195 -- ^ Sets the 'DynFlags' to be appropriate to the optimisation level
1196 updOptLevel n dfs
1197 = dfs2{ optLevel = final_n }
1198 where
1199 final_n = max 0 (min 2 n) -- Clamp to 0 <= n <= 2
1200 dfs1 = foldr (flip dopt_unset) dfs remove_dopts
1201 dfs2 = foldr (flip dopt_set) dfs1 extra_dopts
1202
1203 extra_dopts = [ f | (ns,f) <- optLevelFlags, final_n `elem` ns ]
1204 remove_dopts = [ f | (ns,f) <- optLevelFlags, final_n `notElem` ns ]
1205
1206 -- -----------------------------------------------------------------------------
1207 -- StgToDo: abstraction of stg-to-stg passes to run.
1208
1209 data StgToDo
1210 = StgDoMassageForProfiling -- should be (next to) last
1211 -- There's also setStgVarInfo, but its absolute "lastness"
1212 -- is so critical that it is hardwired in (no flag).
1213 | D_stg_stats
1214
1215 getStgToDo :: DynFlags -> [StgToDo]
1216 getStgToDo dflags
1217 = todo2
1218 where
1219 stg_stats = dopt Opt_StgStats dflags
1220
1221 todo1 = if stg_stats then [D_stg_stats] else []
1222
1223 todo2 | WayProf `elem` wayNames dflags
1224 = StgDoMassageForProfiling : todo1
1225 | otherwise
1226 = todo1
1227
1228 {- **********************************************************************
1229 %* *
1230 DynFlags parser
1231 %* *
1232 %********************************************************************* -}
1233
1234 -- -----------------------------------------------------------------------------
1235 -- Parsing the dynamic flags.
1236
1237 -- | Parse dynamic flags from a list of command line arguments. Returns the
1238 -- the parsed 'DynFlags', the left-over arguments, and a list of warnings.
1239 -- Throws a 'UsageError' if errors occurred during parsing (such as unknown
1240 -- flags or missing arguments).
1241 parseDynamicFlagsCmdLine :: Monad m =>
1242 DynFlags -> [Located String]
1243 -> m (DynFlags, [Located String], [Located String])
1244 -- ^ Updated 'DynFlags', left-over arguments, and
1245 -- list of warnings.
1246 parseDynamicFlagsCmdLine dflags args = parseDynamicFlags dflags args True
1247
1248 -- | Like 'parseDynamicFlagsCmdLine' but does not allow the package flags
1249 -- (-package, -hide-package, -ignore-package, -hide-all-packages, -package-conf).
1250 -- Used to parse flags set in a modules pragma.
1251 parseDynamicFilePragma :: Monad m =>
1252 DynFlags -> [Located String]
1253 -> m (DynFlags, [Located String], [Located String])
1254 -- ^ Updated 'DynFlags', left-over arguments, and
1255 -- list of warnings.
1256 parseDynamicFilePragma dflags args = parseDynamicFlags dflags args False
1257
1258 parseDynamicFlags :: Monad m =>
1259 DynFlags -> [Located String] -> Bool
1260 -> m (DynFlags, [Located String], [Located String])
1261 parseDynamicFlags dflags0 args cmdline = do
1262 -- XXX Legacy support code
1263 -- We used to accept things like
1264 -- optdep-f -optdepdepend
1265 -- optdep-f -optdep depend
1266 -- optdep -f -optdepdepend
1267 -- optdep -f -optdep depend
1268 -- but the spaces trip up proper argument handling. So get rid of them.
1269 let f (L p "-optdep" : L _ x : xs) = (L p ("-optdep" ++ x)) : f xs
1270 f (x : xs) = x : f xs
1271 f xs = xs
1272 args' = f args
1273
1274 -- Note: -ignore-package (package_flags) must precede -i* (dynamic_flags)
1275 flag_spec | cmdline = package_flags ++ dynamic_flags
1276 | otherwise = dynamic_flags
1277
1278 let ((leftover, errs, warns), dflags1)
1279 = runCmdLine (processArgs flag_spec args') dflags0
1280 when (not (null errs)) $ ghcError $ errorsToGhcException errs
1281
1282 -- check for disabled flags in safe haskell
1283 let (dflags2, sh_warns) = safeFlagCheck dflags1
1284
1285 return (dflags2, leftover, sh_warns ++ warns)
1286
1287 -- | Check (and potentially disable) any extensions that aren't allowed
1288 -- in safe mode.
1289 safeFlagCheck :: DynFlags -> (DynFlags, [Located String])
1290 safeFlagCheck dflags | not (safeLanguageOn dflags || safeInferOn dflags)
1291 = (dflags, [])
1292 safeFlagCheck dflags =
1293 case safeLanguageOn dflags of
1294 True -> (dflags', warns)
1295
1296 False | null warns && safeInfOk
1297 -> (dflags', [])
1298
1299 | otherwise
1300 -> (dflags' { safeHaskell = Sf_None }, [])
1301 -- Have we infered Unsafe?
1302 -- See Note [HscMain . Safe Haskell Inference]
1303 where
1304 -- TODO: Can we do better than this for inference?
1305 safeInfOk = not $ xopt Opt_OverlappingInstances dflags
1306
1307 (dflags', warns) = foldl check_method (dflags, []) bad_flags
1308
1309 check_method (df, warns) (str,loc,test,fix)
1310 | test df = (apFix fix df, warns ++ safeFailure loc str)
1311 | otherwise = (df, warns)
1312
1313 apFix f = if safeInferOn dflags then id else f
1314
1315 safeFailure loc str = [L loc $ "Warning: " ++ str ++ " is not allowed in"
1316 ++ " Safe Haskell; ignoring " ++ str]
1317
1318 bad_flags = [("-XGeneralizedNewtypeDeriving", newDerivOnLoc dflags,
1319 xopt Opt_GeneralizedNewtypeDeriving,
1320 flip xopt_unset Opt_GeneralizedNewtypeDeriving),
1321 ("-XTemplateHaskell", thOnLoc dflags,
1322 xopt Opt_TemplateHaskell,
1323 flip xopt_unset Opt_TemplateHaskell)]
1324
1325
1326 {- **********************************************************************
1327 %* *
1328 DynFlags specifications
1329 %* *
1330 %********************************************************************* -}
1331
1332 allFlags :: [String]
1333 allFlags = map ('-':) $
1334 [ flagName flag | flag <- dynamic_flags, ok (flagOptKind flag) ] ++
1335 map ("fno-"++) fflags ++
1336 map ("f"++) fflags ++
1337 map ("X"++) supportedExtensions
1338 where ok (PrefixPred _ _) = False
1339 ok _ = True
1340 fflags = fflags0 ++ fflags1 ++ fflags2
1341 fflags0 = [ name | (name, _, _) <- fFlags ]
1342 fflags1 = [ name | (name, _, _) <- fWarningFlags ]
1343 fflags2 = [ name | (name, _, _) <- fLangFlags ]
1344
1345 --------------- The main flags themselves ------------------
1346 dynamic_flags :: [Flag (CmdLineP DynFlags)]
1347 dynamic_flags = [
1348 Flag "n" (NoArg (addWarn "The -n flag is deprecated and no longer has any effect"))
1349 , Flag "cpp" (NoArg (setExtensionFlag Opt_Cpp))
1350 , Flag "F" (NoArg (setDynFlag Opt_Pp))
1351 , Flag "#include"
1352 (HasArg (\s -> do addCmdlineHCInclude s
1353 addWarn "-#include and INCLUDE pragmas are deprecated: They no longer have any effect"))
1354 , Flag "v" (OptIntSuffix setVerbosity)
1355
1356 ------- Specific phases --------------------------------------------
1357 -- need to appear before -pgmL to be parsed as LLVM flags.
1358 , Flag "pgmlo" (hasArg (\f -> alterSettings (\s -> s { sPgm_lo = (f,[])})))
1359 , Flag "pgmlc" (hasArg (\f -> alterSettings (\s -> s { sPgm_lc = (f,[])})))
1360 , Flag "pgmL" (hasArg (\f -> alterSettings (\s -> s { sPgm_L = f})))
1361 , Flag "pgmP" (hasArg setPgmP)
1362 , Flag "pgmF" (hasArg (\f -> alterSettings (\s -> s { sPgm_F = f})))
1363 , Flag "pgmc" (hasArg (\f -> alterSettings (\s -> s { sPgm_c = (f,[])})))
1364 , Flag "pgmm" (HasArg (\_ -> addWarn "The -pgmm flag does nothing; it will be removed in a future GHC release"))
1365 , Flag "pgms" (hasArg (\f -> alterSettings (\s -> s { sPgm_s = (f,[])})))
1366 , Flag "pgma" (hasArg (\f -> alterSettings (\s -> s { sPgm_a = (f,[])})))
1367 , Flag "pgml" (hasArg (\f -> alterSettings (\s -> s { sPgm_l = (f,[])})))
1368 , Flag "pgmdll" (hasArg (\f -> alterSettings (\s -> s { sPgm_dll = (f,[])})))
1369 , Flag "pgmwindres" (hasArg (\f -> alterSettings (\s -> s { sPgm_windres = f})))
1370
1371 -- need to appear before -optl/-opta to be parsed as LLVM flags.
1372 , Flag "optlo" (hasArg (\f -> alterSettings (\s -> s { sOpt_lo = f : sOpt_lo s})))
1373 , Flag "optlc" (hasArg (\f -> alterSettings (\s -> s { sOpt_lc = f : sOpt_lc s})))
1374 , Flag "optL" (hasArg (\f -> alterSettings (\s -> s { sOpt_L = f : sOpt_L s})))
1375 , Flag "optP" (hasArg addOptP)
1376 , Flag "optF" (hasArg (\f -> alterSettings (\s -> s { sOpt_F = f : sOpt_F s})))
1377 , Flag "optc" (hasArg (\f -> alterSettings (\s -> s { sOpt_c = f : sOpt_c s})))
1378 , Flag "optm" (HasArg (\_ -> addWarn "The -optm flag does nothing; it will be removed in a future GHC release"))
1379 , Flag "opta" (hasArg (\f -> alterSettings (\s -> s { sOpt_a = f : sOpt_a s})))
1380 , Flag "optl" (hasArg addOptl)
1381 , Flag "optwindres" (hasArg (\f -> alterSettings (\s -> s { sOpt_windres = f : sOpt_windres s})))
1382
1383 , Flag "split-objs"
1384 (NoArg (if can_split
1385 then setDynFlag Opt_SplitObjs
1386 else addWarn "ignoring -fsplit-objs"))
1387
1388 -------- ghc -M -----------------------------------------------------
1389 , Flag "dep-suffix" (hasArg addDepSuffix)
1390 , Flag "optdep-s" (hasArgDF addDepSuffix "Use -dep-suffix instead")
1391 , Flag "dep-makefile" (hasArg setDepMakefile)
1392 , Flag "optdep-f" (hasArgDF setDepMakefile "Use -dep-makefile instead")
1393 , Flag "optdep-w" (NoArg (deprecate "doesn't do anything"))
1394 , Flag "include-pkg-deps" (noArg (setDepIncludePkgDeps True))
1395 , Flag "optdep--include-prelude" (noArgDF (setDepIncludePkgDeps True) "Use -include-pkg-deps instead")
1396 , Flag "optdep--include-pkg-deps" (noArgDF (setDepIncludePkgDeps True) "Use -include-pkg-deps instead")
1397 , Flag "exclude-module" (hasArg addDepExcludeMod)
1398 , Flag "optdep--exclude-module" (hasArgDF addDepExcludeMod "Use -exclude-module instead")
1399 , Flag "optdep-x" (hasArgDF addDepExcludeMod "Use -exclude-module instead")
1400
1401 -------- Linking ----------------------------------------------------
1402 , Flag "no-link" (noArg (\d -> d{ ghcLink=NoLink }))
1403 , Flag "shared" (noArg (\d -> d{ ghcLink=LinkDynLib }))
1404 , Flag "dynload" (hasArg parseDynLibLoaderMode)
1405 , Flag "dylib-install-name" (hasArg setDylibInstallName)
1406
1407 ------- Libraries ---------------------------------------------------
1408 , Flag "L" (Prefix addLibraryPath)
1409 , Flag "l" (hasArg (addOptl . ("-l" ++)))
1410
1411 ------- Frameworks --------------------------------------------------
1412 -- -framework-path should really be -F ...
1413 , Flag "framework-path" (HasArg addFrameworkPath)
1414 , Flag "framework" (hasArg addCmdlineFramework)
1415
1416 ------- Output Redirection ------------------------------------------
1417 , Flag "odir" (hasArg setObjectDir)
1418 , Flag "o" (sepArg (setOutputFile . Just))
1419 , Flag "ohi" (hasArg (setOutputHi . Just ))
1420 , Flag "osuf" (hasArg setObjectSuf)
1421 , Flag "hcsuf" (hasArg setHcSuf)
1422 , Flag "hisuf" (hasArg setHiSuf)
1423 , Flag "hidir" (hasArg setHiDir)
1424 , Flag "tmpdir" (hasArg setTmpDir)
1425 , Flag "stubdir" (hasArg setStubDir)
1426 , Flag "outputdir" (hasArg setOutputDir)
1427 , Flag "ddump-file-prefix" (hasArg (setDumpPrefixForce . Just))
1428
1429 ------- Keeping temporary files -------------------------------------
1430 -- These can be singular (think ghc -c) or plural (think ghc --make)
1431 , Flag "keep-hc-file" (NoArg (setDynFlag Opt_KeepHcFiles))
1432 , Flag "keep-hc-files" (NoArg (setDynFlag Opt_KeepHcFiles))
1433 , Flag "keep-s-file" (NoArg (setDynFlag Opt_KeepSFiles))
1434 , Flag "keep-s-files" (NoArg (setDynFlag Opt_KeepSFiles))
1435 , Flag "keep-raw-s-file" (NoArg (addWarn "The -keep-raw-s-file flag does nothing; it will be removed in a future GHC release"))
1436 , Flag "keep-raw-s-files" (NoArg (addWarn "The -keep-raw-s-files flag does nothing; it will be removed in a future GHC release"))
1437 , Flag "keep-llvm-file" (NoArg (setDynFlag Opt_KeepLlvmFiles))
1438 , Flag "keep-llvm-files" (NoArg (setDynFlag Opt_KeepLlvmFiles))
1439 -- This only makes sense as plural
1440 , Flag "keep-tmp-files" (NoArg (setDynFlag Opt_KeepTmpFiles))
1441
1442 ------- Miscellaneous ----------------------------------------------
1443 , Flag "no-auto-link-packages" (NoArg (unSetDynFlag Opt_AutoLinkPackages))
1444 , Flag "no-hs-main" (NoArg (setDynFlag Opt_NoHsMain))
1445 , Flag "with-rtsopts" (HasArg setRtsOpts)
1446 , Flag "rtsopts" (NoArg (setRtsOptsEnabled RtsOptsAll))
1447 , Flag "rtsopts=all" (NoArg (setRtsOptsEnabled RtsOptsAll))
1448 , Flag "rtsopts=some" (NoArg (setRtsOptsEnabled RtsOptsSafeOnly))
1449 , Flag "rtsopts=none" (NoArg (setRtsOptsEnabled RtsOptsNone))
1450 , Flag "no-rtsopts" (NoArg (setRtsOptsEnabled RtsOptsNone))
1451 , Flag "main-is" (SepArg setMainIs)
1452 , Flag "haddock" (NoArg (setDynFlag Opt_Haddock))
1453 , Flag "haddock-opts" (hasArg addHaddockOpts)
1454 , Flag "hpcdir" (SepArg setOptHpcDir)
1455
1456 ------- recompilation checker --------------------------------------
1457 , Flag "recomp" (NoArg (do unSetDynFlag Opt_ForceRecomp
1458 deprecate "Use -fno-force-recomp instead"))
1459 , Flag "no-recomp" (NoArg (do setDynFlag Opt_ForceRecomp
1460 deprecate "Use -fforce-recomp instead"))
1461
1462 ------ HsCpp opts ---------------------------------------------------
1463 , Flag "D" (AnySuffix (upd . addOptP))
1464 , Flag "U" (AnySuffix (upd . addOptP))
1465
1466 ------- Include/Import Paths ----------------------------------------
1467 , Flag "I" (Prefix addIncludePath)
1468 , Flag "i" (OptPrefix addImportPath)
1469
1470 ------ Debugging ----------------------------------------------------
1471 , Flag "dstg-stats" (NoArg (setDynFlag Opt_StgStats))
1472
1473 , Flag "ddump-cmm" (setDumpFlag Opt_D_dump_cmm)
1474 , Flag "ddump-raw-cmm" (setDumpFlag Opt_D_dump_raw_cmm)
1475 , Flag "ddump-cmmz" (setDumpFlag Opt_D_dump_cmmz)
1476 , Flag "ddump-cmmz-pretty" (setDumpFlag Opt_D_dump_cmmz_pretty)
1477 , Flag "ddump-cmmz-cbe" (setDumpFlag Opt_D_dump_cmmz_cbe)
1478 , Flag "ddump-cmmz-spills" (setDumpFlag Opt_D_dump_cmmz_spills)
1479 , Flag "ddump-cmmz-proc" (setDumpFlag Opt_D_dump_cmmz_proc)
1480 , Flag "ddump-cmmz-rewrite" (setDumpFlag Opt_D_dump_cmmz_rewrite)
1481 , Flag "ddump-cmmz-dead" (setDumpFlag Opt_D_dump_cmmz_dead)
1482 , Flag "ddump-cmmz-stub" (setDumpFlag Opt_D_dump_cmmz_stub)
1483 , Flag "ddump-cmmz-sp" (setDumpFlag Opt_D_dump_cmmz_sp)
1484 , Flag "ddump-cmmz-procmap" (setDumpFlag Opt_D_dump_cmmz_procmap)
1485 , Flag "ddump-cmmz-split" (setDumpFlag Opt_D_dump_cmmz_split)
1486 , Flag "ddump-cmmz-lower" (setDumpFlag Opt_D_dump_cmmz_lower)
1487 , Flag "ddump-cmmz-info" (setDumpFlag Opt_D_dump_cmmz_info)
1488 , Flag "ddump-cmmz-cafs" (setDumpFlag Opt_D_dump_cmmz_cafs)
1489 , Flag "ddump-core-stats" (setDumpFlag Opt_D_dump_core_stats)
1490 , Flag "ddump-cps-cmm" (setDumpFlag Opt_D_dump_cps_cmm)
1491 , Flag "ddump-cvt-cmm" (setDumpFlag Opt_D_dump_cvt_cmm)
1492 , Flag "ddump-asm" (setDumpFlag Opt_D_dump_asm)
1493 , Flag "ddump-asm-native" (setDumpFlag Opt_D_dump_asm_native)
1494 , Flag "ddump-asm-liveness" (setDumpFlag Opt_D_dump_asm_liveness)
1495 , Flag "ddump-asm-coalesce" (setDumpFlag Opt_D_dump_asm_coalesce)
1496 , Flag "ddump-asm-regalloc" (setDumpFlag Opt_D_dump_asm_regalloc)
1497 , Flag "ddump-asm-conflicts" (setDumpFlag Opt_D_dump_asm_conflicts)
1498 , Flag "ddump-asm-regalloc-stages" (setDumpFlag Opt_D_dump_asm_regalloc_stages)
1499 , Flag "ddump-asm-stats" (setDumpFlag Opt_D_dump_asm_stats)
1500 , Flag "ddump-asm-expanded" (setDumpFlag Opt_D_dump_asm_expanded)
1501 , Flag "ddump-llvm" (NoArg (do setObjTarget HscLlvm
1502 setDumpFlag' Opt_D_dump_llvm))
1503 , Flag "ddump-cpranal" (setDumpFlag Opt_D_dump_cpranal)
1504 , Flag "ddump-deriv" (setDumpFlag Opt_D_dump_deriv)
1505 , Flag "ddump-ds" (setDumpFlag Opt_D_dump_ds)
1506 , Flag "ddump-flatC" (setDumpFlag Opt_D_dump_flatC)
1507 , Flag "ddump-foreign" (setDumpFlag Opt_D_dump_foreign)
1508 , Flag "ddump-inlinings" (setDumpFlag Opt_D_dump_inlinings)
1509 , Flag "ddump-rule-firings" (setDumpFlag Opt_D_dump_rule_firings)
1510 , Flag "ddump-rule-rewrites" (setDumpFlag Opt_D_dump_rule_rewrites)
1511 , Flag "ddump-occur-anal" (setDumpFlag Opt_D_dump_occur_anal)
1512 , Flag "ddump-parsed" (setDumpFlag Opt_D_dump_parsed)
1513 , Flag "ddump-rn" (setDumpFlag Opt_D_dump_rn)
1514 , Flag "ddump-core-pipeline" (setDumpFlag Opt_D_dump_core_pipeline)
1515 , Flag "ddump-simpl" (setDumpFlag Opt_D_dump_simpl)
1516 , Flag "ddump-simpl-iterations" (setDumpFlag Opt_D_dump_simpl_iterations)
1517 , Flag "ddump-simpl-phases" (OptPrefix setDumpSimplPhases)
1518 , Flag "ddump-spec" (setDumpFlag Opt_D_dump_spec)
1519 , Flag "ddump-prep" (setDumpFlag Opt_D_dump_prep)
1520 , Flag "ddump-stg" (setDumpFlag Opt_D_dump_stg)
1521 , Flag "ddump-stranal" (setDumpFlag Opt_D_dump_stranal)
1522 , Flag "ddump-tc" (setDumpFlag Opt_D_dump_tc)
1523 , Flag "ddump-types" (setDumpFlag Opt_D_dump_types)
1524 , Flag "ddump-rules" (setDumpFlag Opt_D_dump_rules)
1525 , Flag "ddump-cse" (setDumpFlag Opt_D_dump_cse)
1526 , Flag "ddump-worker-wrapper" (setDumpFlag Opt_D_dump_worker_wrapper)
1527 , Flag "ddump-rn-trace" (setDumpFlag Opt_D_dump_rn_trace)
1528 , Flag "ddump-if-trace" (setDumpFlag Opt_D_dump_if_trace)
1529 , Flag "ddump-cs-trace" (setDumpFlag Opt_D_dump_cs_trace)
1530 , Flag "ddump-tc-trace" (setDumpFlag Opt_D_dump_tc_trace)
1531 , Flag "ddump-vt-trace" (setDumpFlag Opt_D_dump_vt_trace)
1532 , Flag "ddump-splices" (setDumpFlag Opt_D_dump_splices)
1533 , Flag "ddump-rn-stats" (setDumpFlag Opt_D_dump_rn_stats)
1534 , Flag "ddump-opt-cmm" (setDumpFlag Opt_D_dump_opt_cmm)
1535 , Flag "ddump-simpl-stats" (setDumpFlag Opt_D_dump_simpl_stats)
1536 , Flag "ddump-bcos" (setDumpFlag Opt_D_dump_BCOs)
1537 , Flag "dsource-stats" (setDumpFlag Opt_D_source_stats)
1538 , Flag "dverbose-core2core" (NoArg (do setVerbosity (Just 2)
1539 setVerboseCore2Core))
1540 , Flag "dverbose-stg2stg" (setDumpFlag Opt_D_verbose_stg2stg)
1541 , Flag "ddump-hi" (setDumpFlag Opt_D_dump_hi)
1542 , Flag "ddump-minimal-imports" (setDumpFlag Opt_D_dump_minimal_imports)
1543 , Flag "ddump-vect" (setDumpFlag Opt_D_dump_vect)
1544 , Flag "ddump-hpc" (setDumpFlag Opt_D_dump_hpc)
1545 , Flag "ddump-mod-cycles" (setDumpFlag Opt_D_dump_mod_cycles)
1546 , Flag "ddump-view-pattern-commoning" (setDumpFlag Opt_D_dump_view_pattern_commoning)
1547 , Flag "ddump-to-file" (setDumpFlag Opt_DumpToFile)
1548 , Flag "ddump-hi-diffs" (setDumpFlag Opt_D_dump_hi_diffs)
1549 , Flag "ddump-rtti" (setDumpFlag Opt_D_dump_rtti)
1550 , Flag "dcore-lint" (NoArg (setDynFlag Opt_DoCoreLinting))
1551 , Flag "dstg-lint" (NoArg (setDynFlag Opt_DoStgLinting))
1552 , Flag "dcmm-lint" (NoArg (setDynFlag Opt_DoCmmLinting))
1553 , Flag "dasm-lint" (NoArg (setDynFlag Opt_DoAsmLinting))
1554 , Flag "dshow-passes" (NoArg (do forceRecompile
1555 setVerbosity $ Just 2))
1556 , Flag "dfaststring-stats" (NoArg (setDynFlag Opt_D_faststring_stats))
1557
1558 ------ Machine dependant (-m<blah>) stuff ---------------------------
1559
1560 , Flag "monly-2-regs" (NoArg (addWarn "The -monly-2-regs flag does nothing; it will be removed in a future GHC release"))
1561 , Flag "monly-3-regs" (NoArg (addWarn "The -monly-3-regs flag does nothing; it will be removed in a future GHC release"))
1562 , Flag "monly-4-regs" (NoArg (addWarn "The -monly-4-regs flag does nothing; it will be removed in a future GHC release"))
1563 , Flag "msse2" (NoArg (setDynFlag Opt_SSE2))
1564 , Flag "msse4.2" (NoArg (setDynFlag Opt_SSE4_2))
1565
1566 ------ Warning opts -------------------------------------------------
1567 , Flag "W" (NoArg (mapM_ setWarningFlag minusWOpts))
1568 , Flag "Werror" (NoArg (setDynFlag Opt_WarnIsError))
1569 , Flag "Wwarn" (NoArg (unSetDynFlag Opt_WarnIsError))
1570 , Flag "Wall" (NoArg (mapM_ setWarningFlag minusWallOpts))
1571 , Flag "Wnot" (NoArg (do upd (\dfs -> dfs {warningFlags = []})
1572 deprecate "Use -w instead"))
1573 , Flag "w" (NoArg (upd (\dfs -> dfs {warningFlags = []})))
1574
1575 ------ Plugin flags ------------------------------------------------
1576 , Flag "fplugin-opt" (hasArg addPluginModuleNameOption)
1577 , Flag "fplugin" (hasArg addPluginModuleName)
1578
1579 ------ Optimisation flags ------------------------------------------
1580 , Flag "O" (noArgM (setOptLevel 1))
1581 , Flag "Onot" (noArgM (\dflags -> do deprecate "Use -O0 instead"
1582 setOptLevel 0 dflags))
1583 , Flag "Odph" (noArgM setDPHOpt)
1584 , Flag "O" (optIntSuffixM (\mb_n -> setOptLevel (mb_n `orElse` 1)))
1585 -- If the number is missing, use 1
1586
1587 , Flag "fsimplifier-phases" (intSuffix (\n d -> d{ simplPhases = n }))
1588 , Flag "fmax-simplifier-iterations" (intSuffix (\n d -> d{ maxSimplIterations = n }))
1589 , Flag "fsimpl-tick-factor" (intSuffix (\n d -> d{ simplTickFactor = n }))
1590 , Flag "fspec-constr-threshold" (intSuffix (\n d -> d{ specConstrThreshold = Just n }))
1591 , Flag "fno-spec-constr-threshold" (noArg (\d -> d{ specConstrThreshold = Nothing }))
1592 , Flag "fspec-constr-count" (intSuffix (\n d -> d{ specConstrCount = Just n }))
1593 , Flag "fno-spec-constr-count" (noArg (\d -> d{ specConstrCount = Nothing }))
1594 , Flag "fliberate-case-threshold" (intSuffix (\n d -> d{ liberateCaseThreshold = Just n }))
1595 , Flag "fno-liberate-case-threshold" (noArg (\d -> d{ liberateCaseThreshold = Nothing }))
1596 , Flag "frule-check" (sepArg (\s d -> d{ ruleCheck = Just s }))
1597 , Flag "fcontext-stack" (intSuffix (\n d -> d{ ctxtStkDepth = n }))
1598 , Flag "fstrictness-before" (intSuffix (\n d -> d{ strictnessBefore = n : strictnessBefore d }))
1599 , Flag "ffloat-lam-args" (intSuffix (\n d -> d{ floatLamArgs = Just n }))
1600 , Flag "ffloat-all-lams" (noArg (\d -> d{ floatLamArgs = Nothing }))
1601
1602 ------ Profiling ----------------------------------------------------
1603
1604 -- XXX Should the -f* flags be deprecated?
1605 -- They don't seem to be documented
1606 , Flag "fauto-sccs-on-all-toplevs" (NoArg (setDynFlag Opt_AutoSccsOnAllToplevs))
1607 , Flag "auto-all" (NoArg (setDynFlag Opt_AutoSccsOnAllToplevs))
1608 , Flag "no-auto-all" (NoArg (unSetDynFlag Opt_AutoSccsOnAllToplevs))
1609 , Flag "fauto-sccs-on-exported-toplevs" (NoArg (setDynFlag Opt_AutoSccsOnExportedToplevs))
1610 , Flag "auto" (NoArg (setDynFlag Opt_AutoSccsOnExportedToplevs))
1611 , Flag "no-auto" (NoArg (unSetDynFlag Opt_AutoSccsOnExportedToplevs))
1612 , Flag "fauto-sccs-on-individual-cafs" (NoArg (setDynFlag Opt_AutoSccsOnIndividualCafs))
1613 , Flag "caf-all" (NoArg (setDynFlag Opt_AutoSccsOnIndividualCafs))
1614 , Flag "no-caf-all" (NoArg (unSetDynFlag Opt_AutoSccsOnIndividualCafs))
1615
1616 ------ DPH flags ----------------------------------------------------
1617
1618 , Flag "fdph-seq" (NoArg (setDPHBackend DPHSeq))
1619 , Flag "fdph-par" (NoArg (setDPHBackend DPHPar))
1620 , Flag "fdph-this" (NoArg (setDPHBackend DPHThis))
1621 , Flag "fdph-none" (NoArg (setDPHBackend DPHNone))
1622
1623 ------ Compiler flags -----------------------------------------------
1624
1625 , Flag "fasm" (NoArg (setObjTarget HscAsm))
1626 , Flag "fvia-c" (NoArg
1627 (addWarn "The -fvia-c flag does nothing; it will be removed in a future GHC release"))
1628 , Flag "fvia-C" (NoArg
1629 (addWarn "The -fvia-C flag does nothing; it will be removed in a future GHC release"))
1630 , Flag "fllvm" (NoArg (setObjTarget HscLlvm))
1631
1632 , Flag "fno-code" (NoArg (do upd $ \d -> d{ ghcLink=NoLink }
1633 setTarget HscNothing))
1634 , Flag "fbyte-code" (NoArg (setTarget HscInterpreted))
1635 , Flag "fobject-code" (NoArg (setTarget defaultHscTarget))
1636 , Flag "fglasgow-exts" (NoArg (enableGlasgowExts >> deprecate "Use individual extensions instead"))
1637 , Flag "fno-glasgow-exts" (NoArg (disableGlasgowExts >> deprecate "Use individual extensions instead"))
1638
1639 ------ Safe Haskell flags -------------------------------------------
1640 , Flag "fpackage-trust" (NoArg (setDynFlag Opt_PackageTrust))
1641 ]
1642 ++ map (mkFlag turnOn "f" setDynFlag ) fFlags
1643 ++ map (mkFlag turnOff "fno-" unSetDynFlag) fFlags
1644 ++ map (mkFlag turnOn "f" setWarningFlag ) fWarningFlags
1645 ++ map (mkFlag turnOff "fno-" unSetWarningFlag) fWarningFlags
1646 ++ map (mkFlag turnOn "f" setExtensionFlag ) fLangFlags
1647 ++ map (mkFlag turnOff "fno-" unSetExtensionFlag) fLangFlags
1648 ++ map (mkFlag turnOn "X" setExtensionFlag ) xFlags
1649 ++ map (mkFlag turnOff "XNo" unSetExtensionFlag) xFlags
1650 ++ map (mkFlag turnOn "X" setLanguage) languageFlags
1651 ++ map (mkFlag turnOn "X" setSafeHaskell) safeHaskellFlags
1652 ++ [ Flag "XGenerics" (NoArg (deprecate "it does nothing; look into -XDefaultSignatures and -XDeriveGeneric for generic programming support."))
1653 , Flag "XNoGenerics" (NoArg (deprecate "it does nothing; look into -XDefaultSignatures and -XDeriveGeneric for generic programming support.")) ]
1654
1655 package_flags :: [Flag (CmdLineP DynFlags)]
1656 package_flags = [
1657 ------- Packages ----------------------------------------------------
1658 Flag "package-conf" (HasArg extraPkgConf_)
1659 , Flag "no-user-package-conf" (NoArg (unSetDynFlag Opt_ReadUserPackageConf))
1660 , Flag "package-name" (hasArg setPackageName)
1661 , Flag "package-id" (HasArg exposePackageId)
1662 , Flag "package" (HasArg exposePackage)
1663 , Flag "hide-package" (HasArg hidePackage)
1664 , Flag "hide-all-packages" (NoArg (setDynFlag Opt_HideAllPackages))
1665 , Flag "ignore-package" (HasArg ignorePackage)
1666 , Flag "syslib" (HasArg (\s -> do exposePackage s
1667 deprecate "Use -package instead"))
1668 , Flag "trust" (HasArg trustPackage)
1669 , Flag "distrust" (HasArg distrustPackage)
1670 , Flag "distrust-all-packages" (NoArg (setDynFlag Opt_DistrustAllPackages))
1671 ]
1672
1673 type TurnOnFlag = Bool -- True <=> we are turning the flag on
1674 -- False <=> we are turning the flag off
1675 turnOn :: TurnOnFlag; turnOn = True
1676 turnOff :: TurnOnFlag; turnOff = False
1677
1678 type FlagSpec flag
1679 = ( String -- Flag in string form
1680 , flag -- Flag in internal form
1681 , TurnOnFlag -> DynP ()) -- Extra action to run when the flag is found
1682 -- Typically, emit a warning or error
1683
1684 mkFlag :: TurnOnFlag -- ^ True <=> it should be turned on
1685 -> String -- ^ The flag prefix
1686 -> (flag -> DynP ()) -- ^ What to do when the flag is found
1687 -> FlagSpec flag -- ^ Specification of this particular flag
1688 -> Flag (CmdLineP DynFlags)
1689 mkFlag turn_on flagPrefix f (name, flag, extra_action)
1690 = Flag (flagPrefix ++ name) (NoArg (f flag >> extra_action turn_on))
1691
1692 deprecatedForExtension :: String -> TurnOnFlag -> DynP ()
1693 deprecatedForExtension lang turn_on
1694 = deprecate ("use -X" ++ flag ++ " or pragma {-# LANGUAGE " ++ flag ++ " #-} instead")
1695 where
1696 flag | turn_on = lang
1697 | otherwise = "No"++lang
1698
1699 useInstead :: String -> TurnOnFlag -> DynP ()
1700 useInstead flag turn_on
1701 = deprecate ("Use -f" ++ no ++ flag ++ " instead")
1702 where
1703 no = if turn_on then "" else "no-"
1704
1705 nop :: TurnOnFlag -> DynP ()
1706 nop _ = return ()
1707
1708 -- | These @-f\<blah\>@ flags can all be reversed with @-fno-\<blah\>@
1709 fWarningFlags :: [FlagSpec WarningFlag]
1710 fWarningFlags = [
1711 ( "warn-dodgy-foreign-imports", Opt_WarnDodgyForeignImports, nop ),
1712 ( "warn-dodgy-exports", Opt_WarnDodgyExports, nop ),
1713 ( "warn-dodgy-imports", Opt_WarnDodgyImports, nop ),
1714 ( "warn-duplicate-exports", Opt_WarnDuplicateExports, nop ),
1715 ( "warn-hi-shadowing", Opt_WarnHiShadows, nop ),
1716 ( "warn-implicit-prelude", Opt_WarnImplicitPrelude, nop ),
1717 ( "warn-incomplete-patterns", Opt_WarnIncompletePatterns, nop ),
1718 ( "warn-incomplete-uni-patterns", Opt_WarnIncompleteUniPatterns, nop ),
1719 ( "warn-incomplete-record-updates", Opt_WarnIncompletePatternsRecUpd, nop ),
1720 ( "warn-missing-fields", Opt_WarnMissingFields, nop ),
1721 ( "warn-missing-import-lists", Opt_WarnMissingImportList, nop ),
1722 ( "warn-missing-methods", Opt_WarnMissingMethods, nop ),
1723 ( "warn-missing-signatures", Opt_WarnMissingSigs, nop ),
1724 ( "warn-missing-local-sigs", Opt_WarnMissingLocalSigs, nop ),
1725 ( "warn-name-shadowing", Opt_WarnNameShadowing, nop ),
1726 ( "warn-overlapping-patterns", Opt_WarnOverlappingPatterns, nop ),
1727 ( "warn-type-defaults", Opt_WarnTypeDefaults, nop ),
1728 ( "warn-monomorphism-restriction", Opt_WarnMonomorphism, nop ),
1729 ( "warn-unused-binds", Opt_WarnUnusedBinds, nop ),
1730 ( "warn-unused-imports", Opt_WarnUnusedImports, nop ),
1731 ( "warn-unused-matches", Opt_WarnUnusedMatches, nop ),
1732 ( "warn-warnings-deprecations", Opt_WarnWarningsDeprecations, nop ),
1733 ( "warn-deprecations", Opt_WarnWarningsDeprecations, nop ),
1734 ( "warn-deprecated-flags", Opt_WarnDeprecatedFlags, nop ),
1735 ( "warn-orphans", Opt_WarnOrphans, nop ),
1736 ( "warn-identities", Opt_WarnIdentities, nop ),
1737 ( "warn-auto-orphans", Opt_WarnAutoOrphans, nop ),
1738 ( "warn-tabs", Opt_WarnTabs, nop ),
1739 ( "warn-unrecognised-pragmas", Opt_WarnUnrecognisedPragmas, nop ),
1740 ( "warn-lazy-unlifted-bindings", Opt_WarnLazyUnliftedBindings, nop),
1741 ( "warn-unused-do-bind", Opt_WarnUnusedDoBind, nop ),
1742 ( "warn-wrong-do-bind", Opt_WarnWrongDoBind, nop ),
1743 ( "warn-alternative-layout-rule-transitional", Opt_WarnAlternativeLayoutRuleTransitional, nop )]
1744
1745 -- | These @-f\<blah\>@ flags can all be reversed with @-fno-\<blah\>@
1746 fFlags :: [FlagSpec DynFlag]
1747 fFlags = [
1748 ( "print-explicit-foralls", Opt_PrintExplicitForalls, nop ),
1749 ( "strictness", Opt_Strictness, nop ),
1750 ( "specialise", Opt_Specialise, nop ),
1751 ( "float-in", Opt_FloatIn, nop ),
1752 ( "static-argument-transformation", Opt_StaticArgumentTransformation, nop ),
1753 ( "full-laziness", Opt_FullLaziness, nop ),
1754 ( "liberate-case", Opt_LiberateCase, nop ),
1755 ( "spec-constr", Opt_SpecConstr, nop ),
1756 ( "cse", Opt_CSE, nop ),
1757 ( "ignore-interface-pragmas", Opt_IgnoreInterfacePragmas, nop ),
1758 ( "omit-interface-pragmas", Opt_OmitInterfacePragmas, nop ),
1759 ( "expose-all-unfoldings", Opt_ExposeAllUnfoldings, nop ),
1760 ( "do-lambda-eta-expansion", Opt_DoLambdaEtaExpansion, nop ),
1761 ( "ignore-asserts", Opt_IgnoreAsserts, nop ),
1762 ( "do-eta-reduction", Opt_DoEtaReduction, nop ),
1763 ( "case-merge", Opt_CaseMerge, nop ),
1764 ( "unbox-strict-fields", Opt_UnboxStrictFields, nop ),
1765 ( "dicts-cheap", Opt_DictsCheap, nop ),
1766 ( "excess-precision", Opt_ExcessPrecision, nop ),
1767 ( "eager-blackholing", Opt_EagerBlackHoling, nop ),
1768 ( "print-bind-result", Opt_PrintBindResult, nop ),
1769 ( "force-recomp", Opt_ForceRecomp, nop ),
1770 ( "hpc-no-auto", Opt_Hpc_No_Auto, nop ),
1771 ( "rewrite-rules", Opt_EnableRewriteRules, useInstead "enable-rewrite-rules" ),
1772 ( "enable-rewrite-rules", Opt_EnableRewriteRules, nop ),
1773 ( "break-on-exception", Opt_BreakOnException, nop ),
1774 ( "break-on-error", Opt_BreakOnError, nop ),
1775 ( "print-evld-with-show", Opt_PrintEvldWithShow, nop ),
1776 ( "print-bind-contents", Opt_PrintBindContents, nop ),
1777 ( "run-cps", Opt_RunCPS, nop ),
1778 ( "run-cpsz", Opt_RunCPSZ, nop ),
1779 ( "new-codegen", Opt_TryNewCodeGen, nop ),
1780 ( "vectorise", Opt_Vectorise, nop ),
1781 ( "regs-graph", Opt_RegsGraph, nop ),
1782 ( "regs-iterative", Opt_RegsIterative, nop ),
1783 ( "gen-manifest", Opt_GenManifest, nop ),
1784 ( "embed-manifest", Opt_EmbedManifest, nop ),
1785 ( "ext-core", Opt_EmitExternalCore, nop ),
1786 ( "shared-implib", Opt_SharedImplib, nop ),
1787 ( "ghci-sandbox", Opt_GhciSandbox, nop ),
1788 ( "ghci-history", Opt_GhciHistory, nop ),
1789 ( "helpful-errors", Opt_HelpfulErrors, nop ),
1790 ( "building-cabal-package", Opt_BuildingCabalPackage, nop ),
1791 ( "implicit-import-qualified", Opt_ImplicitImportQualified, nop )
1792 ]
1793
1794 -- | These @-f\<blah\>@ flags can all be reversed with @-fno-\<blah\>@
1795 fLangFlags :: [FlagSpec ExtensionFlag]
1796 fLangFlags = [
1797 ( "th", Opt_TemplateHaskell,
1798 deprecatedForExtension "TemplateHaskell" >> checkTemplateHaskellOk ),
1799 ( "fi", Opt_ForeignFunctionInterface,
1800 deprecatedForExtension "ForeignFunctionInterface" ),
1801 ( "ffi", Opt_ForeignFunctionInterface,
1802 deprecatedForExtension "ForeignFunctionInterface" ),
1803 ( "arrows", Opt_Arrows,
1804 deprecatedForExtension "Arrows" ),
1805 ( "implicit-prelude", Opt_ImplicitPrelude,
1806 deprecatedForExtension "ImplicitPrelude" ),
1807 ( "bang-patterns", Opt_BangPatterns,
1808 deprecatedForExtension "BangPatterns" ),
1809 ( "monomorphism-restriction", Opt_MonomorphismRestriction,
1810 deprecatedForExtension "MonomorphismRestriction" ),
1811 ( "mono-pat-binds", Opt_MonoPatBinds,
1812 deprecatedForExtension "MonoPatBinds" ),
1813 ( "extended-default-rules", Opt_ExtendedDefaultRules,
1814 deprecatedForExtension "ExtendedDefaultRules" ),
1815 ( "implicit-params", Opt_ImplicitParams,
1816 deprecatedForExtension "ImplicitParams" ),
1817 ( "scoped-type-variables", Opt_ScopedTypeVariables,
1818 deprecatedForExtension "ScopedTypeVariables" ),
1819 ( "parr", Opt_ParallelArrays,
1820 deprecatedForExtension "ParallelArrays" ),
1821 ( "PArr", Opt_ParallelArrays,
1822 deprecatedForExtension "ParallelArrays" ),
1823 ( "allow-overlapping-instances", Opt_OverlappingInstances,
1824 deprecatedForExtension "OverlappingInstances" ),
1825 ( "allow-undecidable-instances", Opt_UndecidableInstances,
1826 deprecatedForExtension "UndecidableInstances" ),
1827 ( "allow-incoherent-instances", Opt_IncoherentInstances,
1828 deprecatedForExtension "IncoherentInstances" )
1829 ]
1830
1831 supportedLanguages :: [String]
1832 supportedLanguages = [ name | (name, _, _) <- languageFlags ]
1833
1834 supportedLanguageOverlays :: [String]
1835 supportedLanguageOverlays = [ name | (name, _, _) <- safeHaskellFlags ]
1836
1837 supportedExtensions :: [String]
1838 supportedExtensions = [ name' | (name, _, _) <- xFlags, name' <- [name, "No" ++ name] ]
1839
1840 supportedLanguagesAndExtensions :: [String]
1841 supportedLanguagesAndExtensions =
1842 supportedLanguages ++ supportedLanguageOverlays ++ supportedExtensions
1843
1844 -- | These -X<blah> flags cannot be reversed with -XNo<blah>
1845 languageFlags :: [FlagSpec Language]
1846 languageFlags = [
1847 ( "Haskell98", Haskell98, nop ),
1848 ( "Haskell2010", Haskell2010, nop )
1849 ]
1850
1851 -- | These -X<blah> flags cannot be reversed with -XNo<blah>
1852 -- They are used to place hard requirements on what GHC Haskell language
1853 -- features can be used.
1854 safeHaskellFlags :: [FlagSpec SafeHaskellMode]
1855 safeHaskellFlags = [mkF Sf_Unsafe, mkF Sf_Trustworthy, mkF Sf_Safe]
1856 where mkF flag = (showPpr flag, flag, nop)
1857
1858 -- | These -X<blah> flags can all be reversed with -XNo<blah>
1859 xFlags :: [FlagSpec ExtensionFlag]
1860 xFlags = [
1861 ( "CPP", Opt_Cpp, nop ),
1862 ( "PostfixOperators", Opt_PostfixOperators, nop ),
1863 ( "TupleSections", Opt_TupleSections, nop ),
1864 ( "PatternGuards", Opt_PatternGuards, nop ),
1865 ( "UnicodeSyntax", Opt_UnicodeSyntax, nop ),
1866 ( "MagicHash", Opt_MagicHash, nop ),
1867 ( "PolymorphicComponents", Opt_PolymorphicComponents, nop ),
1868 ( "ExistentialQuantification", Opt_ExistentialQuantification, nop ),
1869 ( "KindSignatures", Opt_KindSignatures, nop ),
1870 ( "EmptyDataDecls", Opt_EmptyDataDecls, nop ),
1871 ( "ParallelListComp", Opt_ParallelListComp, nop ),
1872 ( "TransformListComp", Opt_TransformListComp, nop ),
1873 ( "MonadComprehensions", Opt_MonadComprehensions, nop),
1874 ( "ForeignFunctionInterface", Opt_ForeignFunctionInterface, nop ),
1875 ( "UnliftedFFITypes", Opt_UnliftedFFITypes, nop ),
1876 ( "InterruptibleFFI", Opt_InterruptibleFFI, nop ),
1877 ( "GHCForeignImportPrim", Opt_GHCForeignImportPrim, nop ),
1878 ( "LiberalTypeSynonyms", Opt_LiberalTypeSynonyms, nop ),
1879 ( "Rank2Types", Opt_Rank2Types, nop ),
1880 ( "RankNTypes", Opt_RankNTypes, nop ),
1881 ( "ImpredicativeTypes", Opt_ImpredicativeTypes, nop),
1882 ( "TypeOperators", Opt_TypeOperators, nop ),
1883 ( "RecursiveDo", Opt_RecursiveDo, -- Enables 'mdo'
1884 deprecatedForExtension "DoRec"),
1885 ( "DoRec", Opt_DoRec, nop ), -- Enables 'rec' keyword
1886 ( "Arrows", Opt_Arrows, nop ),
1887 ( "ParallelArrays", Opt_ParallelArrays, nop ),
1888 ( "TemplateHaskell", Opt_TemplateHaskell, checkTemplateHaskellOk ),
1889 ( "QuasiQuotes", Opt_QuasiQuotes, nop ),
1890 ( "ImplicitPrelude", Opt_ImplicitPrelude, nop ),
1891 ( "RecordWildCards", Opt_RecordWildCards, nop ),
1892 ( "NamedFieldPuns", Opt_RecordPuns, nop ),
1893 ( "RecordPuns", Opt_RecordPuns,
1894 deprecatedForExtension "NamedFieldPuns" ),
1895 ( "DisambiguateRecordFields", Opt_DisambiguateRecordFields, nop ),
1896 ( "OverloadedStrings", Opt_OverloadedStrings, nop ),
1897 ( "GADTs", Opt_GADTs, nop ),
1898 ( "GADTSyntax", Opt_GADTSyntax, nop ),
1899 ( "ViewPatterns", Opt_ViewPatterns, nop ),
1900 ( "TypeFamilies", Opt_TypeFamilies, nop ),
1901 ( "BangPatterns", Opt_BangPatterns, nop ),
1902 ( "MonomorphismRestriction", Opt_MonomorphismRestriction, nop ),
1903 ( "NPlusKPatterns", Opt_NPlusKPatterns, nop ),
1904 ( "DoAndIfThenElse", Opt_DoAndIfThenElse, nop ),
1905 ( "RebindableSyntax", Opt_RebindableSyntax, nop ),
1906 ( "ConstraintKinds", Opt_ConstraintKinds, nop ),
1907 ( "MonoPatBinds", Opt_MonoPatBinds,
1908 \ turn_on -> when turn_on $ deprecate "Experimental feature now removed; has no effect" ),
1909 ( "ExplicitForAll", Opt_ExplicitForAll, nop ),
1910 ( "AlternativeLayoutRule", Opt_AlternativeLayoutRule, nop ),
1911 ( "AlternativeLayoutRuleTransitional",Opt_AlternativeLayoutRuleTransitional, nop ),
1912 ( "DatatypeContexts", Opt_DatatypeContexts,
1913 \ turn_on -> when turn_on $ deprecate "It was widely considered a misfeature, and has been removed from the Haskell language." ),
1914 ( "NondecreasingIndentation", Opt_NondecreasingIndentation, nop ),
1915 ( "RelaxedLayout", Opt_RelaxedLayout, nop ),
1916 ( "TraditionalRecordSyntax", Opt_TraditionalRecordSyntax, nop ),
1917 ( "MonoLocalBinds", Opt_MonoLocalBinds, nop ),
1918 ( "RelaxedPolyRec", Opt_RelaxedPolyRec,
1919 \ turn_on -> if not turn_on
1920 then deprecate "You can't turn off RelaxedPolyRec any more"
1921 else return () ),
1922 ( "ExtendedDefaultRules", Opt_ExtendedDefaultRules, nop ),
1923 ( "ImplicitParams", Opt_ImplicitParams, nop ),
1924 ( "ScopedTypeVariables", Opt_ScopedTypeVariables, nop ),
1925
1926 ( "PatternSignatures", Opt_ScopedTypeVariables,
1927 deprecatedForExtension "ScopedTypeVariables" ),
1928
1929 ( "UnboxedTuples", Opt_UnboxedTuples, nop ),
1930 ( "StandaloneDeriving", Opt_StandaloneDeriving, nop ),
1931 ( "DeriveDataTypeable", Opt_DeriveDataTypeable, nop ),
1932 ( "DeriveFunctor", Opt_DeriveFunctor, nop ),
1933 ( "DeriveTraversable", Opt_DeriveTraversable, nop ),
1934 ( "DeriveFoldable", Opt_DeriveFoldable, nop ),
1935 ( "DeriveGeneric", Opt_DeriveGeneric, nop ),
1936 ( "DefaultSignatures", Opt_DefaultSignatures, nop ),
1937 ( "TypeSynonymInstances", Opt_TypeSynonymInstances, nop ),
1938 ( "FlexibleContexts", Opt_FlexibleContexts, nop ),
1939 ( "FlexibleInstances", Opt_FlexibleInstances, nop ),
1940 ( "ConstrainedClassMethods", Opt_ConstrainedClassMethods, nop ),
1941 ( "MultiParamTypeClasses", Opt_MultiParamTypeClasses, nop ),
1942 ( "FunctionalDependencies", Opt_FunctionalDependencies, nop ),
1943 ( "GeneralizedNewtypeDeriving", Opt_GeneralizedNewtypeDeriving, setGenDeriving ),
1944 ( "OverlappingInstances", Opt_OverlappingInstances, nop ),
1945 ( "UndecidableInstances", Opt_UndecidableInstances, nop ),
1946 ( "IncoherentInstances", Opt_IncoherentInstances, nop ),
1947 ( "PackageImports", Opt_PackageImports, nop )
1948 ]
1949
1950 defaultFlags :: [DynFlag]
1951 defaultFlags
1952 = [ Opt_AutoLinkPackages,
1953 Opt_ReadUserPackageConf,
1954
1955 Opt_SharedImplib,
1956
1957 #if GHC_DEFAULT_NEW_CODEGEN
1958 Opt_TryNewCodeGen,
1959 #endif
1960
1961 Opt_GenManifest,
1962 Opt_EmbedManifest,
1963 Opt_PrintBindContents,
1964 Opt_GhciSandbox,
1965 Opt_GhciHistory,
1966 Opt_HelpfulErrors
1967 ]
1968
1969 ++ [f | (ns,f) <- optLevelFlags, 0 `elem` ns]
1970 -- The default -O0 options
1971
1972 impliedFlags :: [(ExtensionFlag, TurnOnFlag, ExtensionFlag)]
1973 impliedFlags
1974 = [ (Opt_RankNTypes, turnOn, Opt_ExplicitForAll)
1975 , (Opt_Rank2Types, turnOn, Opt_ExplicitForAll)
1976 , (Opt_ScopedTypeVariables, turnOn, Opt_ExplicitForAll)
1977 , (Opt_LiberalTypeSynonyms, turnOn, Opt_ExplicitForAll)
1978 , (Opt_ExistentialQuantification, turnOn, Opt_ExplicitForAll)
1979 , (Opt_PolymorphicComponents, turnOn, Opt_ExplicitForAll)
1980 , (Opt_FlexibleInstances, turnOn, Opt_TypeSynonymInstances)
1981 , (Opt_FunctionalDependencies, turnOn, Opt_MultiParamTypeClasses)
1982
1983 , (Opt_RebindableSyntax, turnOff, Opt_ImplicitPrelude) -- NB: turn off!
1984
1985 , (Opt_GADTs, turnOn, Opt_GADTSyntax)
1986 , (Opt_GADTs, turnOn, Opt_MonoLocalBinds)
1987 , (Opt_TypeFamilies, turnOn, Opt_MonoLocalBinds)
1988
1989 , (Opt_TypeFamilies, turnOn, Opt_KindSignatures) -- Type families use kind signatures
1990 -- all over the place
1991
1992 , (Opt_ImpredicativeTypes, turnOn, Opt_RankNTypes)
1993
1994 -- Record wild-cards implies field disambiguation
1995 -- Otherwise if you write (C {..}) you may well get
1996 -- stuff like " 'a' not in scope ", which is a bit silly
1997 -- if the compiler has just filled in field 'a' of constructor 'C'
1998 , (Opt_RecordWildCards, turnOn, Opt_DisambiguateRecordFields)
1999
2000 , (Opt_ParallelArrays, turnOn, Opt_ParallelListComp)
2001 ]
2002
2003 optLevelFlags :: [([Int], DynFlag)]
2004 optLevelFlags
2005 = [ ([0], Opt_IgnoreInterfacePragmas)
2006 , ([0], Opt_OmitInterfacePragmas)
2007
2008 , ([1,2], Opt_IgnoreAsserts)
2009 , ([1,2], Opt_EnableRewriteRules) -- Off for -O0; see Note [Scoping for Builtin rules]
2010 -- in PrelRules
2011 , ([1,2], Opt_DoEtaReduction)
2012 , ([1,2], Opt_CaseMerge)
2013 , ([1,2], Opt_Strictness)
2014 , ([1,2], Opt_CSE)
2015 , ([1,2], Opt_FullLaziness)
2016 , ([1,2], Opt_Specialise)
2017 , ([1,2], Opt_FloatIn)
2018
2019 , ([2], Opt_LiberateCase)
2020 , ([2], Opt_SpecConstr)
2021 , ([2], Opt_RegsGraph)
2022
2023 -- , ([2], Opt_StaticArgumentTransformation)
2024 -- Max writes: I think it's probably best not to enable SAT with -O2 for the
2025 -- 6.10 release. The version of SAT in HEAD at the moment doesn't incorporate
2026 -- several improvements to the heuristics, and I'm concerned that without
2027 -- those changes SAT will interfere with some attempts to write "high
2028 -- performance Haskell", as we saw in some posts on Haskell-Cafe earlier
2029 -- this year. In particular, the version in HEAD lacks the tail call
2030 -- criterion, so many things that look like reasonable loops will be
2031 -- turned into functions with extra (unneccesary) thunk creation.
2032
2033 , ([0,1,2], Opt_DoLambdaEtaExpansion)
2034 -- This one is important for a tiresome reason:
2035 -- we want to make sure that the bindings for data
2036 -- constructors are eta-expanded. This is probably
2037 -- a good thing anyway, but it seems fragile.
2038 ]
2039
2040 -- -----------------------------------------------------------------------------
2041 -- Standard sets of warning options
2042
2043 standardWarnings :: [WarningFlag]
2044 standardWarnings
2045 = [ Opt_WarnWarningsDeprecations,
2046 Opt_WarnDeprecatedFlags,
2047 Opt_WarnUnrecognisedPragmas,
2048 Opt_WarnOverlappingPatterns,
2049 Opt_WarnMissingFields,
2050 Opt_WarnMissingMethods,
2051 Opt_WarnDuplicateExports,
2052 Opt_WarnLazyUnliftedBindings,
2053 Opt_WarnDodgyForeignImports,
2054 Opt_WarnWrongDoBind,
2055 Opt_WarnAlternativeLayoutRuleTransitional
2056 ]
2057
2058 minusWOpts :: [WarningFlag]
2059 -- Things you get with -W
2060 minusWOpts
2061 = standardWarnings ++
2062 [ Opt_WarnUnusedBinds,
2063 Opt_WarnUnusedMatches,
2064 Opt_WarnUnusedImports,
2065 Opt_WarnIncompletePatterns,
2066 Opt_WarnDodgyExports,
2067 Opt_WarnDodgyImports
2068 ]
2069
2070 minusWallOpts :: [WarningFlag]
2071 -- Things you get with -Wall
2072 minusWallOpts
2073 = minusWOpts ++
2074 [ Opt_WarnTypeDefaults,
2075 Opt_WarnNameShadowing,
2076 Opt_WarnMissingSigs,
2077 Opt_WarnHiShadows,
2078 Opt_WarnOrphans,
2079 Opt_WarnUnusedDoBind
2080 ]
2081
2082 enableGlasgowExts :: DynP ()
2083 enableGlasgowExts = do setDynFlag Opt_PrintExplicitForalls
2084 mapM_ setExtensionFlag glasgowExtsFlags
2085
2086 disableGlasgowExts :: DynP ()
2087 disableGlasgowExts = do unSetDynFlag Opt_PrintExplicitForalls
2088 mapM_ unSetExtensionFlag glasgowExtsFlags
2089
2090 glasgowExtsFlags :: [ExtensionFlag]
2091 glasgowExtsFlags = [
2092 Opt_ForeignFunctionInterface
2093 , Opt_UnliftedFFITypes
2094 , Opt_ImplicitParams
2095 , Opt_ScopedTypeVariables
2096 , Opt_UnboxedTuples
2097 , Opt_TypeSynonymInstances
2098 , Opt_StandaloneDeriving
2099 , Opt_DeriveDataTypeable
2100 , Opt_DeriveFunctor
2101 , Opt_DeriveFoldable
2102 , Opt_DeriveTraversable
2103 , Opt_DeriveGeneric
2104 , Opt_FlexibleContexts
2105 , Opt_FlexibleInstances
2106 , Opt_ConstrainedClassMethods
2107 , Opt_MultiParamTypeClasses
2108 , Opt_FunctionalDependencies
2109 , Opt_MagicHash
2110 , Opt_PolymorphicComponents
2111 , Opt_ExistentialQuantification
2112 , Opt_UnicodeSyntax
2113 , Opt_PostfixOperators
2114 , Opt_PatternGuards
2115 , Opt_LiberalTypeSynonyms
2116 , Opt_RankNTypes
2117 , Opt_TypeOperators
2118 , Opt_DoRec
2119 , Opt_ParallelListComp
2120 , Opt_EmptyDataDecls
2121 , Opt_KindSignatures
2122 , Opt_GeneralizedNewtypeDeriving ]
2123
2124 #ifdef GHCI
2125 -- Consult the RTS to find whether GHC itself has been built profiled
2126 -- If so, you can't use Template Haskell
2127 foreign import ccall unsafe "rts_isProfiled" rtsIsProfiledIO :: IO CInt
2128
2129 rtsIsProfiled :: Bool
2130 rtsIsProfiled = unsafePerformIO rtsIsProfiledIO /= 0
2131 #endif
2132
2133 setGenDeriving :: Bool -> DynP ()
2134 setGenDeriving True = getCurLoc >>= \l -> upd (\d -> d { newDerivOnLoc = l })
2135 setGenDeriving False = return ()
2136
2137 checkTemplateHaskellOk :: Bool -> DynP ()
2138 #ifdef GHCI
2139 checkTemplateHaskellOk turn_on
2140 | turn_on && rtsIsProfiled
2141 = addErr "You can't use Template Haskell with a profiled compiler"
2142 | otherwise
2143 = getCurLoc >>= \l -> upd (\d -> d { thOnLoc = l })
2144 #else
2145 -- In stage 1 we don't know that the RTS has rts_isProfiled,
2146 -- so we simply say "ok". It doesn't matter because TH isn't
2147 -- available in stage 1 anyway.
2148 checkTemplateHaskellOk _ = return ()
2149 #endif
2150
2151 {- **********************************************************************
2152 %* *
2153 DynFlags constructors
2154 %* *
2155 %********************************************************************* -}
2156
2157 type DynP = EwM (CmdLineP DynFlags)
2158
2159 upd :: (DynFlags -> DynFlags) -> DynP ()
2160 upd f = liftEwM (do dflags <- getCmdLineState
2161 putCmdLineState $! f dflags)
2162
2163 updM :: (DynFlags -> DynP DynFlags) -> DynP ()
2164 updM f = do dflags <- liftEwM getCmdLineState
2165 dflags' <- f dflags
2166 liftEwM $ putCmdLineState $! dflags'
2167
2168 --------------- Constructor functions for OptKind -----------------
2169 noArg :: (DynFlags -> DynFlags) -> OptKind (CmdLineP DynFlags)
2170 noArg fn = NoArg (upd fn)
2171
2172 noArgM :: (DynFlags -> DynP DynFlags) -> OptKind (CmdLineP DynFlags)
2173 noArgM fn = NoArg (updM fn)
2174
2175 noArgDF :: (DynFlags -> DynFlags) -> String -> OptKind (CmdLineP DynFlags)
2176 noArgDF fn deprec = NoArg (upd fn >> deprecate deprec)
2177
2178 hasArg :: (String -> DynFlags -> DynFlags) -> OptKind (CmdLineP DynFlags)
2179 hasArg fn = HasArg (upd . fn)
2180
2181 hasArgDF :: (String -> DynFlags -> DynFlags) -> String -> OptKind (CmdLineP DynFlags)
2182 hasArgDF fn deprec = HasArg (\s -> do upd (fn s)
2183 deprecate deprec)
2184
2185 sepArg :: (String -> DynFlags -> DynFlags) -> OptKind (CmdLineP DynFlags)
2186 sepArg fn = SepArg (upd . fn)
2187
2188 intSuffix :: (Int -> DynFlags -> DynFlags) -> OptKind (CmdLineP DynFlags)
2189 intSuffix fn = IntSuffix (\n -> upd (fn n))
2190
2191 optIntSuffixM :: (Maybe Int -> DynFlags -> DynP DynFlags)
2192 -> OptKind (CmdLineP DynFlags)
2193 optIntSuffixM fn = OptIntSuffix (\mi -> updM (fn mi))
2194
2195 setDumpFlag :: DynFlag -> OptKind (CmdLineP DynFlags)
2196 setDumpFlag dump_flag = NoArg (setDumpFlag' dump_flag)
2197
2198 --------------------------
2199 setDynFlag, unSetDynFlag :: DynFlag -> DynP ()
2200 setDynFlag f = upd (\dfs -> dopt_set dfs f)
2201 unSetDynFlag f = upd (\dfs -> dopt_unset dfs f)
2202
2203 --------------------------
2204 setWarningFlag, unSetWarningFlag :: WarningFlag -> DynP ()
2205 setWarningFlag f = upd (\dfs -> wopt_set dfs f)
2206 unSetWarningFlag f = upd (\dfs -> wopt_unset dfs f)
2207
2208 --------------------------
2209 setExtensionFlag, unSetExtensionFlag :: ExtensionFlag -> DynP ()
2210 setExtensionFlag f = do upd (\dfs -> xopt_set dfs f)
2211 sequence_ deps
2212 where
2213 deps = [ if turn_on then setExtensionFlag d
2214 else unSetExtensionFlag d
2215 | (f', turn_on, d) <- impliedFlags, f' == f ]
2216 -- When you set f, set the ones it implies
2217 -- NB: use setExtensionFlag recursively, in case the implied flags
2218 -- implies further flags
2219
2220 unSetExtensionFlag f = upd (\dfs -> xopt_unset dfs f)
2221 -- When you un-set f, however, we don't un-set the things it implies
2222 -- (except for -fno-glasgow-exts, which is treated specially)
2223
2224 --------------------------
2225 alterSettings :: (Settings -> Settings) -> DynFlags -> DynFlags
2226 alterSettings f dflags = dflags { settings = f (settings dflags) }
2227
2228 --------------------------
2229 setDumpFlag' :: DynFlag -> DynP ()
2230 setDumpFlag' dump_flag
2231 = do setDynFlag dump_flag
2232 when want_recomp forceRecompile
2233 where
2234 -- Certain dumpy-things are really interested in what's going
2235 -- on during recompilation checking, so in those cases we
2236 -- don't want to turn it off.
2237 want_recomp = dump_flag `notElem` [Opt_D_dump_if_trace,
2238 Opt_D_dump_hi_diffs]
2239
2240 forceRecompile :: DynP ()
2241 -- Whenver we -ddump, force recompilation (by switching off the
2242 -- recompilation checker), else you don't see the dump! However,
2243 -- don't switch it off in --make mode, else *everything* gets
2244 -- recompiled which probably isn't what you want
2245 forceRecompile = do dfs <- liftEwM getCmdLineState
2246 when (force_recomp dfs) (setDynFlag Opt_ForceRecomp)
2247 where
2248 force_recomp dfs = isOneShot (ghcMode dfs)
2249
2250 setVerboseCore2Core :: DynP ()
2251 setVerboseCore2Core = do forceRecompile
2252 setDynFlag Opt_D_verbose_core2core
2253 upd (\dfs -> dfs { shouldDumpSimplPhase = Nothing })
2254
2255 setDumpSimplPhases :: String -> DynP ()
2256 setDumpSimplPhases s = do forceRecompile
2257 upd (\dfs -> dfs { shouldDumpSimplPhase = Just spec })
2258 where
2259 spec = case s of { ('=' : s') -> s'; _ -> s }
2260
2261 setVerbosity :: Maybe Int -> DynP ()
2262 setVerbosity mb_n = upd (\dfs -> dfs{ verbosity = mb_n `orElse` 3 })
2263
2264 addCmdlineHCInclude :: String -> DynP ()
2265 addCmdlineHCInclude a = upd (\s -> s{cmdlineHcIncludes = a : cmdlineHcIncludes s})
2266
2267 extraPkgConf_ :: FilePath -> DynP ()
2268 extraPkgConf_ p = upd (\s -> s{ extraPkgConfs = p : extraPkgConfs s })
2269
2270 exposePackage, exposePackageId, hidePackage, ignorePackage,
2271 trustPackage, distrustPackage :: String -> DynP ()
2272 exposePackage p =
2273 upd (\s -> s{ packageFlags = ExposePackage p : packageFlags s })
2274 exposePackageId p =
2275 upd (\s -> s{ packageFlags = ExposePackageId p : packageFlags s })
2276 hidePackage p =
2277 upd (\s -> s{ packageFlags = HidePackage p : packageFlags s })
2278 ignorePackage p =
2279 upd (\s -> s{ packageFlags = IgnorePackage p : packageFlags s })
2280 trustPackage p = exposePackage p >> -- both trust and distrust also expose a package
2281 upd (\s -> s{ packageFlags = TrustPackage p : packageFlags s })
2282 distrustPackage p = exposePackage p >>
2283 upd (\s -> s{ packageFlags = DistrustPackage p : packageFlags s })
2284
2285 setPackageName :: String -> DynFlags -> DynFlags
2286 setPackageName p s = s{ thisPackage = stringToPackageId p }
2287
2288 -- If we're linking a binary, then only targets that produce object
2289 -- code are allowed (requests for other target types are ignored).
2290 setTarget :: HscTarget -> DynP ()
2291 setTarget l = upd set
2292 where
2293 set dfs
2294 | ghcLink dfs /= LinkBinary || isObjectTarget l = dfs{ hscTarget = l }
2295 | otherwise = dfs
2296
2297 -- Changes the target only if we're compiling object code. This is
2298 -- used by -fasm and -fllvm, which switch from one to the other, but
2299 -- not from bytecode to object-code. The idea is that -fasm/-fllvm
2300 -- can be safely used in an OPTIONS_GHC pragma.
2301 setObjTarget :: HscTarget -> DynP ()
2302 setObjTarget l = updM set
2303 where
2304 set dflags
2305 | isObjectTarget (hscTarget dflags)
2306 = case l of
2307 HscC
2308 | cGhcUnregisterised /= "YES" ->
2309 do addWarn ("Compiler not unregisterised, so ignoring " ++ flag)
2310 return dflags
2311 HscAsm
2312 | cGhcWithNativeCodeGen /= "YES" ->
2313 do addWarn ("Compiler has no native codegen, so ignoring " ++
2314 flag)
2315 return dflags
2316 HscLlvm
2317 | not ((arch == ArchX86_64) && (os == OSLinux || os == OSDarwin)) &&
2318 (not opt_Static || opt_PIC)
2319 ->
2320 do addWarn ("Ignoring " ++ flag ++ " as it is incompatible with -fPIC and -dynamic on this platform")
2321 return dflags
2322 _ -> return $ dflags { hscTarget = l }
2323 | otherwise = return dflags
2324 where platform = targetPlatform dflags
2325 arch = platformArch platform
2326 os = platformOS platform
2327 flag = showHscTargetFlag l
2328
2329 setOptLevel :: Int -> DynFlags -> DynP DynFlags
2330 setOptLevel n dflags
2331 | hscTarget dflags == HscInterpreted && n > 0
2332 = do addWarn "-O conflicts with --interactive; -O ignored."
2333 return dflags
2334 | otherwise
2335 = return (updOptLevel n dflags)
2336
2337
2338 -- -Odph is equivalent to
2339 --
2340 -- -O2 optimise as much as possible
2341 -- -fmax-simplifier-iterations20 this is necessary sometimes
2342 -- -fsimplifier-phases=3 we use an additional simplifier phase for fusion
2343 --
2344 setDPHOpt :: DynFlags -> DynP DynFlags
2345 setDPHOpt dflags = setOptLevel 2 (dflags { maxSimplIterations = 20
2346 , simplPhases = 3
2347 })
2348
2349 -- Determines the package used by the vectoriser for the symbols of the vectorised code.
2350 -- 'DPHNone' indicates that no data-parallel backend library is available; hence, the
2351 -- vectoriser cannot be used.
2352 --
2353 data DPHBackend = DPHPar -- "dph-par"
2354 | DPHSeq -- "dph-seq"
2355 | DPHThis -- the currently compiled package
2356 | DPHNone -- no DPH library available
2357 deriving(Eq, Ord, Enum, Show)
2358
2359 setDPHBackend :: DPHBackend -> DynP ()
2360 setDPHBackend backend = upd $ \dflags -> dflags { dphBackend = backend }
2361
2362 -- Query the DPH backend package to be used by the vectoriser and desugaring of DPH syntax.
2363 --
2364 dphPackageMaybe :: DynFlags -> Maybe PackageId
2365 dphPackageMaybe dflags
2366 = case dphBackend dflags of
2367 DPHPar -> Just dphParPackageId
2368 DPHSeq -> Just dphSeqPackageId
2369 DPHThis -> Just (thisPackage dflags)
2370 DPHNone -> Nothing
2371
2372 setMainIs :: String -> DynP ()
2373 setMainIs arg
2374 | not (null main_fn) && isLower (head main_fn)
2375 -- The arg looked like "Foo.Bar.baz"
2376 = upd $ \d -> d{ mainFunIs = Just main_fn,
2377 mainModIs = mkModule mainPackageId (mkModuleName main_mod) }
2378
2379 | isUpper (head arg) -- The arg looked like "Foo" or "Foo.Bar"
2380 = upd $ \d -> d{ mainModIs = mkModule mainPackageId (mkModuleName arg) }
2381
2382 | otherwise -- The arg looked like "baz"
2383 = upd $ \d -> d{ mainFunIs = Just arg }
2384 where
2385 (main_mod, main_fn) = splitLongestPrefix arg (== '.')
2386
2387 -----------------------------------------------------------------------------
2388 -- Paths & Libraries
2389
2390 addImportPath, addLibraryPath, addIncludePath, addFrameworkPath :: FilePath -> DynP ()
2391
2392 -- -i on its own deletes the import paths
2393 addImportPath "" = upd (\s -> s{importPaths = []})
2394 addImportPath p = upd (\s -> s{importPaths = importPaths s ++ splitPathList p})
2395
2396 addLibraryPath p =
2397 upd (\s -> s{libraryPaths = libraryPaths s ++ splitPathList p})
2398
2399 addIncludePath p =
2400 upd (\s -> s{includePaths = includePaths s ++ splitPathList p})
2401
2402 addFrameworkPath p =
2403 upd (\s -> s{frameworkPaths = frameworkPaths s ++ splitPathList p})
2404
2405 #ifndef mingw32_TARGET_OS
2406 split_marker :: Char
2407 split_marker = ':' -- not configurable (ToDo)
2408 #endif
2409
2410 splitPathList :: String -> [String]
2411 splitPathList s = filter notNull (splitUp s)
2412 -- empty paths are ignored: there might be a trailing
2413 -- ':' in the initial list, for example. Empty paths can
2414 -- cause confusion when they are translated into -I options
2415 -- for passing to gcc.
2416 where
2417 #ifndef mingw32_TARGET_OS
2418 splitUp xs = split split_marker xs
2419 #else
2420 -- Windows: 'hybrid' support for DOS-style paths in directory lists.
2421 --
2422 -- That is, if "foo:bar:baz" is used, this interpreted as
2423 -- consisting of three entries, 'foo', 'bar', 'baz'.
2424 -- However, with "c:/foo:c:\\foo;x:/bar", this is interpreted
2425 -- as 3 elts, "c:/foo", "c:\\foo", "x:/bar"
2426 --
2427 -- Notice that no attempt is made to fully replace the 'standard'
2428 -- split marker ':' with the Windows / DOS one, ';'. The reason being
2429 -- that this will cause too much breakage for users & ':' will
2430 -- work fine even with DOS paths, if you're not insisting on being silly.
2431 -- So, use either.
2432 splitUp [] = []
2433 splitUp (x:':':div:xs) | div `elem` dir_markers
2434 = ((x:':':div:p): splitUp rs)
2435 where
2436 (p,rs) = findNextPath xs
2437 -- we used to check for existence of the path here, but that
2438 -- required the IO monad to be threaded through the command-line
2439 -- parser which is quite inconvenient. The
2440 splitUp xs = cons p (splitUp rs)
2441 where
2442 (p,rs) = findNextPath xs
2443
2444 cons "" xs = xs
2445 cons x xs = x:xs
2446
2447 -- will be called either when we've consumed nought or the
2448 -- "<Drive>:/" part of a DOS path, so splitting is just a Q of
2449 -- finding the next split marker.
2450 findNextPath xs =
2451 case break (`elem` split_markers) xs of
2452 (p, _:ds) -> (p, ds)
2453 (p, xs) -> (p, xs)
2454
2455 split_markers :: [Char]
2456 split_markers = [':', ';']
2457
2458 dir_markers :: [Char]
2459 dir_markers = ['/', '\\']
2460 #endif
2461
2462 -- -----------------------------------------------------------------------------
2463 -- tmpDir, where we store temporary files.
2464
2465 setTmpDir :: FilePath -> DynFlags -> DynFlags
2466 setTmpDir dir = alterSettings (\s -> s { sTmpDir = normalise dir })
2467 -- we used to fix /cygdrive/c/.. on Windows, but this doesn't
2468 -- seem necessary now --SDM 7/2/2008
2469
2470 -----------------------------------------------------------------------------
2471 -- RTS opts
2472
2473 setRtsOpts :: String -> DynP ()
2474 setRtsOpts arg = upd $ \ d -> d {rtsOpts = Just arg}
2475
2476 setRtsOptsEnabled :: RtsOptsEnabled -> DynP ()
2477 setRtsOptsEnabled arg = upd $ \ d -> d {rtsOptsEnabled = arg}
2478
2479 -----------------------------------------------------------------------------
2480 -- Hpc stuff
2481
2482 setOptHpcDir :: String -> DynP ()
2483 setOptHpcDir arg = upd $ \ d -> d{hpcDir = arg}
2484
2485 -----------------------------------------------------------------------------
2486 -- Via-C compilation stuff
2487
2488 -- There are some options that we need to pass to gcc when compiling
2489 -- Haskell code via C, but are only supported by recent versions of
2490 -- gcc. The configure script decides which of these options we need,
2491 -- and puts them in the "settings" file in $topdir. The advantage of
2492 -- having these in a separate file is that the file can be created at
2493 -- install-time depending on the available gcc version, and even
2494 -- re-generated later if gcc is upgraded.
2495 --
2496 -- The options below are not dependent on the version of gcc, only the
2497 -- platform.
2498
2499 picCCOpts :: DynFlags -> [String]
2500 picCCOpts dflags
2501 = case platformOS (targetPlatform dflags) of
2502 OSDarwin
2503 -- Apple prefers to do things the other way round.
2504 -- PIC is on by default.
2505 -- -mdynamic-no-pic:
2506 -- Turn off PIC code generation.
2507 -- -fno-common:
2508 -- Don't generate "common" symbols - these are unwanted
2509 -- in dynamic libraries.
2510
2511 | opt_PIC -> ["-fno-common", "-U __PIC__", "-D__PIC__"]
2512 | otherwise -> ["-mdynamic-no-pic"]
2513 OSMinGW32 -- no -fPIC for Windows
2514 | opt_PIC -> ["-U __PIC__", "-D__PIC__"]
2515 | otherwise -> []
2516 _
2517 -- we need -fPIC for C files when we are compiling with -dynamic,
2518 -- otherwise things like stub.c files don't get compiled
2519 -- correctly. They need to reference data in the Haskell
2520 -- objects, but can't without -fPIC. See
2521 -- http://hackage.haskell.org/trac/ghc/wiki/Commentary/PositionIndependentCode
2522 | opt_PIC || not opt_Static -> ["-fPIC", "-U __PIC__", "-D__PIC__"]
2523 | otherwise -> []
2524
2525 -- -----------------------------------------------------------------------------
2526 -- Splitting
2527
2528 can_split :: Bool
2529 can_split = cSupportsSplitObjs == "YES"
2530
2531 -- -----------------------------------------------------------------------------
2532 -- Compiler Info
2533
2534 compilerInfo :: DynFlags -> [(String, String)]
2535 compilerInfo dflags
2536 = -- We always make "Project name" be first to keep parsing in
2537 -- other languages simple, i.e. when looking for other fields,
2538 -- you don't have to worry whether there is a leading '[' or not
2539 ("Project name", cProjectName)
2540 -- Next come the settings, so anything else can be overridden
2541 -- in the settings file (as "lookup" uses the first match for the
2542 -- key)
2543 : rawSettings dflags
2544 ++ [("Project version", cProjectVersion),
2545 ("Booter version", cBooterVersion),
2546 ("Stage", cStage),
2547 ("Build platform", cBuildPlatformString),
2548 ("Host platform", cHostPlatformString),
2549 ("Target platform", cTargetPlatformString),
2550 ("Have interpreter", cGhcWithInterpreter),
2551 ("Object splitting supported", cSupportsSplitObjs),
2552 ("Have native code generator", cGhcWithNativeCodeGen),
2553 ("Support SMP", cGhcWithSMP),
2554 ("Unregisterised", cGhcUnregisterised),
2555 ("Tables next to code", cGhcEnableTablesNextToCode),
2556 ("RTS ways", cGhcRTSWays),
2557 ("Leading underscore", cLeadingUnderscore),
2558 ("Debug on", show debugIsOn),
2559 ("LibDir", topDir dflags),
2560 ("Global Package DB", systemPackageConfig dflags),
2561 ("Gcc Linker flags", show cGccLinkerOpts),
2562 ("Ld Linker flags", show cLdLinkerOpts)
2563 ]
2564