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