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