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