{-# LANGUAGE CPP #-}
{-# LANGUAGE FlexibleInstances #-}

-------------------------------------------------------------------------------
--
-- | Dynamic flags
--
-- Most flags are dynamic flags, which means they can change from compilation
-- to compilation using @OPTIONS_GHC@ pragmas, and in a multi-session GHC each
-- session can be using different dynamic flags. Dynamic flags can also be set
-- at the prompt in GHCi.
--
-- (c) The University of Glasgow 2005
--
-------------------------------------------------------------------------------

{-# OPTIONS_GHC -fno-cse #-}
-- -fno-cse is needed for GLOBAL_VAR's to behave properly

module DynFlags (
        -- * Dynamic flags and associated configuration types
        DumpFlag(..),
        GeneralFlag(..),
        WarningFlag(..), WarnReason(..),
        Language(..),
        PlatformConstants(..),
        FatalMessager, LogAction, FlushOut(..), FlushErr(..),
        ProfAuto(..),
        glasgowExtsFlags,
        warningGroups, warningHierarchies,
        hasPprDebug, hasNoDebugOutput, hasNoStateHack, hasNoOptCoercion,
        dopt, dopt_set, dopt_unset,
        gopt, gopt_set, gopt_unset, setGeneralFlag', unSetGeneralFlag',
        wopt, wopt_set, wopt_unset,
        wopt_fatal, wopt_set_fatal, wopt_unset_fatal,
        xopt, xopt_set, xopt_unset,
        xopt_set_unlessExplSpec,
        lang_set,
        useUnicodeSyntax,
        useStarIsType,
        whenGeneratingDynamicToo, ifGeneratingDynamicToo,
        whenCannotGenerateDynamicToo,
        dynamicTooMkDynamicDynFlags,
        dynamicOutputFile,
        DynFlags(..),
        FlagSpec(..),
        HasDynFlags(..), ContainsDynFlags(..),
        RtsOptsEnabled(..),
        HscTarget(..), isObjectTarget, defaultObjectTarget,
        targetRetainsAllBindings,
        GhcMode(..), isOneShot,
        GhcLink(..), isNoLink,
        PackageFlag(..), PackageArg(..), ModRenaming(..),
        packageFlagsChanged,
        IgnorePackageFlag(..), TrustFlag(..),
        PackageDBFlag(..), PkgConfRef(..),
        Option(..), showOpt,
        DynLibLoader(..),
        fFlags, fLangFlags, xFlags,
        wWarningFlags,
        dynFlagDependencies,
        makeDynFlagsConsistent,
        shouldUseColor,
        shouldUseHexWordLiterals,
        positionIndependent,
        optimisationFlags,
        setFlagsFromEnvFile,

        Way(..), mkBuildTag, wayRTSOnly, addWay', updateWays,
        wayGeneralFlags, wayUnsetGeneralFlags,

        thisPackage, thisComponentId, thisUnitIdInsts,

        -- ** Log output
        putLogMsg,

        -- ** Safe Haskell
        SafeHaskellMode(..),
        safeHaskellOn, safeHaskellModeEnabled,
        safeImportsOn, safeLanguageOn, safeInferOn,
        packageTrustOn,
        safeDirectImpsReq, safeImplicitImpsReq,
        unsafeFlags, unsafeFlagsForInfer,

        -- ** LLVM Targets
        LlvmTarget(..), LlvmConfig(..),

        -- ** System tool settings and locations
        Settings(..),
        sProgramName,
        sProjectVersion,
        sGhcUsagePath,
        sGhciUsagePath,
        sToolDir,
        sTopDir,
        sTmpDir,
        sSystemPackageConfig,
        sLdSupportsCompactUnwind,
        sLdSupportsBuildId,
        sLdSupportsFilelist,
        sLdIsGnuLd,
        sGccSupportsNoPie,
        sPgm_L,
        sPgm_P,
        sPgm_F,
        sPgm_c,
        sPgm_a,
        sPgm_l,
        sPgm_dll,
        sPgm_T,
        sPgm_windres,
        sPgm_libtool,
        sPgm_ar,
        sPgm_ranlib,
        sPgm_lo,
        sPgm_lc,
        sPgm_lcc,
        sPgm_i,
        sOpt_L,
        sOpt_P,
        sOpt_P_fingerprint,
        sOpt_F,
        sOpt_c,
        sOpt_cxx,
        sOpt_a,
        sOpt_l,
        sOpt_windres,
        sOpt_lo,
        sOpt_lc,
        sOpt_lcc,
        sOpt_i,
        sExtraGccViaCFlags,
        sTargetPlatformString,
        sIntegerLibrary,
        sIntegerLibraryType,
        sGhcWithInterpreter,
        sGhcWithNativeCodeGen,
        sGhcWithSMP,
        sGhcRTSWays,
        sTablesNextToCode,
        sLeadingUnderscore,
        sLibFFI,
        sGhcThreaded,
        sGhcDebugged,
        sGhcRtsWithLibdw,
        IntegerLibrary(..),
        GhcNameVersion(..),
        FileSettings(..),
        PlatformMisc(..),
        settings,
        programName, projectVersion,
        ghcUsagePath, ghciUsagePath, topDir, tmpDir,
        versionedAppDir, versionedFilePath,
        extraGccViaCFlags, systemPackageConfig,
        pgm_L, pgm_P, pgm_F, pgm_c, pgm_a, pgm_l, pgm_dll, pgm_T,
        pgm_windres, pgm_libtool, pgm_ar, pgm_ranlib, pgm_lo, pgm_lc,
        pgm_lcc, pgm_i,
        opt_L, opt_P, opt_F, opt_c, opt_cxx, opt_a, opt_l, opt_i,
        opt_P_signature,
        opt_windres, opt_lo, opt_lc, opt_lcc,
        tablesNextToCode,

        -- ** Manipulating DynFlags
        addPluginModuleName,
        defaultDynFlags,                -- Settings -> DynFlags
        defaultWays,
        interpWays,
        interpreterProfiled, interpreterDynamic,
        initDynFlags,                   -- DynFlags -> IO DynFlags
        defaultFatalMessager,
        defaultLogAction,
        defaultLogActionHPrintDoc,
        defaultLogActionHPutStrDoc,
        defaultFlushOut,
        defaultFlushErr,

        getOpts,                        -- DynFlags -> (DynFlags -> [a]) -> [a]
        getVerbFlags,
        updOptLevel,
        setTmpDir,
        setUnitId,
        canonicalizeHomeModule,
        canonicalizeModuleIfHome,

        -- ** Parsing DynFlags
        parseDynamicFlagsCmdLine,
        parseDynamicFilePragma,
        parseDynamicFlagsFull,

        -- ** Available DynFlags
        allNonDeprecatedFlags,
        flagsAll,
        flagsDynamic,
        flagsPackage,
        flagsForCompletion,

        supportedLanguagesAndExtensions,
        languageExtensions,

        -- ** DynFlags C compiler options
        picCCOpts, picPOpts,

        -- * Compiler configuration suitable for display to the user
        compilerInfo,

        rtsIsProfiled,
        dynamicGhc,

#include "GHCConstantsHaskellExports.hs"
        bLOCK_SIZE_W,
        wORD_SIZE_IN_BITS,
        wordAlignment,
        tAG_MASK,
        mAX_PTR_TAG,
        tARGET_MIN_INT, tARGET_MAX_INT, tARGET_MAX_WORD,

        unsafeGlobalDynFlags, setUnsafeGlobalDynFlags,

        -- * SSE and AVX
        isSseEnabled,
        isSse2Enabled,
        isSse4_2Enabled,
        isBmiEnabled,
        isBmi2Enabled,
        isAvxEnabled,
        isAvx2Enabled,
        isAvx512cdEnabled,
        isAvx512erEnabled,
        isAvx512fEnabled,
        isAvx512pfEnabled,

        -- * Linker/compiler information
        LinkerInfo(..),
        CompilerInfo(..),

        -- * File cleanup
        FilesToClean(..), emptyFilesToClean,

        -- * Include specifications
        IncludeSpecs(..), addGlobalInclude, addQuoteInclude, flattenIncludes,


        -- * Make use of the Cmm CFG
        CfgWeights(..), backendMaintainsCfg
  ) where

#include "HsVersions.h"

import GhcPrelude

import GHC.Platform
import GHC.UniqueSubdir (uniqueSubdir)
import PlatformConstants
import Module
import PackageConfig
import {-# SOURCE #-} Plugins
import {-# SOURCE #-} Hooks
import {-# SOURCE #-} PrelNames ( mAIN )
import {-# SOURCE #-} Packages (PackageState, emptyPackageState)
import DriverPhases     ( Phase(..), phaseInputExt )
import Config
import CliOption
import CmdLineParser hiding (WarnReason(..))
import qualified CmdLineParser as Cmd
import Constants
import GhcNameVersion
import Panic
import qualified PprColour as Col
import Util
import Maybes
import MonadUtils
import qualified Pretty
import SrcLoc
import BasicTypes       ( Alignment, alignmentOf, IntWithInf, treatZeroAsInf )
import FastString
import Fingerprint
import FileSettings
import Outputable
import Settings
import ToolSettings

import Foreign.C        ( CInt(..) )
import System.IO.Unsafe ( unsafeDupablePerformIO )
import {-# SOURCE #-} ErrUtils ( Severity(..), MsgDoc, mkLocMessageAnn
                               , getCaretDiagnostic )
import Json
import SysTools.Terminal ( stderrSupportsAnsiColors )
import SysTools.BaseDir ( expandToolDir, expandTopDir )

import System.IO.Unsafe ( unsafePerformIO )
import Data.IORef
import Control.Arrow ((&&&))
import Control.Monad
import Control.Monad.Trans.Class
import Control.Monad.Trans.Writer
import Control.Monad.Trans.Reader
import Control.Monad.Trans.Except

import Data.Ord
import Data.Bits
import Data.Char
import Data.Int
import Data.List
import Data.Map (Map)
import qualified Data.Map as Map
import Data.Set (Set)
import qualified Data.Set as Set
import Data.Word
import System.FilePath
import System.Directory
import System.Environment (lookupEnv)
import System.IO
import System.IO.Error
import Text.ParserCombinators.ReadP hiding (char)
import Text.ParserCombinators.ReadP as R

import EnumSet (EnumSet)
import qualified EnumSet

import GHC.Foreign (withCString, peekCString)
import qualified GHC.LanguageExtensions as LangExt

#if GHC_STAGE >= 2
-- used by SHARED_GLOBAL_VAR
import Foreign (Ptr)
#endif

-- Note [Updating flag description in the User's Guide]
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
--
-- If you modify anything in this file please make sure that your changes are
-- described in the User's Guide. Please update the flag description in the
-- users guide (docs/users_guide) whenever you add or change a flag.

-- Note [Supporting CLI completion]
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
--
-- The command line interface completion (in for example bash) is an easy way
-- for the developer to learn what flags are available from GHC.
-- GHC helps by separating which flags are available when compiling with GHC,
-- and which flags are available when using GHCi.
-- A flag is assumed to either work in both these modes, or only in one of them.
-- When adding or changing a flag, please consider for which mode the flag will
-- have effect, and annotate it accordingly. For Flags use defFlag, defGhcFlag,
-- defGhciFlag, and for FlagSpec use flagSpec or flagGhciSpec.

-- Note [Adding a language extension]
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
--
-- There are a few steps to adding (or removing) a language extension,
--
--  * Adding the extension to GHC.LanguageExtensions
--
--    The Extension type in libraries/ghc-boot-th/GHC/LanguageExtensions/Type.hs
--    is the canonical list of language extensions known by GHC.
--
--  * Adding a flag to DynFlags.xFlags
--
--    This is fairly self-explanatory. The name should be concise, memorable,
--    and consistent with any previous implementations of the similar idea in
--    other Haskell compilers.
--
--  * Adding the flag to the documentation
--
--    This is the same as any other flag. See
--    Note [Updating flag description in the User's Guide]
--
--  * Adding the flag to Cabal
--
--    The Cabal library has its own list of all language extensions supported
--    by all major compilers. This is the list that user code being uploaded
--    to Hackage is checked against to ensure language extension validity.
--    Consequently, it is very important that this list remains up-to-date.
--
--    To this end, there is a testsuite test (testsuite/tests/driver/T4437.hs)
--    whose job it is to ensure these GHC's extensions are consistent with
--    Cabal.
--
--    The recommended workflow is,
--
--     1. Temporarily add your new language extension to the
--        expectedGhcOnlyExtensions list in T4437 to ensure the test doesn't
--        break while Cabal is updated.
--
--     2. After your GHC change is accepted, submit a Cabal pull request adding
--        your new extension to Cabal's list (found in
--        Cabal/Language/Haskell/Extension.hs).
--
--     3. After your Cabal change is accepted, let the GHC developers know so
--        they can update the Cabal submodule and remove the extensions from
--        expectedGhcOnlyExtensions.
--
--  * Adding the flag to the GHC Wiki
--
--    There is a change log tracking language extension additions and removals
--    on the GHC wiki:  https://gitlab.haskell.org/ghc/ghc/wikis/language-pragma-history
--
--  See #4437 and #8176.

-- -----------------------------------------------------------------------------
-- DynFlags

data DumpFlag
-- See Note [Updating flag description in the User's Guide]

   -- debugging flags
   = Opt_D_dump_cmm
   | Opt_D_dump_cmm_from_stg
   | Opt_D_dump_cmm_raw
   | Opt_D_dump_cmm_verbose_by_proc
   -- All of the cmm subflags (there are a lot!) automatically
   -- enabled if you run -ddump-cmm-verbose-by-proc
   -- Each flag corresponds to exact stage of Cmm pipeline.
   | Opt_D_dump_cmm_verbose
   -- same as -ddump-cmm-verbose-by-proc but writes each stage
   -- to a separate file (if used with -ddump-to-file)
   | Opt_D_dump_cmm_cfg
   | Opt_D_dump_cmm_cbe
   | Opt_D_dump_cmm_switch
   | Opt_D_dump_cmm_proc
   | Opt_D_dump_cmm_sp
   | Opt_D_dump_cmm_sink
   | Opt_D_dump_cmm_caf
   | Opt_D_dump_cmm_procmap
   | Opt_D_dump_cmm_split
   | Opt_D_dump_cmm_info
   | Opt_D_dump_cmm_cps
   -- end cmm subflags
   | Opt_D_dump_cfg_weights -- ^ Dump the cfg used for block layout.
   | Opt_D_dump_asm
   | Opt_D_dump_asm_native
   | Opt_D_dump_asm_liveness
   | Opt_D_dump_asm_regalloc
   | Opt_D_dump_asm_regalloc_stages
   | Opt_D_dump_asm_conflicts
   | Opt_D_dump_asm_stats
   | Opt_D_dump_asm_expanded
   | Opt_D_dump_llvm
   | Opt_D_dump_core_stats
   | Opt_D_dump_deriv
   | Opt_D_dump_ds
   | Opt_D_dump_ds_preopt
   | Opt_D_dump_foreign
   | Opt_D_dump_inlinings
   | Opt_D_dump_rule_firings
   | Opt_D_dump_rule_rewrites
   | Opt_D_dump_simpl_trace
   | Opt_D_dump_occur_anal
   | Opt_D_dump_parsed
   | Opt_D_dump_parsed_ast
   | Opt_D_dump_rn
   | Opt_D_dump_rn_ast
   | Opt_D_dump_simpl
   | Opt_D_dump_simpl_iterations
   | Opt_D_dump_spec
   | Opt_D_dump_prep
   | Opt_D_dump_stg -- CoreToStg output
   | Opt_D_dump_stg_unarised -- STG after unarise
   | Opt_D_dump_stg_final -- STG after stg2stg
   | Opt_D_dump_call_arity
   | Opt_D_dump_exitify
   | Opt_D_dump_stranal
   | Opt_D_dump_str_signatures
   | Opt_D_dump_tc
   | Opt_D_dump_tc_ast
   | Opt_D_dump_types
   | Opt_D_dump_rules
   | Opt_D_dump_cse
   | Opt_D_dump_worker_wrapper
   | Opt_D_dump_rn_trace
   | Opt_D_dump_rn_stats
   | Opt_D_dump_opt_cmm
   | Opt_D_dump_simpl_stats
   | Opt_D_dump_cs_trace -- Constraint solver in type checker
   | Opt_D_dump_tc_trace
   | Opt_D_dump_ec_trace -- Pattern match exhaustiveness checker
   | Opt_D_dump_if_trace
   | Opt_D_dump_vt_trace
   | Opt_D_dump_splices
   | Opt_D_th_dec_file
   | Opt_D_dump_BCOs
   | Opt_D_dump_ticked
   | Opt_D_dump_rtti
   | Opt_D_source_stats
   | Opt_D_verbose_stg2stg
   | Opt_D_dump_hi
   | Opt_D_dump_hi_diffs
   | Opt_D_dump_mod_cycles
   | Opt_D_dump_mod_map
   | Opt_D_dump_timings
   | Opt_D_dump_view_pattern_commoning
   | Opt_D_verbose_core2core
   | Opt_D_dump_debug
   | Opt_D_dump_json
   | Opt_D_ppr_debug
   | Opt_D_no_debug_output
   deriving (DumpFlag -> DumpFlag -> Bool
(DumpFlag -> DumpFlag -> Bool)
-> (DumpFlag -> DumpFlag -> Bool) -> Eq DumpFlag
forall a. (a -> a -> Bool) -> (a -> a -> Bool) -> Eq a
/= :: DumpFlag -> DumpFlag -> Bool
$c/= :: DumpFlag -> DumpFlag -> Bool
== :: DumpFlag -> DumpFlag -> Bool
$c== :: DumpFlag -> DumpFlag -> Bool
Eq, Int -> DumpFlag -> ShowS
[DumpFlag] -> ShowS
DumpFlag -> String
(Int -> DumpFlag -> ShowS)
-> (DumpFlag -> String) -> ([DumpFlag] -> ShowS) -> Show DumpFlag
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
showList :: [DumpFlag] -> ShowS
$cshowList :: [DumpFlag] -> ShowS
show :: DumpFlag -> String
$cshow :: DumpFlag -> String
showsPrec :: Int -> DumpFlag -> ShowS
$cshowsPrec :: Int -> DumpFlag -> ShowS
Show, Int -> DumpFlag
DumpFlag -> Int
DumpFlag -> [DumpFlag]
DumpFlag -> DumpFlag
DumpFlag -> DumpFlag -> [DumpFlag]
DumpFlag -> DumpFlag -> DumpFlag -> [DumpFlag]
(DumpFlag -> DumpFlag)
-> (DumpFlag -> DumpFlag)
-> (Int -> DumpFlag)
-> (DumpFlag -> Int)
-> (DumpFlag -> [DumpFlag])
-> (DumpFlag -> DumpFlag -> [DumpFlag])
-> (DumpFlag -> DumpFlag -> [DumpFlag])
-> (DumpFlag -> DumpFlag -> DumpFlag -> [DumpFlag])
-> Enum DumpFlag
forall a.
(a -> a)
-> (a -> a)
-> (Int -> a)
-> (a -> Int)
-> (a -> [a])
-> (a -> a -> [a])
-> (a -> a -> [a])
-> (a -> a -> a -> [a])
-> Enum a
enumFromThenTo :: DumpFlag -> DumpFlag -> DumpFlag -> [DumpFlag]
$cenumFromThenTo :: DumpFlag -> DumpFlag -> DumpFlag -> [DumpFlag]
enumFromTo :: DumpFlag -> DumpFlag -> [DumpFlag]
$cenumFromTo :: DumpFlag -> DumpFlag -> [DumpFlag]
enumFromThen :: DumpFlag -> DumpFlag -> [DumpFlag]
$cenumFromThen :: DumpFlag -> DumpFlag -> [DumpFlag]
enumFrom :: DumpFlag -> [DumpFlag]
$cenumFrom :: DumpFlag -> [DumpFlag]
fromEnum :: DumpFlag -> Int
$cfromEnum :: DumpFlag -> Int
toEnum :: Int -> DumpFlag
$ctoEnum :: Int -> DumpFlag
pred :: DumpFlag -> DumpFlag
$cpred :: DumpFlag -> DumpFlag
succ :: DumpFlag -> DumpFlag
$csucc :: DumpFlag -> DumpFlag
Enum)


-- | Enumerates the simple on-or-off dynamic flags
data GeneralFlag
-- See Note [Updating flag description in the User's Guide]

   = Opt_DumpToFile                     -- ^ Append dump output to files instead of stdout.
   | Opt_D_faststring_stats
   | Opt_D_dump_minimal_imports
   | Opt_DoCoreLinting
   | Opt_DoStgLinting
   | Opt_DoCmmLinting
   | Opt_DoAsmLinting
   | Opt_DoAnnotationLinting
   | Opt_NoLlvmMangler                  -- hidden flag
   | Opt_FastLlvm                       -- hidden flag
   | Opt_NoTypeableBinds

   | Opt_WarnIsError                    -- -Werror; makes warnings fatal
   | Opt_ShowWarnGroups                 -- Show the group a warning belongs to
   | Opt_HideSourcePaths                -- Hide module source/object paths

   | Opt_PrintExplicitForalls
   | Opt_PrintExplicitKinds
   | Opt_PrintExplicitCoercions
   | Opt_PrintExplicitRuntimeReps
   | Opt_PrintEqualityRelations
   | Opt_PrintAxiomIncomps
   | Opt_PrintUnicodeSyntax
   | Opt_PrintExpandedSynonyms
   | Opt_PrintPotentialInstances
   | Opt_PrintTypecheckerElaboration

   -- optimisation opts
   | Opt_CallArity
   | Opt_Exitification
   | Opt_Strictness
   | Opt_LateDmdAnal                    -- #6087
   | Opt_KillAbsence
   | Opt_KillOneShot
   | Opt_FullLaziness
   | Opt_FloatIn
   | Opt_LateSpecialise
   | Opt_Specialise
   | Opt_SpecialiseAggressively
   | Opt_CrossModuleSpecialise
   | Opt_StaticArgumentTransformation
   | Opt_CSE
   | Opt_StgCSE
   | Opt_StgLiftLams
   | Opt_LiberateCase
   | Opt_SpecConstr
   | Opt_SpecConstrKeen
   | Opt_DoLambdaEtaExpansion
   | Opt_IgnoreAsserts
   | Opt_DoEtaReduction
   | Opt_CaseMerge
   | Opt_CaseFolding                    -- Constant folding through case-expressions
   | Opt_UnboxStrictFields
   | Opt_UnboxSmallStrictFields
   | Opt_DictsCheap
   | Opt_EnableRewriteRules             -- Apply rewrite rules during simplification
   | Opt_EnableThSpliceWarnings         -- Enable warnings for TH splices
   | Opt_RegsGraph                      -- do graph coloring register allocation
   | Opt_RegsIterative                  -- do iterative coalescing graph coloring register allocation
   | Opt_PedanticBottoms                -- Be picky about how we treat bottom
   | Opt_LlvmTBAA                       -- Use LLVM TBAA infastructure for improving AA (hidden flag)
   | Opt_LlvmFillUndefWithGarbage       -- Testing for undef bugs (hidden flag)
   | Opt_IrrefutableTuples
   | Opt_CmmSink
   | Opt_CmmElimCommonBlocks
   | Opt_AsmShortcutting
   | Opt_OmitYields
   | Opt_FunToThunk               -- allow WwLib.mkWorkerArgs to remove all value lambdas
   | Opt_DictsStrict                     -- be strict in argument dictionaries
   | Opt_DmdTxDictSel              -- use a special demand transformer for dictionary selectors
   | Opt_Loopification                  -- See Note [Self-recursive tail calls]
   | Opt_CfgBlocklayout             -- ^ Use the cfg based block layout algorithm.
   | Opt_WeightlessBlocklayout         -- ^ Layout based on last instruction per block.
   | Opt_CprAnal
   | Opt_WorkerWrapper
   | Opt_SolveConstantDicts
   | Opt_AlignmentSanitisation
   | Opt_CatchBottoms
   | Opt_NumConstantFolding

   -- PreInlining is on by default. The option is there just to see how
   -- bad things get if you turn it off!
   | Opt_SimplPreInlining

   -- Interface files
   | Opt_IgnoreInterfacePragmas
   | Opt_OmitInterfacePragmas
   | Opt_ExposeAllUnfoldings
   | Opt_WriteInterface -- forces .hi files to be written even with -fno-code
   | Opt_WriteHie -- generate .hie files

   -- profiling opts
   | Opt_AutoSccsOnIndividualCafs
   | Opt_ProfCountEntries

   -- misc opts
   | Opt_Pp
   | Opt_ForceRecomp
   | Opt_IgnoreOptimChanges
   | Opt_IgnoreHpcChanges
   | Opt_ExcessPrecision
   | Opt_EagerBlackHoling
   | Opt_NoHsMain
   | Opt_SplitSections
   | Opt_StgStats
   | Opt_HideAllPackages
   | Opt_HideAllPluginPackages
   | Opt_PrintBindResult
   | Opt_Haddock
   | Opt_HaddockOptions
   | Opt_BreakOnException
   | Opt_BreakOnError
   | Opt_PrintEvldWithShow
   | Opt_PrintBindContents
   | Opt_GenManifest
   | Opt_EmbedManifest
   | Opt_SharedImplib
   | Opt_BuildingCabalPackage
   | Opt_IgnoreDotGhci
   | Opt_GhciSandbox
   | Opt_GhciHistory
   | Opt_GhciLeakCheck
   | Opt_ValidateHie
   | Opt_LocalGhciHistory
   | Opt_NoIt
   | Opt_HelpfulErrors
   | Opt_DeferTypeErrors
   | Opt_DeferTypedHoles
   | Opt_DeferOutOfScopeVariables
   | Opt_PIC                         -- ^ @-fPIC@
   | Opt_PIE                         -- ^ @-fPIE@
   | Opt_PICExecutable               -- ^ @-pie@
   | Opt_ExternalDynamicRefs
   | Opt_SccProfilingOn
   | Opt_Ticky
   | Opt_Ticky_Allocd
   | Opt_Ticky_LNE
   | Opt_Ticky_Dyn_Thunk
   | Opt_RPath
   | Opt_RelativeDynlibPaths
   | Opt_Hpc
   | Opt_FlatCache
   | Opt_ExternalInterpreter
   | Opt_OptimalApplicativeDo
   | Opt_VersionMacros
   | Opt_WholeArchiveHsLibs
   -- copy all libs into a single folder prior to linking binaries
   -- this should elivate the excessive command line limit restrictions
   -- on windows, by only requiring a single -L argument instead of
   -- one for each dependency.  At the time of this writing, gcc
   -- forwards all -L flags to the collect2 command without using a
   -- response file and as such breaking apart.
   | Opt_SingleLibFolder
   | Opt_KeepCAFs
   | Opt_KeepGoing
   | Opt_ByteCode

   -- output style opts
   | Opt_ErrorSpans -- Include full span info in error messages,
                    -- instead of just the start position.
   | Opt_DeferDiagnostics
   | Opt_DiagnosticsShowCaret -- Show snippets of offending code
   | Opt_PprCaseAsLet
   | Opt_PprShowTicks
   | Opt_ShowHoleConstraints
    -- Options relating to the display of valid hole fits
    -- when generating an error message for a typed hole
    -- See Note [Valid hole fits include] in TcHoleErrors.hs
   | Opt_ShowValidHoleFits
   | Opt_SortValidHoleFits
   | Opt_SortBySizeHoleFits
   | Opt_SortBySubsumHoleFits
   | Opt_AbstractRefHoleFits
   | Opt_UnclutterValidHoleFits
   | Opt_ShowTypeAppOfHoleFits
   | Opt_ShowTypeAppVarsOfHoleFits
   | Opt_ShowDocsOfHoleFits
   | Opt_ShowTypeOfHoleFits
   | Opt_ShowProvOfHoleFits
   | Opt_ShowMatchesOfHoleFits

   | Opt_ShowLoadedModules
   | Opt_HexWordLiterals -- See Note [Print Hexadecimal Literals]

   -- Suppress all coercions, them replacing with '...'
   | Opt_SuppressCoercions
   | Opt_SuppressVarKinds
   -- Suppress module id prefixes on variables.
   | Opt_SuppressModulePrefixes
   -- Suppress type applications.
   | Opt_SuppressTypeApplications
   -- Suppress info such as arity and unfoldings on identifiers.
   | Opt_SuppressIdInfo
   -- Suppress separate type signatures in core, but leave types on
   -- lambda bound vars
   | Opt_SuppressUnfoldings
   -- Suppress the details of even stable unfoldings
   | Opt_SuppressTypeSignatures
   -- Suppress unique ids on variables.
   -- Except for uniques, as some simplifier phases introduce new
   -- variables that have otherwise identical names.
   | Opt_SuppressUniques
   | Opt_SuppressStgExts
   | Opt_SuppressTicks     -- Replaces Opt_PprShowTicks
   | Opt_SuppressTimestamps -- ^ Suppress timestamps in dumps

   -- temporary flags
   | Opt_AutoLinkPackages
   | Opt_ImplicitImportQualified

   -- keeping stuff
   | Opt_KeepHscppFiles
   | Opt_KeepHiDiffs
   | Opt_KeepHcFiles
   | Opt_KeepSFiles
   | Opt_KeepTmpFiles
   | Opt_KeepRawTokenStream
   | Opt_KeepLlvmFiles
   | Opt_KeepHiFiles
   | Opt_KeepOFiles

   | Opt_BuildDynamicToo

   -- safe haskell flags
   | Opt_DistrustAllPackages
   | Opt_PackageTrust
   | Opt_PluginTrustworthy

   | Opt_G_NoStateHack
   | Opt_G_NoOptCoercion
   deriving (GeneralFlag -> GeneralFlag -> Bool
(GeneralFlag -> GeneralFlag -> Bool)
-> (GeneralFlag -> GeneralFlag -> Bool) -> Eq GeneralFlag
forall a. (a -> a -> Bool) -> (a -> a -> Bool) -> Eq a
/= :: GeneralFlag -> GeneralFlag -> Bool
$c/= :: GeneralFlag -> GeneralFlag -> Bool
== :: GeneralFlag -> GeneralFlag -> Bool
$c== :: GeneralFlag -> GeneralFlag -> Bool
Eq, Int -> GeneralFlag -> ShowS
[GeneralFlag] -> ShowS
GeneralFlag -> String
(Int -> GeneralFlag -> ShowS)
-> (GeneralFlag -> String)
-> ([GeneralFlag] -> ShowS)
-> Show GeneralFlag
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
showList :: [GeneralFlag] -> ShowS
$cshowList :: [GeneralFlag] -> ShowS
show :: GeneralFlag -> String
$cshow :: GeneralFlag -> String
showsPrec :: Int -> GeneralFlag -> ShowS
$cshowsPrec :: Int -> GeneralFlag -> ShowS
Show, Int -> GeneralFlag
GeneralFlag -> Int
GeneralFlag -> [GeneralFlag]
GeneralFlag -> GeneralFlag
GeneralFlag -> GeneralFlag -> [GeneralFlag]
GeneralFlag -> GeneralFlag -> GeneralFlag -> [GeneralFlag]
(GeneralFlag -> GeneralFlag)
-> (GeneralFlag -> GeneralFlag)
-> (Int -> GeneralFlag)
-> (GeneralFlag -> Int)
-> (GeneralFlag -> [GeneralFlag])
-> (GeneralFlag -> GeneralFlag -> [GeneralFlag])
-> (GeneralFlag -> GeneralFlag -> [GeneralFlag])
-> (GeneralFlag -> GeneralFlag -> GeneralFlag -> [GeneralFlag])
-> Enum GeneralFlag
forall a.
(a -> a)
-> (a -> a)
-> (Int -> a)
-> (a -> Int)
-> (a -> [a])
-> (a -> a -> [a])
-> (a -> a -> [a])
-> (a -> a -> a -> [a])
-> Enum a
enumFromThenTo :: GeneralFlag -> GeneralFlag -> GeneralFlag -> [GeneralFlag]
$cenumFromThenTo :: GeneralFlag -> GeneralFlag -> GeneralFlag -> [GeneralFlag]
enumFromTo :: GeneralFlag -> GeneralFlag -> [GeneralFlag]
$cenumFromTo :: GeneralFlag -> GeneralFlag -> [GeneralFlag]
enumFromThen :: GeneralFlag -> GeneralFlag -> [GeneralFlag]
$cenumFromThen :: GeneralFlag -> GeneralFlag -> [GeneralFlag]
enumFrom :: GeneralFlag -> [GeneralFlag]
$cenumFrom :: GeneralFlag -> [GeneralFlag]
fromEnum :: GeneralFlag -> Int
$cfromEnum :: GeneralFlag -> Int
toEnum :: Int -> GeneralFlag
$ctoEnum :: Int -> GeneralFlag
pred :: GeneralFlag -> GeneralFlag
$cpred :: GeneralFlag -> GeneralFlag
succ :: GeneralFlag -> GeneralFlag
$csucc :: GeneralFlag -> GeneralFlag
Enum)

-- Check whether a flag should be considered an "optimisation flag"
-- for purposes of recompilation avoidance (see
-- Note [Ignoring some flag changes] in FlagChecker). Being listed here is
-- not a guarantee that the flag has no other effect. We could, and
-- perhaps should, separate out the flags that have some minor impact on
-- program semantics and/or error behavior (e.g., assertions), but
-- then we'd need to go to extra trouble (and an additional flag)
-- to allow users to ignore the optimisation level even though that
-- means ignoring some change.
optimisationFlags :: EnumSet GeneralFlag
optimisationFlags :: EnumSet GeneralFlag
optimisationFlags = [GeneralFlag] -> EnumSet GeneralFlag
forall a. Enum a => [a] -> EnumSet a
EnumSet.fromList
   [ GeneralFlag
Opt_CallArity
   , GeneralFlag
Opt_Strictness
   , GeneralFlag
Opt_LateDmdAnal
   , GeneralFlag
Opt_KillAbsence
   , GeneralFlag
Opt_KillOneShot
   , GeneralFlag
Opt_FullLaziness
   , GeneralFlag
Opt_FloatIn
   , GeneralFlag
Opt_LateSpecialise
   , GeneralFlag
Opt_Specialise
   , GeneralFlag
Opt_SpecialiseAggressively
   , GeneralFlag
Opt_CrossModuleSpecialise
   , GeneralFlag
Opt_StaticArgumentTransformation
   , GeneralFlag
Opt_CSE
   , GeneralFlag
Opt_StgCSE
   , GeneralFlag
Opt_StgLiftLams
   , GeneralFlag
Opt_LiberateCase
   , GeneralFlag
Opt_SpecConstr
   , GeneralFlag
Opt_SpecConstrKeen
   , GeneralFlag
Opt_DoLambdaEtaExpansion
   , GeneralFlag
Opt_IgnoreAsserts
   , GeneralFlag
Opt_DoEtaReduction
   , GeneralFlag
Opt_CaseMerge
   , GeneralFlag
Opt_CaseFolding
   , GeneralFlag
Opt_UnboxStrictFields
   , GeneralFlag
Opt_UnboxSmallStrictFields
   , GeneralFlag
Opt_DictsCheap
   , GeneralFlag
Opt_EnableRewriteRules
   , GeneralFlag
Opt_RegsGraph
   , GeneralFlag
Opt_RegsIterative
   , GeneralFlag
Opt_PedanticBottoms
   , GeneralFlag
Opt_LlvmTBAA
   , GeneralFlag
Opt_LlvmFillUndefWithGarbage
   , GeneralFlag
Opt_IrrefutableTuples
   , GeneralFlag
Opt_CmmSink
   , GeneralFlag
Opt_CmmElimCommonBlocks
   , GeneralFlag
Opt_AsmShortcutting
   , GeneralFlag
Opt_OmitYields
   , GeneralFlag
Opt_FunToThunk
   , GeneralFlag
Opt_DictsStrict
   , GeneralFlag
Opt_DmdTxDictSel
   , GeneralFlag
Opt_Loopification
   , GeneralFlag
Opt_CfgBlocklayout
   , GeneralFlag
Opt_WeightlessBlocklayout
   , GeneralFlag
Opt_CprAnal
   , GeneralFlag
Opt_WorkerWrapper
   , GeneralFlag
Opt_SolveConstantDicts
   , GeneralFlag
Opt_CatchBottoms
   , GeneralFlag
Opt_IgnoreAsserts
   ]

-- | Used when outputting warnings: if a reason is given, it is
-- displayed. If a warning isn't controlled by a flag, this is made
-- explicit at the point of use.
data WarnReason
  = NoReason
  -- | Warning was enabled with the flag
  | Reason !WarningFlag
  -- | Warning was made an error because of -Werror or -Werror=WarningFlag
  | ErrReason !(Maybe WarningFlag)
  deriving Int -> WarnReason -> ShowS
[WarnReason] -> ShowS
WarnReason -> String
(Int -> WarnReason -> ShowS)
-> (WarnReason -> String)
-> ([WarnReason] -> ShowS)
-> Show WarnReason
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
showList :: [WarnReason] -> ShowS
$cshowList :: [WarnReason] -> ShowS
show :: WarnReason -> String
$cshow :: WarnReason -> String
showsPrec :: Int -> WarnReason -> ShowS
$cshowsPrec :: Int -> WarnReason -> ShowS
Show

-- | Used to differentiate the scope an include needs to apply to.
-- We have to split the include paths to avoid accidentally forcing recursive
-- includes since -I overrides the system search paths. See #14312.
data IncludeSpecs
  = IncludeSpecs { IncludeSpecs -> [String]
includePathsQuote  :: [String]
                 , IncludeSpecs -> [String]
includePathsGlobal :: [String]
                 }
  deriving Int -> IncludeSpecs -> ShowS
[IncludeSpecs] -> ShowS
IncludeSpecs -> String
(Int -> IncludeSpecs -> ShowS)
-> (IncludeSpecs -> String)
-> ([IncludeSpecs] -> ShowS)
-> Show IncludeSpecs
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
showList :: [IncludeSpecs] -> ShowS
$cshowList :: [IncludeSpecs] -> ShowS
show :: IncludeSpecs -> String
$cshow :: IncludeSpecs -> String
showsPrec :: Int -> IncludeSpecs -> ShowS
$cshowsPrec :: Int -> IncludeSpecs -> ShowS
Show

-- | Append to the list of includes a path that shall be included using `-I`
-- when the C compiler is called. These paths override system search paths.
addGlobalInclude :: IncludeSpecs -> [String] -> IncludeSpecs
addGlobalInclude :: IncludeSpecs -> [String] -> IncludeSpecs
addGlobalInclude IncludeSpecs
spec [String]
paths  = let f :: [String]
f = IncludeSpecs -> [String]
includePathsGlobal IncludeSpecs
spec
                               in IncludeSpecs
spec { includePathsGlobal :: [String]
includePathsGlobal = [String]
f [String] -> [String] -> [String]
forall a. [a] -> [a] -> [a]
++ [String]
paths }

-- | Append to the list of includes a path that shall be included using
-- `-iquote` when the C compiler is called. These paths only apply when quoted
-- includes are used. e.g. #include "foo.h"
addQuoteInclude :: IncludeSpecs -> [String] -> IncludeSpecs
addQuoteInclude :: IncludeSpecs -> [String] -> IncludeSpecs
addQuoteInclude IncludeSpecs
spec [String]
paths  = let f :: [String]
f = IncludeSpecs -> [String]
includePathsQuote IncludeSpecs
spec
                              in IncludeSpecs
spec { includePathsQuote :: [String]
includePathsQuote = [String]
f [String] -> [String] -> [String]
forall a. [a] -> [a] -> [a]
++ [String]
paths }

-- | Concatenate and flatten the list of global and quoted includes returning
-- just a flat list of paths.
flattenIncludes :: IncludeSpecs -> [String]
flattenIncludes :: IncludeSpecs -> [String]
flattenIncludes IncludeSpecs
specs = IncludeSpecs -> [String]
includePathsQuote IncludeSpecs
specs [String] -> [String] -> [String]
forall a. [a] -> [a] -> [a]
++ IncludeSpecs -> [String]
includePathsGlobal IncludeSpecs
specs

instance Outputable WarnReason where
  ppr :: WarnReason -> SDoc
ppr = String -> SDoc
text (String -> SDoc) -> (WarnReason -> String) -> WarnReason -> SDoc
forall b c a. (b -> c) -> (a -> b) -> a -> c
. WarnReason -> String
forall a. Show a => a -> String
show

instance ToJson WarnReason where
  json :: WarnReason -> JsonDoc
json WarnReason
NoReason = JsonDoc
JSNull
  json (Reason WarningFlag
wf) = String -> JsonDoc
JSString (WarningFlag -> String
forall a. Show a => a -> String
show WarningFlag
wf)
  json (ErrReason Maybe WarningFlag
Nothing) = String -> JsonDoc
JSString String
"Opt_WarnIsError"
  json (ErrReason (Just WarningFlag
wf)) = String -> JsonDoc
JSString (WarningFlag -> String
forall a. Show a => a -> String
show WarningFlag
wf)

data WarningFlag =
-- See Note [Updating flag description in the User's Guide]
     Opt_WarnDuplicateExports
   | Opt_WarnDuplicateConstraints
   | Opt_WarnRedundantConstraints
   | Opt_WarnHiShadows
   | Opt_WarnImplicitPrelude
   | Opt_WarnIncompletePatterns
   | Opt_WarnIncompleteUniPatterns
   | Opt_WarnIncompletePatternsRecUpd
   | Opt_WarnOverflowedLiterals
   | Opt_WarnEmptyEnumerations
   | Opt_WarnMissingFields
   | Opt_WarnMissingImportList
   | Opt_WarnMissingMethods
   | Opt_WarnMissingSignatures
   | Opt_WarnMissingLocalSignatures
   | Opt_WarnNameShadowing
   | Opt_WarnOverlappingPatterns
   | Opt_WarnTypeDefaults
   | Opt_WarnMonomorphism
   | Opt_WarnUnusedTopBinds
   | Opt_WarnUnusedLocalBinds
   | Opt_WarnUnusedPatternBinds
   | Opt_WarnUnusedImports
   | Opt_WarnUnusedMatches
   | Opt_WarnUnusedTypePatterns
   | Opt_WarnUnusedForalls
   | Opt_WarnUnusedRecordWildcards
   | Opt_WarnRedundantRecordWildcards
   | Opt_WarnWarningsDeprecations
   | Opt_WarnDeprecatedFlags
   | Opt_WarnMissingMonadFailInstances -- since 8.0
   | Opt_WarnSemigroup -- since 8.0
   | Opt_WarnDodgyExports
   | Opt_WarnDodgyImports
   | Opt_WarnOrphans
   | Opt_WarnAutoOrphans
   | Opt_WarnIdentities
   | Opt_WarnTabs
   | Opt_WarnUnrecognisedPragmas
   | Opt_WarnDodgyForeignImports
   | Opt_WarnUnusedDoBind
   | Opt_WarnWrongDoBind
   | Opt_WarnAlternativeLayoutRuleTransitional
   | Opt_WarnUnsafe
   | Opt_WarnSafe
   | Opt_WarnTrustworthySafe
   | Opt_WarnMissedSpecs
   | Opt_WarnAllMissedSpecs
   | Opt_WarnUnsupportedCallingConventions
   | Opt_WarnUnsupportedLlvmVersion
   | Opt_WarnMissedExtraSharedLib
   | Opt_WarnInlineRuleShadowing
   | Opt_WarnTypedHoles
   | Opt_WarnPartialTypeSignatures
   | Opt_WarnMissingExportedSignatures
   | Opt_WarnUntickedPromotedConstructors
   | Opt_WarnDerivingTypeable
   | Opt_WarnDeferredTypeErrors
   | Opt_WarnDeferredOutOfScopeVariables
   | Opt_WarnNonCanonicalMonadInstances   -- since 8.0
   | Opt_WarnNonCanonicalMonadFailInstances   -- since 8.0, removed 8.8
   | Opt_WarnNonCanonicalMonoidInstances  -- since 8.0
   | Opt_WarnMissingPatternSynonymSignatures -- since 8.0
   | Opt_WarnUnrecognisedWarningFlags     -- since 8.0
   | Opt_WarnSimplifiableClassConstraints -- Since 8.2
   | Opt_WarnCPPUndef                     -- Since 8.2
   | Opt_WarnUnbangedStrictPatterns       -- Since 8.2
   | Opt_WarnMissingHomeModules           -- Since 8.2
   | Opt_WarnPartialFields                -- Since 8.4
   | Opt_WarnMissingExportList
   | Opt_WarnInaccessibleCode
   | Opt_WarnStarIsType                   -- Since 8.6
   | Opt_WarnStarBinder                   -- Since 8.6
   | Opt_WarnImplicitKindVars             -- Since 8.6
   | Opt_WarnSpaceAfterBang
   | Opt_WarnMissingDerivingStrategies    -- Since 8.8
   | Opt_WarnPrepositiveQualifiedModule   -- Since TBD
   | Opt_WarnUnusedPackages               -- Since 8.10
   | Opt_WarnInferredSafeImports          -- Since 8.10
   | Opt_WarnMissingSafeHaskellMode       -- Since 8.10
   | Opt_WarnCompatUnqualifiedImports     -- Since 8.10
   | Opt_WarnDerivingDefaults
   deriving (WarningFlag -> WarningFlag -> Bool
(WarningFlag -> WarningFlag -> Bool)
-> (WarningFlag -> WarningFlag -> Bool) -> Eq WarningFlag
forall a. (a -> a -> Bool) -> (a -> a -> Bool) -> Eq a
/= :: WarningFlag -> WarningFlag -> Bool
$c/= :: WarningFlag -> WarningFlag -> Bool
== :: WarningFlag -> WarningFlag -> Bool
$c== :: WarningFlag -> WarningFlag -> Bool
Eq, Int -> WarningFlag -> ShowS
[WarningFlag] -> ShowS
WarningFlag -> String
(Int -> WarningFlag -> ShowS)
-> (WarningFlag -> String)
-> ([WarningFlag] -> ShowS)
-> Show WarningFlag
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
showList :: [WarningFlag] -> ShowS
$cshowList :: [WarningFlag] -> ShowS
show :: WarningFlag -> String
$cshow :: WarningFlag -> String
showsPrec :: Int -> WarningFlag -> ShowS
$cshowsPrec :: Int -> WarningFlag -> ShowS
Show, Int -> WarningFlag
WarningFlag -> Int
WarningFlag -> [WarningFlag]
WarningFlag -> WarningFlag
WarningFlag -> WarningFlag -> [WarningFlag]
WarningFlag -> WarningFlag -> WarningFlag -> [WarningFlag]
(WarningFlag -> WarningFlag)
-> (WarningFlag -> WarningFlag)
-> (Int -> WarningFlag)
-> (WarningFlag -> Int)
-> (WarningFlag -> [WarningFlag])
-> (WarningFlag -> WarningFlag -> [WarningFlag])
-> (WarningFlag -> WarningFlag -> [WarningFlag])
-> (WarningFlag -> WarningFlag -> WarningFlag -> [WarningFlag])
-> Enum WarningFlag
forall a.
(a -> a)
-> (a -> a)
-> (Int -> a)
-> (a -> Int)
-> (a -> [a])
-> (a -> a -> [a])
-> (a -> a -> [a])
-> (a -> a -> a -> [a])
-> Enum a
enumFromThenTo :: WarningFlag -> WarningFlag -> WarningFlag -> [WarningFlag]
$cenumFromThenTo :: WarningFlag -> WarningFlag -> WarningFlag -> [WarningFlag]
enumFromTo :: WarningFlag -> WarningFlag -> [WarningFlag]
$cenumFromTo :: WarningFlag -> WarningFlag -> [WarningFlag]
enumFromThen :: WarningFlag -> WarningFlag -> [WarningFlag]
$cenumFromThen :: WarningFlag -> WarningFlag -> [WarningFlag]
enumFrom :: WarningFlag -> [WarningFlag]
$cenumFrom :: WarningFlag -> [WarningFlag]
fromEnum :: WarningFlag -> Int
$cfromEnum :: WarningFlag -> Int
toEnum :: Int -> WarningFlag
$ctoEnum :: Int -> WarningFlag
pred :: WarningFlag -> WarningFlag
$cpred :: WarningFlag -> WarningFlag
succ :: WarningFlag -> WarningFlag
$csucc :: WarningFlag -> WarningFlag
Enum)

data Language = Haskell98 | Haskell2010
   deriving (Language -> Language -> Bool
(Language -> Language -> Bool)
-> (Language -> Language -> Bool) -> Eq Language
forall a. (a -> a -> Bool) -> (a -> a -> Bool) -> Eq a
/= :: Language -> Language -> Bool
$c/= :: Language -> Language -> Bool
== :: Language -> Language -> Bool
$c== :: Language -> Language -> Bool
Eq, Int -> Language
Language -> Int
Language -> [Language]
Language -> Language
Language -> Language -> [Language]
Language -> Language -> Language -> [Language]
(Language -> Language)
-> (Language -> Language)
-> (Int -> Language)
-> (Language -> Int)
-> (Language -> [Language])
-> (Language -> Language -> [Language])
-> (Language -> Language -> [Language])
-> (Language -> Language -> Language -> [Language])
-> Enum Language
forall a.
(a -> a)
-> (a -> a)
-> (Int -> a)
-> (a -> Int)
-> (a -> [a])
-> (a -> a -> [a])
-> (a -> a -> [a])
-> (a -> a -> a -> [a])
-> Enum a
enumFromThenTo :: Language -> Language -> Language -> [Language]
$cenumFromThenTo :: Language -> Language -> Language -> [Language]
enumFromTo :: Language -> Language -> [Language]
$cenumFromTo :: Language -> Language -> [Language]
enumFromThen :: Language -> Language -> [Language]
$cenumFromThen :: Language -> Language -> [Language]
enumFrom :: Language -> [Language]
$cenumFrom :: Language -> [Language]
fromEnum :: Language -> Int
$cfromEnum :: Language -> Int
toEnum :: Int -> Language
$ctoEnum :: Int -> Language
pred :: Language -> Language
$cpred :: Language -> Language
succ :: Language -> Language
$csucc :: Language -> Language
Enum, Int -> Language -> ShowS
[Language] -> ShowS
Language -> String
(Int -> Language -> ShowS)
-> (Language -> String) -> ([Language] -> ShowS) -> Show Language
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
showList :: [Language] -> ShowS
$cshowList :: [Language] -> ShowS
show :: Language -> String
$cshow :: Language -> String
showsPrec :: Int -> Language -> ShowS
$cshowsPrec :: Int -> Language -> ShowS
Show)

instance Outputable Language where
    ppr :: Language -> SDoc
ppr = String -> SDoc
text (String -> SDoc) -> (Language -> String) -> Language -> SDoc
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Language -> String
forall a. Show a => a -> String
show

-- | The various Safe Haskell modes
data SafeHaskellMode
   = Sf_None          -- ^ inferred unsafe
   | Sf_Unsafe        -- ^ declared and checked
   | Sf_Trustworthy   -- ^ declared and checked
   | Sf_Safe          -- ^ declared and checked
   | Sf_SafeInferred  -- ^ inferred as safe
   | Sf_Ignore        -- ^ @-fno-safe-haskell@ state
   deriving (SafeHaskellMode -> SafeHaskellMode -> Bool
(SafeHaskellMode -> SafeHaskellMode -> Bool)
-> (SafeHaskellMode -> SafeHaskellMode -> Bool)
-> Eq SafeHaskellMode
forall a. (a -> a -> Bool) -> (a -> a -> Bool) -> Eq a
/= :: SafeHaskellMode -> SafeHaskellMode -> Bool
$c/= :: SafeHaskellMode -> SafeHaskellMode -> Bool
== :: SafeHaskellMode -> SafeHaskellMode -> Bool
$c== :: SafeHaskellMode -> SafeHaskellMode -> Bool
Eq)

instance Show SafeHaskellMode where
    show :: SafeHaskellMode -> String
show SafeHaskellMode
Sf_None         = String
"None"
    show SafeHaskellMode
Sf_Unsafe       = String
"Unsafe"
    show SafeHaskellMode
Sf_Trustworthy  = String
"Trustworthy"
    show SafeHaskellMode
Sf_Safe         = String
"Safe"
    show SafeHaskellMode
Sf_SafeInferred = String
"Safe-Inferred"
    show SafeHaskellMode
Sf_Ignore       = String
"Ignore"

instance Outputable SafeHaskellMode where
    ppr :: SafeHaskellMode -> SDoc
ppr = String -> SDoc
text (String -> SDoc)
-> (SafeHaskellMode -> String) -> SafeHaskellMode -> SDoc
forall b c a. (b -> c) -> (a -> b) -> a -> c
. SafeHaskellMode -> String
forall a. Show a => a -> String
show

-- | Contains not only a collection of 'GeneralFlag's but also a plethora of
-- information relating to the compilation of a single file or GHC session
data DynFlags = DynFlags {
  DynFlags -> GhcMode
ghcMode               :: GhcMode,
  DynFlags -> GhcLink
ghcLink               :: GhcLink,
  DynFlags -> HscTarget
hscTarget             :: HscTarget,

  -- formerly Settings
  DynFlags -> GhcNameVersion
ghcNameVersion    :: {-# UNPACK #-} !GhcNameVersion,
  DynFlags -> FileSettings
fileSettings      :: {-# UNPACK #-} !FileSettings,
  DynFlags -> Platform
targetPlatform    :: Platform,       -- Filled in by SysTools
  DynFlags -> ToolSettings
toolSettings      :: {-# UNPACK #-} !ToolSettings,
  DynFlags -> PlatformMisc
platformMisc      :: {-# UNPACK #-} !PlatformMisc,
  DynFlags -> PlatformConstants
platformConstants :: PlatformConstants,
  DynFlags -> [(String, String)]
rawSettings       :: [(String, String)],

  DynFlags -> IntegerLibrary
integerLibrary        :: IntegerLibrary,
    -- ^ IntegerGMP or IntegerSimple. Set at configure time, but may be overriden
    --   by GHC-API users. See Note [The integer library] in PrelNames
  DynFlags -> LlvmConfig
llvmConfig            :: LlvmConfig,
    -- ^ N.B. It's important that this field is lazy since we load the LLVM
    -- configuration lazily. See Note [LLVM Configuration] in SysTools.
  DynFlags -> Int
verbosity             :: Int,         -- ^ Verbosity level: see Note [Verbosity levels]
  DynFlags -> Int
optLevel              :: Int,         -- ^ Optimisation level
  DynFlags -> Int
debugLevel            :: Int,         -- ^ How much debug information to produce
  DynFlags -> Int
simplPhases           :: Int,         -- ^ Number of simplifier phases
  DynFlags -> Int
maxSimplIterations    :: Int,         -- ^ Max simplifier iterations
  DynFlags -> Maybe String
ruleCheck             :: Maybe String,
  DynFlags -> Maybe String
inlineCheck           :: Maybe String, -- ^ A prefix to report inlining decisions about
  DynFlags -> [Int]
strictnessBefore      :: [Int],       -- ^ Additional demand analysis

  DynFlags -> Maybe Int
parMakeCount          :: Maybe Int,   -- ^ The number of modules to compile in parallel
                                        --   in --make mode, where Nothing ==> compile as
                                        --   many in parallel as there are CPUs.

  DynFlags -> Bool
enableTimeStats       :: Bool,        -- ^ Enable RTS timing statistics?
  DynFlags -> Maybe Int
ghcHeapSize           :: Maybe Int,   -- ^ The heap size to set.

  DynFlags -> Maybe Int
maxRelevantBinds      :: Maybe Int,   -- ^ Maximum number of bindings from the type envt
                                        --   to show in type error messages
  DynFlags -> Maybe Int
maxValidHoleFits      :: Maybe Int,   -- ^ Maximum number of hole fits to show
                                        --   in typed hole error messages
  DynFlags -> Maybe Int
maxRefHoleFits        :: Maybe Int,   -- ^ Maximum number of refinement hole
                                        --   fits to show in typed hole error
                                        --   messages
  DynFlags -> Maybe Int
refLevelHoleFits      :: Maybe Int,   -- ^ Maximum level of refinement for
                                        --   refinement hole fits in typed hole
                                        --   error messages
  DynFlags -> Int
maxUncoveredPatterns  :: Int,         -- ^ Maximum number of unmatched patterns to show
                                        --   in non-exhaustiveness warnings
  DynFlags -> Int
maxPmCheckModels      :: Int,         -- ^ Soft limit on the number of models
                                        --   the pattern match checker checks
                                        --   a pattern against. A safe guard
                                        --   against exponential blow-up.
  DynFlags -> Int
simplTickFactor       :: Int,         -- ^ Multiplier for simplifier ticks
  DynFlags -> Maybe Int
specConstrThreshold   :: Maybe Int,   -- ^ Threshold for SpecConstr
  DynFlags -> Maybe Int
specConstrCount       :: Maybe Int,   -- ^ Max number of specialisations for any one function
  DynFlags -> Int
specConstrRecursive   :: Int,         -- ^ Max number of specialisations for recursive types
                                        --   Not optional; otherwise ForceSpecConstr can diverge.
  DynFlags -> Word
binBlobThreshold      :: Word,        -- ^ Binary literals (e.g. strings) whose size is above
                                        --   this threshold will be dumped in a binary file
                                        --   by the assembler code generator (0 to disable)
  DynFlags -> Maybe Int
liberateCaseThreshold :: Maybe Int,   -- ^ Threshold for LiberateCase
  DynFlags -> Maybe Int
floatLamArgs          :: Maybe Int,   -- ^ Arg count for lambda floating
                                        --   See CoreMonad.FloatOutSwitches

  DynFlags -> Maybe Int
liftLamsRecArgs       :: Maybe Int,   -- ^ Maximum number of arguments after lambda lifting a
                                        --   recursive function.
  DynFlags -> Maybe Int
liftLamsNonRecArgs    :: Maybe Int,   -- ^ Maximum number of arguments after lambda lifting a
                                        --   non-recursive function.
  DynFlags -> Bool
liftLamsKnown         :: Bool,        -- ^ Lambda lift even when this turns a known call
                                        --   into an unknown call.

  DynFlags -> Maybe Int
cmmProcAlignment      :: Maybe Int,   -- ^ Align Cmm functions at this boundary or use default.

  DynFlags -> Int
historySize           :: Int,         -- ^ Simplification history size

  DynFlags -> [String]
importPaths           :: [FilePath],
  DynFlags -> Module
mainModIs             :: Module,
  DynFlags -> Maybe String
mainFunIs             :: Maybe String,
  DynFlags -> IntWithInf
reductionDepth        :: IntWithInf,   -- ^ Typechecker maximum stack depth
  DynFlags -> IntWithInf
solverIterations      :: IntWithInf,   -- ^ Number of iterations in the constraints solver
                                         --   Typically only 1 is needed

  DynFlags -> InstalledUnitId
thisInstalledUnitId   :: InstalledUnitId,
  DynFlags -> Maybe ComponentId
thisComponentId_      :: Maybe ComponentId,
  DynFlags -> Maybe [(ModuleName, Module)]
thisUnitIdInsts_      :: Maybe [(ModuleName, Module)],

  -- ways
  DynFlags -> [Way]
ways                  :: [Way],       -- ^ Way flags from the command line
  DynFlags -> String
buildTag              :: String,      -- ^ The global \"way\" (e.g. \"p\" for prof)

  -- For object splitting
  DynFlags -> Maybe (String, Int)
splitInfo             :: Maybe (String,Int),

  -- paths etc.
  DynFlags -> Maybe String
objectDir             :: Maybe String,
  DynFlags -> Maybe String
dylibInstallName      :: Maybe String,
  DynFlags -> Maybe String
hiDir                 :: Maybe String,
  DynFlags -> Maybe String
hieDir                :: Maybe String,
  DynFlags -> Maybe String
stubDir               :: Maybe String,
  DynFlags -> Maybe String
dumpDir               :: Maybe String,

  DynFlags -> String
objectSuf             :: String,
  DynFlags -> String
hcSuf                 :: String,
  DynFlags -> String
hiSuf                 :: String,
  DynFlags -> String
hieSuf                :: String,

  DynFlags -> IORef Bool
canGenerateDynamicToo :: IORef Bool,
  DynFlags -> String
dynObjectSuf          :: String,
  DynFlags -> String
dynHiSuf              :: String,

  DynFlags -> Maybe String
outputFile            :: Maybe String,
  DynFlags -> Maybe String
dynOutputFile         :: Maybe String,
  DynFlags -> Maybe String
outputHi              :: Maybe String,
  DynFlags -> DynLibLoader
dynLibLoader          :: DynLibLoader,

  -- | This is set by 'DriverPipeline.runPipeline' based on where
  --    its output is going.
  DynFlags -> Maybe String
dumpPrefix            :: Maybe FilePath,

  -- | Override the 'dumpPrefix' set by 'DriverPipeline.runPipeline'.
  --    Set by @-ddump-file-prefix@
  DynFlags -> Maybe String
dumpPrefixForce       :: Maybe FilePath,

  DynFlags -> [Option]
ldInputs              :: [Option],

  DynFlags -> IncludeSpecs
includePaths          :: IncludeSpecs,
  DynFlags -> [String]
libraryPaths          :: [String],
  DynFlags -> [String]
frameworkPaths        :: [String],    -- used on darwin only
  DynFlags -> [String]
cmdlineFrameworks     :: [String],    -- ditto

  DynFlags -> Maybe String
rtsOpts               :: Maybe String,
  DynFlags -> RtsOptsEnabled
rtsOptsEnabled        :: RtsOptsEnabled,
  DynFlags -> Bool
rtsOptsSuggestions    :: Bool,

  DynFlags -> String
hpcDir                :: String,      -- ^ Path to store the .mix files

  -- Plugins
  DynFlags -> [ModuleName]
pluginModNames        :: [ModuleName],
  DynFlags -> [(ModuleName, String)]
pluginModNameOpts     :: [(ModuleName,String)],
  DynFlags -> [String]
frontendPluginOpts    :: [String],
    -- ^ the @-ffrontend-opt@ flags given on the command line, in *reverse*
    -- order that they're specified on the command line.
  DynFlags -> [LoadedPlugin]
cachedPlugins         :: [LoadedPlugin],
    -- ^ plugins dynamically loaded after processing arguments. What will be
    -- loaded here is directed by pluginModNames. Arguments are loaded from
    -- pluginModNameOpts. The purpose of this field is to cache the plugins so
    -- they don't have to be loaded each time they are needed.  See
    -- 'DynamicLoading.initializePlugins'.
  DynFlags -> [StaticPlugin]
staticPlugins            :: [StaticPlugin],
    -- ^ staic plugins which do not need dynamic loading. These plugins are
    -- intended to be added by GHC API users directly to this list.
    --
    -- To add dynamically loaded plugins through the GHC API see
    -- 'addPluginModuleName' instead.

  -- GHC API hooks
  DynFlags -> Hooks
hooks                 :: Hooks,

  --  For ghc -M
  DynFlags -> String
depMakefile           :: FilePath,
  DynFlags -> Bool
depIncludePkgDeps     :: Bool,
  DynFlags -> Bool
depIncludeCppDeps     :: Bool,
  DynFlags -> [ModuleName]
depExcludeMods        :: [ModuleName],
  DynFlags -> [String]
depSuffixes           :: [String],

  --  Package flags
  DynFlags -> [PackageDBFlag]
packageDBFlags        :: [PackageDBFlag],
        -- ^ The @-package-db@ flags given on the command line, In
        -- *reverse* order that they're specified on the command line.
        -- This is intended to be applied with the list of "initial"
        -- package databases derived from @GHC_PACKAGE_PATH@; see
        -- 'getPackageConfRefs'.

  DynFlags -> [IgnorePackageFlag]
ignorePackageFlags    :: [IgnorePackageFlag],
        -- ^ The @-ignore-package@ flags from the command line.
        -- In *reverse* order that they're specified on the command line.
  DynFlags -> [PackageFlag]
packageFlags          :: [PackageFlag],
        -- ^ The @-package@ and @-hide-package@ flags from the command-line.
        -- In *reverse* order that they're specified on the command line.
  DynFlags -> [PackageFlag]
pluginPackageFlags    :: [PackageFlag],
        -- ^ The @-plugin-package-id@ flags from command line.
        -- In *reverse* order that they're specified on the command line.
  DynFlags -> [TrustFlag]
trustFlags            :: [TrustFlag],
        -- ^ The @-trust@ and @-distrust@ flags.
        -- In *reverse* order that they're specified on the command line.
  DynFlags -> Maybe String
packageEnv            :: Maybe FilePath,
        -- ^ Filepath to the package environment file (if overriding default)

  -- Package state
  -- NB. do not modify this field, it is calculated by
  -- Packages.initPackages
  DynFlags -> Maybe [(String, [PackageConfig])]
pkgDatabase           :: Maybe [(FilePath, [PackageConfig])],
  DynFlags -> PackageState
pkgState              :: PackageState,

  -- Temporary files
  -- These have to be IORefs, because the defaultCleanupHandler needs to
  -- know what to clean when an exception happens
  DynFlags -> IORef FilesToClean
filesToClean          :: IORef FilesToClean,
  DynFlags -> IORef (Map String String)
dirsToClean           :: IORef (Map FilePath FilePath),
  -- The next available suffix to uniquely name a temp file, updated atomically
  DynFlags -> IORef Int
nextTempSuffix        :: IORef Int,

  -- Names of files which were generated from -ddump-to-file; used to
  -- track which ones we need to truncate because it's our first run
  -- through
  DynFlags -> IORef (Set String)
generatedDumps        :: IORef (Set FilePath),

  -- hsc dynamic flags
  DynFlags -> EnumSet DumpFlag
dumpFlags             :: EnumSet DumpFlag,
  DynFlags -> EnumSet GeneralFlag
generalFlags          :: EnumSet GeneralFlag,
  DynFlags -> EnumSet WarningFlag
warningFlags          :: EnumSet WarningFlag,
  DynFlags -> EnumSet WarningFlag
fatalWarningFlags     :: EnumSet WarningFlag,
  -- Don't change this without updating extensionFlags:
  DynFlags -> Maybe Language
language              :: Maybe Language,
  -- | Safe Haskell mode
  DynFlags -> SafeHaskellMode
safeHaskell           :: SafeHaskellMode,
  DynFlags -> Bool
safeInfer             :: Bool,
  DynFlags -> Bool
safeInferred          :: Bool,
  -- We store the location of where some extension and flags were turned on so
  -- we can produce accurate error messages when Safe Haskell fails due to
  -- them.
  DynFlags -> SrcSpan
thOnLoc               :: SrcSpan,
  DynFlags -> SrcSpan
newDerivOnLoc         :: SrcSpan,
  DynFlags -> SrcSpan
overlapInstLoc        :: SrcSpan,
  DynFlags -> SrcSpan
incoherentOnLoc       :: SrcSpan,
  DynFlags -> SrcSpan
pkgTrustOnLoc         :: SrcSpan,
  DynFlags -> SrcSpan
warnSafeOnLoc         :: SrcSpan,
  DynFlags -> SrcSpan
warnUnsafeOnLoc       :: SrcSpan,
  DynFlags -> SrcSpan
trustworthyOnLoc      :: SrcSpan,
  -- Don't change this without updating extensionFlags:
  -- Here we collect the settings of the language extensions
  -- from the command line, the ghci config file and
  -- from interactive :set / :seti commands.
  DynFlags -> [OnOff Extension]
extensions            :: [OnOff LangExt.Extension],
  -- extensionFlags should always be equal to
  --     flattenExtensionFlags language extensions
  -- LangExt.Extension is defined in libraries/ghc-boot so that it can be used
  -- by template-haskell
  DynFlags -> EnumSet Extension
extensionFlags        :: EnumSet LangExt.Extension,

  -- Unfolding control
  -- See Note [Discounts and thresholds] in CoreUnfold
  DynFlags -> Int
ufCreationThreshold   :: Int,
  DynFlags -> Int
ufUseThreshold        :: Int,
  DynFlags -> Int
ufFunAppDiscount      :: Int,
  DynFlags -> Int
ufDictDiscount        :: Int,
  DynFlags -> Float
ufKeenessFactor       :: Float,
  DynFlags -> Int
ufDearOp              :: Int,
  DynFlags -> Bool
ufVeryAggressive      :: Bool,

  DynFlags -> Int
maxWorkerArgs         :: Int,

  DynFlags -> Int
ghciHistSize          :: Int,

  -- | MsgDoc output action: use "ErrUtils" instead of this if you can
  DynFlags -> LogAction
log_action            :: LogAction,
  DynFlags -> FlushOut
flushOut              :: FlushOut,
  DynFlags -> FlushErr
flushErr              :: FlushErr,

  DynFlags -> Maybe String
ghcVersionFile        :: Maybe FilePath,
  DynFlags -> Maybe String
haddockOptions        :: Maybe String,

  -- | GHCi scripts specified by -ghci-script, in reverse order
  DynFlags -> [String]
ghciScripts           :: [String],

  -- Output style options
  DynFlags -> Int
pprUserLength         :: Int,
  DynFlags -> Int
pprCols               :: Int,

  DynFlags -> Bool
useUnicode            :: Bool,
  DynFlags -> OverridingBool
useColor              :: OverridingBool,
  DynFlags -> Bool
canUseColor           :: Bool,
  DynFlags -> Scheme
colScheme             :: Col.Scheme,

  -- | what kind of {-# SCC #-} to add automatically
  DynFlags -> ProfAuto
profAuto              :: ProfAuto,

  DynFlags -> Maybe String
interactivePrint      :: Maybe String,

  DynFlags -> IORef (ModuleEnv Int)
nextWrapperNum        :: IORef (ModuleEnv Int),

  -- | Machine dependent flags (-m<blah> stuff)
  DynFlags -> Maybe SseVersion
sseVersion            :: Maybe SseVersion,
  DynFlags -> Maybe BmiVersion
bmiVersion            :: Maybe BmiVersion,
  DynFlags -> Bool
avx                   :: Bool,
  DynFlags -> Bool
avx2                  :: Bool,
  DynFlags -> Bool
avx512cd              :: Bool, -- Enable AVX-512 Conflict Detection Instructions.
  DynFlags -> Bool
avx512er              :: Bool, -- Enable AVX-512 Exponential and Reciprocal Instructions.
  DynFlags -> Bool
avx512f               :: Bool, -- Enable AVX-512 instructions.
  DynFlags -> Bool
avx512pf              :: Bool, -- Enable AVX-512 PreFetch Instructions.

  -- | Run-time linker information (what options we need, etc.)
  DynFlags -> IORef (Maybe LinkerInfo)
rtldInfo              :: IORef (Maybe LinkerInfo),

  -- | Run-time compiler information
  DynFlags -> IORef (Maybe CompilerInfo)
rtccInfo              :: IORef (Maybe CompilerInfo),

  -- Constants used to control the amount of optimization done.

  -- | Max size, in bytes, of inline array allocations.
  DynFlags -> Int
maxInlineAllocSize    :: Int,

  -- | Only inline memcpy if it generates no more than this many
  -- pseudo (roughly: Cmm) instructions.
  DynFlags -> Int
maxInlineMemcpyInsns  :: Int,

  -- | Only inline memset if it generates no more than this many
  -- pseudo (roughly: Cmm) instructions.
  DynFlags -> Int
maxInlineMemsetInsns  :: Int,

  -- | Reverse the order of error messages in GHC/GHCi
  DynFlags -> Bool
reverseErrors         :: Bool,

  -- | Limit the maximum number of errors to show
  DynFlags -> Maybe Int
maxErrors             :: Maybe Int,

  -- | Unique supply configuration for testing build determinism
  DynFlags -> Int
initialUnique         :: Int,
  DynFlags -> Int
uniqueIncrement       :: Int,

  -- | Temporary: CFG Edge weights for fast iterations
  DynFlags -> CfgWeights
cfgWeightInfo         :: CfgWeights
}

-- | Edge weights to use when generating a CFG from CMM
data CfgWeights
    = CFGWeights
    { CfgWeights -> Int
uncondWeight :: Int
    , CfgWeights -> Int
condBranchWeight :: Int
    , CfgWeights -> Int
switchWeight :: Int
    , CfgWeights -> Int
callWeight :: Int
    , CfgWeights -> Int
likelyCondWeight :: Int
    , CfgWeights -> Int
unlikelyCondWeight :: Int
    , CfgWeights -> Int
infoTablePenalty :: Int
    , CfgWeights -> Int
backEdgeBonus :: Int
    }

defaultCfgWeights :: CfgWeights
defaultCfgWeights :: CfgWeights
defaultCfgWeights
    = CFGWeights :: Int -> Int -> Int -> Int -> Int -> Int -> Int -> Int -> CfgWeights
CFGWeights
    { uncondWeight :: Int
uncondWeight = Int
1000
    , condBranchWeight :: Int
condBranchWeight = Int
800
    , switchWeight :: Int
switchWeight = Int
1
    , callWeight :: Int
callWeight = -Int
10
    , likelyCondWeight :: Int
likelyCondWeight = Int
900
    , unlikelyCondWeight :: Int
unlikelyCondWeight = Int
300
    , infoTablePenalty :: Int
infoTablePenalty = Int
300
    , backEdgeBonus :: Int
backEdgeBonus = Int
400
    }

parseCfgWeights :: String -> CfgWeights -> CfgWeights
parseCfgWeights :: String -> CfgWeights -> CfgWeights
parseCfgWeights String
s CfgWeights
oldWeights =
        (CfgWeights -> (String, Int) -> CfgWeights)
-> CfgWeights -> [(String, Int)] -> CfgWeights
forall (t :: * -> *) b a.
Foldable t =>
(b -> a -> b) -> b -> t a -> b
foldl' (\CfgWeights
cfg (String
n,Int
v) -> String -> Int -> CfgWeights -> CfgWeights
update String
n Int
v CfgWeights
cfg) CfgWeights
oldWeights [(String, Int)]
assignments
    where
        assignments :: [(String, Int)]
assignments = (String -> (String, Int)) -> [String] -> [(String, Int)]
forall a b. (a -> b) -> [a] -> [b]
map String -> (String, Int)
forall b. Read b => String -> (String, b)
assignment ([String] -> [(String, Int)]) -> [String] -> [(String, Int)]
forall a b. (a -> b) -> a -> b
$ String -> [String]
settings String
s
        update :: String -> Int -> CfgWeights -> CfgWeights
update String
"uncondWeight" Int
n CfgWeights
w =
            CfgWeights
w {uncondWeight :: Int
uncondWeight = Int
n}
        update String
"condBranchWeight" Int
n CfgWeights
w =
            CfgWeights
w {condBranchWeight :: Int
condBranchWeight = Int
n}
        update String
"switchWeight" Int
n CfgWeights
w =
            CfgWeights
w {switchWeight :: Int
switchWeight = Int
n}
        update String
"callWeight" Int
n CfgWeights
w =
            CfgWeights
w {callWeight :: Int
callWeight = Int
n}
        update String
"likelyCondWeight" Int
n CfgWeights
w =
            CfgWeights
w {likelyCondWeight :: Int
likelyCondWeight = Int
n}
        update String
"unlikelyCondWeight" Int
n CfgWeights
w =
            CfgWeights
w {unlikelyCondWeight :: Int
unlikelyCondWeight = Int
n}
        update String
"infoTablePenalty" Int
n CfgWeights
w =
            CfgWeights
w {infoTablePenalty :: Int
infoTablePenalty = Int
n}
        update String
"backEdgeBonus" Int
n CfgWeights
w =
            CfgWeights
w {backEdgeBonus :: Int
backEdgeBonus = Int
n}
        update String
other Int
_ CfgWeights
_
            = String -> CfgWeights
forall a. String -> a
panic (String -> CfgWeights) -> String -> CfgWeights
forall a b. (a -> b) -> a -> b
$ String
other String -> ShowS
forall a. [a] -> [a] -> [a]
++
                      String
" is not a cfg weight parameter. " String -> ShowS
forall a. [a] -> [a] -> [a]
++
                      String
exampleString
        settings :: String -> [String]
settings String
s
            | (String
s1,String
rest) <- (Char -> Bool) -> String -> (String, String)
forall a. (a -> Bool) -> [a] -> ([a], [a])
break (Char -> Char -> Bool
forall a. Eq a => a -> a -> Bool
== Char
',') String
s
            , String -> Bool
forall (t :: * -> *) a. Foldable t => t a -> Bool
null String
rest
            = [String
s1]
            | (String
s1,String
rest) <- (Char -> Bool) -> String -> (String, String)
forall a. (a -> Bool) -> [a] -> ([a], [a])
break (Char -> Char -> Bool
forall a. Eq a => a -> a -> Bool
== Char
',') String
s
            = [String
s1] [String] -> [String] -> [String]
forall a. [a] -> [a] -> [a]
++ String -> [String]
settings (Int -> ShowS
forall a. Int -> [a] -> [a]
drop Int
1 String
rest)
            | Bool
otherwise = String -> [String]
forall a. String -> a
panic (String -> [String]) -> String -> [String]
forall a b. (a -> b) -> a -> b
$ String
"Invalid cfg parameters." String -> ShowS
forall a. [a] -> [a] -> [a]
++ String
exampleString
        assignment :: String -> (String, b)
assignment String
as
            | (String
name, Char
_:String
val) <- (Char -> Bool) -> String -> (String, String)
forall a. (a -> Bool) -> [a] -> ([a], [a])
break (Char -> Char -> Bool
forall a. Eq a => a -> a -> Bool
== Char
'=') String
as
            = (String
name,String -> b
forall a. Read a => String -> a
read String
val)
            | Bool
otherwise
            = String -> (String, b)
forall a. String -> a
panic (String -> (String, b)) -> String -> (String, b)
forall a b. (a -> b) -> a -> b
$ String
"Invalid cfg parameters." String -> ShowS
forall a. [a] -> [a] -> [a]
++ String
exampleString
        exampleString :: String
exampleString = String
"Example parameters: uncondWeight=1000," String -> ShowS
forall a. [a] -> [a] -> [a]
++
            String
"condBranchWeight=800,switchWeight=0,callWeight=300" String -> ShowS
forall a. [a] -> [a] -> [a]
++
            String
",likelyCondWeight=900,unlikelyCondWeight=300" String -> ShowS
forall a. [a] -> [a] -> [a]
++
            String
",infoTablePenalty=300,backEdgeBonus=400"

backendMaintainsCfg :: DynFlags -> Bool
backendMaintainsCfg :: DynFlags -> Bool
backendMaintainsCfg DynFlags
dflags = case (Platform -> Arch
platformArch (Platform -> Arch) -> Platform -> Arch
forall a b. (a -> b) -> a -> b
$ DynFlags -> Platform
targetPlatform DynFlags
dflags) of
    -- ArchX86 -- Should work but not tested so disabled currently.
    Arch
ArchX86_64 -> Bool
True
    Arch
_otherwise -> Bool
False

class HasDynFlags m where
    getDynFlags :: m DynFlags

{- It would be desirable to have the more generalised

  instance (MonadTrans t, Monad m, HasDynFlags m) => HasDynFlags (t m) where
      getDynFlags = lift getDynFlags

instance definition. However, that definition would overlap with the
`HasDynFlags (GhcT m)` instance. Instead we define instances for a
couple of common Monad transformers explicitly. -}

instance (Monoid a, Monad m, HasDynFlags m) => HasDynFlags (WriterT a m) where
    getDynFlags :: WriterT a m DynFlags
getDynFlags = m DynFlags -> WriterT a m DynFlags
forall (t :: (* -> *) -> * -> *) (m :: * -> *) a.
(MonadTrans t, Monad m) =>
m a -> t m a
lift m DynFlags
forall (m :: * -> *). HasDynFlags m => m DynFlags
getDynFlags

instance (Monad m, HasDynFlags m) => HasDynFlags (ReaderT a m) where
    getDynFlags :: ReaderT a m DynFlags
getDynFlags = m DynFlags -> ReaderT a m DynFlags
forall (t :: (* -> *) -> * -> *) (m :: * -> *) a.
(MonadTrans t, Monad m) =>
m a -> t m a
lift m DynFlags
forall (m :: * -> *). HasDynFlags m => m DynFlags
getDynFlags

instance (Monad m, HasDynFlags m) => HasDynFlags (MaybeT m) where
    getDynFlags :: MaybeT m DynFlags
getDynFlags = m DynFlags -> MaybeT m DynFlags
forall (t :: (* -> *) -> * -> *) (m :: * -> *) a.
(MonadTrans t, Monad m) =>
m a -> t m a
lift m DynFlags
forall (m :: * -> *). HasDynFlags m => m DynFlags
getDynFlags

instance (Monad m, HasDynFlags m) => HasDynFlags (ExceptT e m) where
    getDynFlags :: ExceptT e m DynFlags
getDynFlags = m DynFlags -> ExceptT e m DynFlags
forall (t :: (* -> *) -> * -> *) (m :: * -> *) a.
(MonadTrans t, Monad m) =>
m a -> t m a
lift m DynFlags
forall (m :: * -> *). HasDynFlags m => m DynFlags
getDynFlags

class ContainsDynFlags t where
    extractDynFlags :: t -> DynFlags

data ProfAuto
  = NoProfAuto         -- ^ no SCC annotations added
  | ProfAutoAll        -- ^ top-level and nested functions are annotated
  | ProfAutoTop        -- ^ top-level functions annotated only
  | ProfAutoExports    -- ^ exported functions annotated only
  | ProfAutoCalls      -- ^ annotate call-sites
  deriving (ProfAuto -> ProfAuto -> Bool
(ProfAuto -> ProfAuto -> Bool)
-> (ProfAuto -> ProfAuto -> Bool) -> Eq ProfAuto
forall a. (a -> a -> Bool) -> (a -> a -> Bool) -> Eq a
/= :: ProfAuto -> ProfAuto -> Bool
$c/= :: ProfAuto -> ProfAuto -> Bool
== :: ProfAuto -> ProfAuto -> Bool
$c== :: ProfAuto -> ProfAuto -> Bool
Eq,Int -> ProfAuto
ProfAuto -> Int
ProfAuto -> [ProfAuto]
ProfAuto -> ProfAuto
ProfAuto -> ProfAuto -> [ProfAuto]
ProfAuto -> ProfAuto -> ProfAuto -> [ProfAuto]
(ProfAuto -> ProfAuto)
-> (ProfAuto -> ProfAuto)
-> (Int -> ProfAuto)
-> (ProfAuto -> Int)
-> (ProfAuto -> [ProfAuto])
-> (ProfAuto -> ProfAuto -> [ProfAuto])
-> (ProfAuto -> ProfAuto -> [ProfAuto])
-> (ProfAuto -> ProfAuto -> ProfAuto -> [ProfAuto])
-> Enum ProfAuto
forall a.
(a -> a)
-> (a -> a)
-> (Int -> a)
-> (a -> Int)
-> (a -> [a])
-> (a -> a -> [a])
-> (a -> a -> [a])
-> (a -> a -> a -> [a])
-> Enum a
enumFromThenTo :: ProfAuto -> ProfAuto -> ProfAuto -> [ProfAuto]
$cenumFromThenTo :: ProfAuto -> ProfAuto -> ProfAuto -> [ProfAuto]
enumFromTo :: ProfAuto -> ProfAuto -> [ProfAuto]
$cenumFromTo :: ProfAuto -> ProfAuto -> [ProfAuto]
enumFromThen :: ProfAuto -> ProfAuto -> [ProfAuto]
$cenumFromThen :: ProfAuto -> ProfAuto -> [ProfAuto]
enumFrom :: ProfAuto -> [ProfAuto]
$cenumFrom :: ProfAuto -> [ProfAuto]
fromEnum :: ProfAuto -> Int
$cfromEnum :: ProfAuto -> Int
toEnum :: Int -> ProfAuto
$ctoEnum :: Int -> ProfAuto
pred :: ProfAuto -> ProfAuto
$cpred :: ProfAuto -> ProfAuto
succ :: ProfAuto -> ProfAuto
$csucc :: ProfAuto -> ProfAuto
Enum)

data LlvmTarget = LlvmTarget
  { LlvmTarget -> String
lDataLayout :: String
  , LlvmTarget -> String
lCPU        :: String
  , LlvmTarget -> [String]
lAttributes :: [String]
  }

-- | See Note [LLVM Configuration] in SysTools.
data LlvmConfig = LlvmConfig { LlvmConfig -> [(String, LlvmTarget)]
llvmTargets :: [(String, LlvmTarget)]
                             , LlvmConfig -> [(Int, String)]
llvmPasses  :: [(Int, String)]
                             }

-----------------------------------------------------------------------------
-- Accessessors from 'DynFlags'

-- | "unbuild" a 'Settings' from a 'DynFlags'. This shouldn't be needed in the
-- vast majority of code. But GHCi questionably uses this to produce a default
-- 'DynFlags' from which to compute a flags diff for printing.
settings :: DynFlags -> Settings
settings :: DynFlags -> Settings
settings DynFlags
dflags = Settings :: GhcNameVersion
-> FileSettings
-> Platform
-> ToolSettings
-> PlatformMisc
-> PlatformConstants
-> [(String, String)]
-> Settings
Settings
  { sGhcNameVersion :: GhcNameVersion
sGhcNameVersion = DynFlags -> GhcNameVersion
ghcNameVersion DynFlags
dflags
  , sFileSettings :: FileSettings
sFileSettings = DynFlags -> FileSettings
fileSettings DynFlags
dflags
  , sTargetPlatform :: Platform
sTargetPlatform = DynFlags -> Platform
targetPlatform DynFlags
dflags
  , sToolSettings :: ToolSettings
sToolSettings = DynFlags -> ToolSettings
toolSettings DynFlags
dflags
  , sPlatformMisc :: PlatformMisc
sPlatformMisc = DynFlags -> PlatformMisc
platformMisc DynFlags
dflags
  , sPlatformConstants :: PlatformConstants
sPlatformConstants = DynFlags -> PlatformConstants
platformConstants DynFlags
dflags
  , sRawSettings :: [(String, String)]
sRawSettings = DynFlags -> [(String, String)]
rawSettings DynFlags
dflags
  }

programName :: DynFlags -> String
programName :: DynFlags -> String
programName DynFlags
dflags = GhcNameVersion -> String
ghcNameVersion_programName (GhcNameVersion -> String) -> GhcNameVersion -> String
forall a b. (a -> b) -> a -> b
$ DynFlags -> GhcNameVersion
ghcNameVersion DynFlags
dflags
projectVersion :: DynFlags -> String
projectVersion :: DynFlags -> String
projectVersion DynFlags
dflags = GhcNameVersion -> String
ghcNameVersion_projectVersion (DynFlags -> GhcNameVersion
ghcNameVersion DynFlags
dflags)
ghcUsagePath          :: DynFlags -> FilePath
ghcUsagePath :: DynFlags -> String
ghcUsagePath DynFlags
dflags = FileSettings -> String
fileSettings_ghcUsagePath (FileSettings -> String) -> FileSettings -> String
forall a b. (a -> b) -> a -> b
$ DynFlags -> FileSettings
fileSettings DynFlags
dflags
ghciUsagePath         :: DynFlags -> FilePath
ghciUsagePath :: DynFlags -> String
ghciUsagePath DynFlags
dflags = FileSettings -> String
fileSettings_ghciUsagePath (FileSettings -> String) -> FileSettings -> String
forall a b. (a -> b) -> a -> b
$ DynFlags -> FileSettings
fileSettings DynFlags
dflags
toolDir               :: DynFlags -> Maybe FilePath
toolDir :: DynFlags -> Maybe String
toolDir DynFlags
dflags = FileSettings -> Maybe String
fileSettings_toolDir (FileSettings -> Maybe String) -> FileSettings -> Maybe String
forall a b. (a -> b) -> a -> b
$ DynFlags -> FileSettings
fileSettings DynFlags
dflags
topDir                :: DynFlags -> FilePath
topDir :: DynFlags -> String
topDir DynFlags
dflags = FileSettings -> String
fileSettings_topDir (FileSettings -> String) -> FileSettings -> String
forall a b. (a -> b) -> a -> b
$ DynFlags -> FileSettings
fileSettings DynFlags
dflags
tmpDir                :: DynFlags -> String
tmpDir :: DynFlags -> String
tmpDir DynFlags
dflags = FileSettings -> String
fileSettings_tmpDir (FileSettings -> String) -> FileSettings -> String
forall a b. (a -> b) -> a -> b
$ DynFlags -> FileSettings
fileSettings DynFlags
dflags
extraGccViaCFlags     :: DynFlags -> [String]
extraGccViaCFlags :: DynFlags -> [String]
extraGccViaCFlags DynFlags
dflags = ToolSettings -> [String]
toolSettings_extraGccViaCFlags (ToolSettings -> [String]) -> ToolSettings -> [String]
forall a b. (a -> b) -> a -> b
$ DynFlags -> ToolSettings
toolSettings DynFlags
dflags
systemPackageConfig   :: DynFlags -> FilePath
systemPackageConfig :: DynFlags -> String
systemPackageConfig DynFlags
dflags = FileSettings -> String
fileSettings_systemPackageConfig (FileSettings -> String) -> FileSettings -> String
forall a b. (a -> b) -> a -> b
$ DynFlags -> FileSettings
fileSettings DynFlags
dflags
pgm_L                 :: DynFlags -> String
pgm_L :: DynFlags -> String
pgm_L DynFlags
dflags = ToolSettings -> String
toolSettings_pgm_L (ToolSettings -> String) -> ToolSettings -> String
forall a b. (a -> b) -> a -> b
$ DynFlags -> ToolSettings
toolSettings DynFlags
dflags
pgm_P                 :: DynFlags -> (String,[Option])
pgm_P :: DynFlags -> (String, [Option])
pgm_P DynFlags
dflags = ToolSettings -> (String, [Option])
toolSettings_pgm_P (ToolSettings -> (String, [Option]))
-> ToolSettings -> (String, [Option])
forall a b. (a -> b) -> a -> b
$ DynFlags -> ToolSettings
toolSettings DynFlags
dflags
pgm_F                 :: DynFlags -> String
pgm_F :: DynFlags -> String
pgm_F DynFlags
dflags = ToolSettings -> String
toolSettings_pgm_F (ToolSettings -> String) -> ToolSettings -> String
forall a b. (a -> b) -> a -> b
$ DynFlags -> ToolSettings
toolSettings DynFlags
dflags
pgm_c                 :: DynFlags -> String
pgm_c :: DynFlags -> String
pgm_c DynFlags
dflags = ToolSettings -> String
toolSettings_pgm_c (ToolSettings -> String) -> ToolSettings -> String
forall a b. (a -> b) -> a -> b
$ DynFlags -> ToolSettings
toolSettings DynFlags
dflags
pgm_a                 :: DynFlags -> (String,[Option])
pgm_a :: DynFlags -> (String, [Option])
pgm_a DynFlags
dflags = ToolSettings -> (String, [Option])
toolSettings_pgm_a (ToolSettings -> (String, [Option]))
-> ToolSettings -> (String, [Option])
forall a b. (a -> b) -> a -> b
$ DynFlags -> ToolSettings
toolSettings DynFlags
dflags
pgm_l                 :: DynFlags -> (String,[Option])
pgm_l :: DynFlags -> (String, [Option])
pgm_l DynFlags
dflags = ToolSettings -> (String, [Option])
toolSettings_pgm_l (ToolSettings -> (String, [Option]))
-> ToolSettings -> (String, [Option])
forall a b. (a -> b) -> a -> b
$ DynFlags -> ToolSettings
toolSettings DynFlags
dflags
pgm_dll               :: DynFlags -> (String,[Option])
pgm_dll :: DynFlags -> (String, [Option])
pgm_dll DynFlags
dflags = ToolSettings -> (String, [Option])
toolSettings_pgm_dll (ToolSettings -> (String, [Option]))
-> ToolSettings -> (String, [Option])
forall a b. (a -> b) -> a -> b
$ DynFlags -> ToolSettings
toolSettings DynFlags
dflags
pgm_T                 :: DynFlags -> String
pgm_T :: DynFlags -> String
pgm_T DynFlags
dflags = ToolSettings -> String
toolSettings_pgm_T (ToolSettings -> String) -> ToolSettings -> String
forall a b. (a -> b) -> a -> b
$ DynFlags -> ToolSettings
toolSettings DynFlags
dflags
pgm_windres           :: DynFlags -> String
pgm_windres :: DynFlags -> String
pgm_windres DynFlags
dflags = ToolSettings -> String
toolSettings_pgm_windres (ToolSettings -> String) -> ToolSettings -> String
forall a b. (a -> b) -> a -> b
$ DynFlags -> ToolSettings
toolSettings DynFlags
dflags
pgm_libtool           :: DynFlags -> String
pgm_libtool :: DynFlags -> String
pgm_libtool DynFlags
dflags = ToolSettings -> String
toolSettings_pgm_libtool (ToolSettings -> String) -> ToolSettings -> String
forall a b. (a -> b) -> a -> b
$ DynFlags -> ToolSettings
toolSettings DynFlags
dflags
pgm_lcc               :: DynFlags -> (String,[Option])
pgm_lcc :: DynFlags -> (String, [Option])
pgm_lcc DynFlags
dflags = ToolSettings -> (String, [Option])
toolSettings_pgm_lcc (ToolSettings -> (String, [Option]))
-> ToolSettings -> (String, [Option])
forall a b. (a -> b) -> a -> b
$ DynFlags -> ToolSettings
toolSettings DynFlags
dflags
pgm_ar                :: DynFlags -> String
pgm_ar :: DynFlags -> String
pgm_ar DynFlags
dflags = ToolSettings -> String
toolSettings_pgm_ar (ToolSettings -> String) -> ToolSettings -> String
forall a b. (a -> b) -> a -> b
$ DynFlags -> ToolSettings
toolSettings DynFlags
dflags
pgm_ranlib            :: DynFlags -> String
pgm_ranlib :: DynFlags -> String
pgm_ranlib DynFlags
dflags = ToolSettings -> String
toolSettings_pgm_ranlib (ToolSettings -> String) -> ToolSettings -> String
forall a b. (a -> b) -> a -> b
$ DynFlags -> ToolSettings
toolSettings DynFlags
dflags
pgm_lo                :: DynFlags -> (String,[Option])
pgm_lo :: DynFlags -> (String, [Option])
pgm_lo DynFlags
dflags = ToolSettings -> (String, [Option])
toolSettings_pgm_lo (ToolSettings -> (String, [Option]))
-> ToolSettings -> (String, [Option])
forall a b. (a -> b) -> a -> b
$ DynFlags -> ToolSettings
toolSettings DynFlags
dflags
pgm_lc                :: DynFlags -> (String,[Option])
pgm_lc :: DynFlags -> (String, [Option])
pgm_lc DynFlags
dflags = ToolSettings -> (String, [Option])
toolSettings_pgm_lc (ToolSettings -> (String, [Option]))
-> ToolSettings -> (String, [Option])
forall a b. (a -> b) -> a -> b
$ DynFlags -> ToolSettings
toolSettings DynFlags
dflags
pgm_i                 :: DynFlags -> String
pgm_i :: DynFlags -> String
pgm_i DynFlags
dflags = ToolSettings -> String
toolSettings_pgm_i (ToolSettings -> String) -> ToolSettings -> String
forall a b. (a -> b) -> a -> b
$ DynFlags -> ToolSettings
toolSettings DynFlags
dflags
opt_L                 :: DynFlags -> [String]
opt_L :: DynFlags -> [String]
opt_L DynFlags
dflags = ToolSettings -> [String]
toolSettings_opt_L (ToolSettings -> [String]) -> ToolSettings -> [String]
forall a b. (a -> b) -> a -> b
$ DynFlags -> ToolSettings
toolSettings DynFlags
dflags
opt_P                 :: DynFlags -> [String]
opt_P :: DynFlags -> [String]
opt_P DynFlags
dflags = (Way -> [String]) -> [Way] -> [String]
forall (t :: * -> *) a b. Foldable t => (a -> [b]) -> t a -> [b]
concatMap (Platform -> Way -> [String]
wayOptP (DynFlags -> Platform
targetPlatform DynFlags
dflags)) (DynFlags -> [Way]
ways DynFlags
dflags)
            [String] -> [String] -> [String]
forall a. [a] -> [a] -> [a]
++ ToolSettings -> [String]
toolSettings_opt_P (DynFlags -> ToolSettings
toolSettings DynFlags
dflags)

-- This function packages everything that's needed to fingerprint opt_P
-- flags. See Note [Repeated -optP hashing].
opt_P_signature       :: DynFlags -> ([String], Fingerprint)
opt_P_signature :: DynFlags -> ([String], Fingerprint)
opt_P_signature DynFlags
dflags =
  ( (Way -> [String]) -> [Way] -> [String]
forall (t :: * -> *) a b. Foldable t => (a -> [b]) -> t a -> [b]
concatMap (Platform -> Way -> [String]
wayOptP (DynFlags -> Platform
targetPlatform DynFlags
dflags)) (DynFlags -> [Way]
ways DynFlags
dflags)
  , ToolSettings -> Fingerprint
toolSettings_opt_P_fingerprint (ToolSettings -> Fingerprint) -> ToolSettings -> Fingerprint
forall a b. (a -> b) -> a -> b
$ DynFlags -> ToolSettings
toolSettings DynFlags
dflags
  )

opt_F                 :: DynFlags -> [String]
opt_F :: DynFlags -> [String]
opt_F DynFlags
dflags= ToolSettings -> [String]
toolSettings_opt_F (ToolSettings -> [String]) -> ToolSettings -> [String]
forall a b. (a -> b) -> a -> b
$ DynFlags -> ToolSettings
toolSettings DynFlags
dflags
opt_c                 :: DynFlags -> [String]
opt_c :: DynFlags -> [String]
opt_c DynFlags
dflags = (Way -> [String]) -> [Way] -> [String]
forall (t :: * -> *) a b. Foldable t => (a -> [b]) -> t a -> [b]
concatMap (Platform -> Way -> [String]
wayOptc (DynFlags -> Platform
targetPlatform DynFlags
dflags)) (DynFlags -> [Way]
ways DynFlags
dflags)
            [String] -> [String] -> [String]
forall a. [a] -> [a] -> [a]
++ ToolSettings -> [String]
toolSettings_opt_c (DynFlags -> ToolSettings
toolSettings DynFlags
dflags)
opt_cxx               :: DynFlags -> [String]
opt_cxx :: DynFlags -> [String]
opt_cxx DynFlags
dflags= ToolSettings -> [String]
toolSettings_opt_cxx (ToolSettings -> [String]) -> ToolSettings -> [String]
forall a b. (a -> b) -> a -> b
$ DynFlags -> ToolSettings
toolSettings DynFlags
dflags
opt_a                 :: DynFlags -> [String]
opt_a :: DynFlags -> [String]
opt_a DynFlags
dflags= ToolSettings -> [String]
toolSettings_opt_a (ToolSettings -> [String]) -> ToolSettings -> [String]
forall a b. (a -> b) -> a -> b
$ DynFlags -> ToolSettings
toolSettings DynFlags
dflags
opt_l                 :: DynFlags -> [String]
opt_l :: DynFlags -> [String]
opt_l DynFlags
dflags = (Way -> [String]) -> [Way] -> [String]
forall (t :: * -> *) a b. Foldable t => (a -> [b]) -> t a -> [b]
concatMap (Platform -> Way -> [String]
wayOptl (DynFlags -> Platform
targetPlatform DynFlags
dflags)) (DynFlags -> [Way]
ways DynFlags
dflags)
            [String] -> [String] -> [String]
forall a. [a] -> [a] -> [a]
++ ToolSettings -> [String]
toolSettings_opt_l (DynFlags -> ToolSettings
toolSettings DynFlags
dflags)
opt_windres           :: DynFlags -> [String]
opt_windres :: DynFlags -> [String]
opt_windres DynFlags
dflags= ToolSettings -> [String]
toolSettings_opt_windres (ToolSettings -> [String]) -> ToolSettings -> [String]
forall a b. (a -> b) -> a -> b
$ DynFlags -> ToolSettings
toolSettings DynFlags
dflags
opt_lcc                :: DynFlags -> [String]
opt_lcc :: DynFlags -> [String]
opt_lcc DynFlags
dflags= ToolSettings -> [String]
toolSettings_opt_lcc (ToolSettings -> [String]) -> ToolSettings -> [String]
forall a b. (a -> b) -> a -> b
$ DynFlags -> ToolSettings
toolSettings DynFlags
dflags
opt_lo                :: DynFlags -> [String]
opt_lo :: DynFlags -> [String]
opt_lo DynFlags
dflags= ToolSettings -> [String]
toolSettings_opt_lo (ToolSettings -> [String]) -> ToolSettings -> [String]
forall a b. (a -> b) -> a -> b
$ DynFlags -> ToolSettings
toolSettings DynFlags
dflags
opt_lc                :: DynFlags -> [String]
opt_lc :: DynFlags -> [String]
opt_lc DynFlags
dflags= ToolSettings -> [String]
toolSettings_opt_lc (ToolSettings -> [String]) -> ToolSettings -> [String]
forall a b. (a -> b) -> a -> b
$ DynFlags -> ToolSettings
toolSettings DynFlags
dflags
opt_i                 :: DynFlags -> [String]
opt_i :: DynFlags -> [String]
opt_i DynFlags
dflags= ToolSettings -> [String]
toolSettings_opt_i (ToolSettings -> [String]) -> ToolSettings -> [String]
forall a b. (a -> b) -> a -> b
$ DynFlags -> ToolSettings
toolSettings DynFlags
dflags

tablesNextToCode :: DynFlags -> Bool
tablesNextToCode :: DynFlags -> Bool
tablesNextToCode = PlatformMisc -> Bool
platformMisc_tablesNextToCode (PlatformMisc -> Bool)
-> (DynFlags -> PlatformMisc) -> DynFlags -> Bool
forall b c a. (b -> c) -> (a -> b) -> a -> c
. DynFlags -> PlatformMisc
platformMisc

-- | The directory for this version of ghc in the user's app directory
-- (typically something like @~/.ghc/x86_64-linux-7.6.3@)
--
versionedAppDir :: DynFlags -> MaybeT IO FilePath
versionedAppDir :: DynFlags -> MaybeT IO String
versionedAppDir DynFlags
dflags = do
  -- Make sure we handle the case the HOME isn't set (see #11678)
  String
appdir <- IO String -> MaybeT IO String
forall a. IO a -> MaybeT IO a
tryMaybeT (IO String -> MaybeT IO String) -> IO String -> MaybeT IO String
forall a b. (a -> b) -> a -> b
$ String -> IO String
getAppUserDataDirectory (DynFlags -> String
programName DynFlags
dflags)
  String -> MaybeT IO String
forall (m :: * -> *) a. Monad m => a -> m a
return (String -> MaybeT IO String) -> String -> MaybeT IO String
forall a b. (a -> b) -> a -> b
$ String
appdir String -> ShowS
</> DynFlags -> String
versionedFilePath DynFlags
dflags

versionedFilePath :: DynFlags -> FilePath
versionedFilePath :: DynFlags -> String
versionedFilePath DynFlags
dflags = PlatformMini -> String
uniqueSubdir (PlatformMini -> String) -> PlatformMini -> String
forall a b. (a -> b) -> a -> b
$ Platform -> PlatformMini
platformMini (Platform -> PlatformMini) -> Platform -> PlatformMini
forall a b. (a -> b) -> a -> b
$ DynFlags -> Platform
targetPlatform DynFlags
dflags

-- | The target code type of the compilation (if any).
--
-- Whenever you change the target, also make sure to set 'ghcLink' to
-- something sensible.
--
-- 'HscNothing' can be used to avoid generating any output, however, note
-- that:
--
--  * If a program uses Template Haskell the typechecker may need to run code
--    from an imported module.  To facilitate this, code generation is enabled
--    for modules imported by modules that use template haskell.
--    See Note [-fno-code mode].
--
data HscTarget
  = HscC           -- ^ Generate C code.
  | HscAsm         -- ^ Generate assembly using the native code generator.
  | HscLlvm        -- ^ Generate assembly using the llvm code generator.
  | HscInterpreted -- ^ Generate bytecode.  (Requires 'LinkInMemory')
  | HscNothing     -- ^ Don't generate any code.  See notes above.
  deriving (HscTarget -> HscTarget -> Bool
(HscTarget -> HscTarget -> Bool)
-> (HscTarget -> HscTarget -> Bool) -> Eq HscTarget
forall a. (a -> a -> Bool) -> (a -> a -> Bool) -> Eq a
/= :: HscTarget -> HscTarget -> Bool
$c/= :: HscTarget -> HscTarget -> Bool
== :: HscTarget -> HscTarget -> Bool
$c== :: HscTarget -> HscTarget -> Bool
Eq, Int -> HscTarget -> ShowS
[HscTarget] -> ShowS
HscTarget -> String
(Int -> HscTarget -> ShowS)
-> (HscTarget -> String)
-> ([HscTarget] -> ShowS)
-> Show HscTarget
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
showList :: [HscTarget] -> ShowS
$cshowList :: [HscTarget] -> ShowS
show :: HscTarget -> String
$cshow :: HscTarget -> String
showsPrec :: Int -> HscTarget -> ShowS
$cshowsPrec :: Int -> HscTarget -> ShowS
Show)

-- | Will this target result in an object file on the disk?
isObjectTarget :: HscTarget -> Bool
isObjectTarget :: HscTarget -> Bool
isObjectTarget HscTarget
HscC     = Bool
True
isObjectTarget HscTarget
HscAsm   = Bool
True
isObjectTarget HscTarget
HscLlvm  = Bool
True
isObjectTarget HscTarget
_        = Bool
False

-- | Does this target retain *all* top-level bindings for a module,
-- rather than just the exported bindings, in the TypeEnv and compiled
-- code (if any)?  In interpreted mode we do this, so that GHCi can
-- call functions inside a module.  In HscNothing mode we also do it,
-- so that Haddock can get access to the GlobalRdrEnv for a module
-- after typechecking it.
targetRetainsAllBindings :: HscTarget -> Bool
targetRetainsAllBindings :: HscTarget -> Bool
targetRetainsAllBindings HscTarget
HscInterpreted = Bool
True
targetRetainsAllBindings HscTarget
HscNothing     = Bool
True
targetRetainsAllBindings HscTarget
_              = Bool
False

-- | The 'GhcMode' tells us whether we're doing multi-module
-- compilation (controlled via the "GHC" API) or one-shot
-- (single-module) compilation.  This makes a difference primarily to
-- the "Finder": in one-shot mode we look for interface files for
-- imported modules, but in multi-module mode we look for source files
-- in order to check whether they need to be recompiled.
data GhcMode
  = CompManager         -- ^ @\-\-make@, GHCi, etc.
  | OneShot             -- ^ @ghc -c Foo.hs@
  | MkDepend            -- ^ @ghc -M@, see "Finder" for why we need this
  deriving GhcMode -> GhcMode -> Bool
(GhcMode -> GhcMode -> Bool)
-> (GhcMode -> GhcMode -> Bool) -> Eq GhcMode
forall a. (a -> a -> Bool) -> (a -> a -> Bool) -> Eq a
/= :: GhcMode -> GhcMode -> Bool
$c/= :: GhcMode -> GhcMode -> Bool
== :: GhcMode -> GhcMode -> Bool
$c== :: GhcMode -> GhcMode -> Bool
Eq

instance Outputable GhcMode where
  ppr :: GhcMode -> SDoc
ppr GhcMode
CompManager = String -> SDoc
text String
"CompManager"
  ppr GhcMode
OneShot     = String -> SDoc
text String
"OneShot"
  ppr GhcMode
MkDepend    = String -> SDoc
text String
"MkDepend"

isOneShot :: GhcMode -> Bool
isOneShot :: GhcMode -> Bool
isOneShot GhcMode
OneShot = Bool
True
isOneShot GhcMode
_other  = Bool
False

-- | What to do in the link step, if there is one.
data GhcLink
  = NoLink              -- ^ Don't link at all
  | LinkBinary          -- ^ Link object code into a binary
  | LinkInMemory        -- ^ Use the in-memory dynamic linker (works for both
                        --   bytecode and object code).
  | LinkDynLib          -- ^ Link objects into a dynamic lib (DLL on Windows, DSO on ELF platforms)
  | LinkStaticLib       -- ^ Link objects into a static lib
  deriving (GhcLink -> GhcLink -> Bool
(GhcLink -> GhcLink -> Bool)
-> (GhcLink -> GhcLink -> Bool) -> Eq GhcLink
forall a. (a -> a -> Bool) -> (a -> a -> Bool) -> Eq a
/= :: GhcLink -> GhcLink -> Bool
$c/= :: GhcLink -> GhcLink -> Bool
== :: GhcLink -> GhcLink -> Bool
$c== :: GhcLink -> GhcLink -> Bool
Eq, Int -> GhcLink -> ShowS
[GhcLink] -> ShowS
GhcLink -> String
(Int -> GhcLink -> ShowS)
-> (GhcLink -> String) -> ([GhcLink] -> ShowS) -> Show GhcLink
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
showList :: [GhcLink] -> ShowS
$cshowList :: [GhcLink] -> ShowS
show :: GhcLink -> String
$cshow :: GhcLink -> String
showsPrec :: Int -> GhcLink -> ShowS
$cshowsPrec :: Int -> GhcLink -> ShowS
Show)

isNoLink :: GhcLink -> Bool
isNoLink :: GhcLink -> Bool
isNoLink GhcLink
NoLink = Bool
True
isNoLink GhcLink
_      = Bool
False

-- | We accept flags which make packages visible, but how they select
-- the package varies; this data type reflects what selection criterion
-- is used.
data PackageArg =
      PackageArg String    -- ^ @-package@, by 'PackageName'
    | UnitIdArg UnitId     -- ^ @-package-id@, by 'UnitId'
  deriving (PackageArg -> PackageArg -> Bool
(PackageArg -> PackageArg -> Bool)
-> (PackageArg -> PackageArg -> Bool) -> Eq PackageArg
forall a. (a -> a -> Bool) -> (a -> a -> Bool) -> Eq a
/= :: PackageArg -> PackageArg -> Bool
$c/= :: PackageArg -> PackageArg -> Bool
== :: PackageArg -> PackageArg -> Bool
$c== :: PackageArg -> PackageArg -> Bool
Eq, Int -> PackageArg -> ShowS
[PackageArg] -> ShowS
PackageArg -> String
(Int -> PackageArg -> ShowS)
-> (PackageArg -> String)
-> ([PackageArg] -> ShowS)
-> Show PackageArg
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
showList :: [PackageArg] -> ShowS
$cshowList :: [PackageArg] -> ShowS
show :: PackageArg -> String
$cshow :: PackageArg -> String
showsPrec :: Int -> PackageArg -> ShowS
$cshowsPrec :: Int -> PackageArg -> ShowS
Show)
instance Outputable PackageArg where
    ppr :: PackageArg -> SDoc
ppr (PackageArg String
pn) = String -> SDoc
text String
"package" SDoc -> SDoc -> SDoc
<+> String -> SDoc
text String
pn
    ppr (UnitIdArg UnitId
uid) = String -> SDoc
text String
"unit" SDoc -> SDoc -> SDoc
<+> UnitId -> SDoc
forall a. Outputable a => a -> SDoc
ppr UnitId
uid

-- | Represents the renaming that may be associated with an exposed
-- package, e.g. the @rns@ part of @-package "foo (rns)"@.
--
-- Here are some example parsings of the package flags (where
-- a string literal is punned to be a 'ModuleName':
--
--      * @-package foo@ is @ModRenaming True []@
--      * @-package foo ()@ is @ModRenaming False []@
--      * @-package foo (A)@ is @ModRenaming False [("A", "A")]@
--      * @-package foo (A as B)@ is @ModRenaming False [("A", "B")]@
--      * @-package foo with (A as B)@ is @ModRenaming True [("A", "B")]@
data ModRenaming = ModRenaming {
    ModRenaming -> Bool
modRenamingWithImplicit :: Bool, -- ^ Bring all exposed modules into scope?
    ModRenaming -> [(ModuleName, ModuleName)]
modRenamings :: [(ModuleName, ModuleName)] -- ^ Bring module @m@ into scope
                                               --   under name @n@.
  } deriving (ModRenaming -> ModRenaming -> Bool
(ModRenaming -> ModRenaming -> Bool)
-> (ModRenaming -> ModRenaming -> Bool) -> Eq ModRenaming
forall a. (a -> a -> Bool) -> (a -> a -> Bool) -> Eq a
/= :: ModRenaming -> ModRenaming -> Bool
$c/= :: ModRenaming -> ModRenaming -> Bool
== :: ModRenaming -> ModRenaming -> Bool
$c== :: ModRenaming -> ModRenaming -> Bool
Eq)
instance Outputable ModRenaming where
    ppr :: ModRenaming -> SDoc
ppr (ModRenaming Bool
b [(ModuleName, ModuleName)]
rns) = Bool -> SDoc
forall a. Outputable a => a -> SDoc
ppr Bool
b SDoc -> SDoc -> SDoc
<+> SDoc -> SDoc
parens ([(ModuleName, ModuleName)] -> SDoc
forall a. Outputable a => a -> SDoc
ppr [(ModuleName, ModuleName)]
rns)

-- | Flags for manipulating the set of non-broken packages.
newtype IgnorePackageFlag = IgnorePackage String -- ^ @-ignore-package@
  deriving (IgnorePackageFlag -> IgnorePackageFlag -> Bool
(IgnorePackageFlag -> IgnorePackageFlag -> Bool)
-> (IgnorePackageFlag -> IgnorePackageFlag -> Bool)
-> Eq IgnorePackageFlag
forall a. (a -> a -> Bool) -> (a -> a -> Bool) -> Eq a
/= :: IgnorePackageFlag -> IgnorePackageFlag -> Bool
$c/= :: IgnorePackageFlag -> IgnorePackageFlag -> Bool
== :: IgnorePackageFlag -> IgnorePackageFlag -> Bool
$c== :: IgnorePackageFlag -> IgnorePackageFlag -> Bool
Eq)

-- | Flags for manipulating package trust.
data TrustFlag
  = TrustPackage    String -- ^ @-trust@
  | DistrustPackage String -- ^ @-distrust@
  deriving (TrustFlag -> TrustFlag -> Bool
(TrustFlag -> TrustFlag -> Bool)
-> (TrustFlag -> TrustFlag -> Bool) -> Eq TrustFlag
forall a. (a -> a -> Bool) -> (a -> a -> Bool) -> Eq a
/= :: TrustFlag -> TrustFlag -> Bool
$c/= :: TrustFlag -> TrustFlag -> Bool
== :: TrustFlag -> TrustFlag -> Bool
$c== :: TrustFlag -> TrustFlag -> Bool
Eq)

-- | Flags for manipulating packages visibility.
data PackageFlag
  = ExposePackage   String PackageArg ModRenaming -- ^ @-package@, @-package-id@
  | HidePackage     String -- ^ @-hide-package@
  deriving (PackageFlag -> PackageFlag -> Bool
(PackageFlag -> PackageFlag -> Bool)
-> (PackageFlag -> PackageFlag -> Bool) -> Eq PackageFlag
forall a. (a -> a -> Bool) -> (a -> a -> Bool) -> Eq a
/= :: PackageFlag -> PackageFlag -> Bool
$c/= :: PackageFlag -> PackageFlag -> Bool
== :: PackageFlag -> PackageFlag -> Bool
$c== :: PackageFlag -> PackageFlag -> Bool
Eq) -- NB: equality instance is used by packageFlagsChanged

data PackageDBFlag
  = PackageDB PkgConfRef
  | NoUserPackageDB
  | NoGlobalPackageDB
  | ClearPackageDBs
  deriving (PackageDBFlag -> PackageDBFlag -> Bool
(PackageDBFlag -> PackageDBFlag -> Bool)
-> (PackageDBFlag -> PackageDBFlag -> Bool) -> Eq PackageDBFlag
forall a. (a -> a -> Bool) -> (a -> a -> Bool) -> Eq a
/= :: PackageDBFlag -> PackageDBFlag -> Bool
$c/= :: PackageDBFlag -> PackageDBFlag -> Bool
== :: PackageDBFlag -> PackageDBFlag -> Bool
$c== :: PackageDBFlag -> PackageDBFlag -> Bool
Eq)

packageFlagsChanged :: DynFlags -> DynFlags -> Bool
packageFlagsChanged :: DynFlags -> DynFlags -> Bool
packageFlagsChanged DynFlags
idflags1 DynFlags
idflags0 =
  DynFlags -> [PackageFlag]
packageFlags DynFlags
idflags1 [PackageFlag] -> [PackageFlag] -> Bool
forall a. Eq a => a -> a -> Bool
/= DynFlags -> [PackageFlag]
packageFlags DynFlags
idflags0 Bool -> Bool -> Bool
||
  DynFlags -> [IgnorePackageFlag]
ignorePackageFlags DynFlags
idflags1 [IgnorePackageFlag] -> [IgnorePackageFlag] -> Bool
forall a. Eq a => a -> a -> Bool
/= DynFlags -> [IgnorePackageFlag]
ignorePackageFlags DynFlags
idflags0 Bool -> Bool -> Bool
||
  DynFlags -> [PackageFlag]
pluginPackageFlags DynFlags
idflags1 [PackageFlag] -> [PackageFlag] -> Bool
forall a. Eq a => a -> a -> Bool
/= DynFlags -> [PackageFlag]
pluginPackageFlags DynFlags
idflags0 Bool -> Bool -> Bool
||
  DynFlags -> [TrustFlag]
trustFlags DynFlags
idflags1 [TrustFlag] -> [TrustFlag] -> Bool
forall a. Eq a => a -> a -> Bool
/= DynFlags -> [TrustFlag]
trustFlags DynFlags
idflags0 Bool -> Bool -> Bool
||
  DynFlags -> [PackageDBFlag]
packageDBFlags DynFlags
idflags1 [PackageDBFlag] -> [PackageDBFlag] -> Bool
forall a. Eq a => a -> a -> Bool
/= DynFlags -> [PackageDBFlag]
packageDBFlags DynFlags
idflags0 Bool -> Bool -> Bool
||
  DynFlags -> [Bool]
packageGFlags DynFlags
idflags1 [Bool] -> [Bool] -> Bool
forall a. Eq a => a -> a -> Bool
/= DynFlags -> [Bool]
packageGFlags DynFlags
idflags0
 where
   packageGFlags :: DynFlags -> [Bool]
packageGFlags DynFlags
dflags = (GeneralFlag -> Bool) -> [GeneralFlag] -> [Bool]
forall a b. (a -> b) -> [a] -> [b]
map (GeneralFlag -> DynFlags -> Bool
`gopt` DynFlags
dflags)
     [ GeneralFlag
Opt_HideAllPackages
     , GeneralFlag
Opt_HideAllPluginPackages
     , GeneralFlag
Opt_AutoLinkPackages ]

instance Outputable PackageFlag where
    ppr :: PackageFlag -> SDoc
ppr (ExposePackage String
n PackageArg
arg ModRenaming
rn) = String -> SDoc
text String
n SDoc -> SDoc -> SDoc
<> SDoc -> SDoc
braces (PackageArg -> SDoc
forall a. Outputable a => a -> SDoc
ppr PackageArg
arg SDoc -> SDoc -> SDoc
<+> ModRenaming -> SDoc
forall a. Outputable a => a -> SDoc
ppr ModRenaming
rn)
    ppr (HidePackage String
str) = String -> SDoc
text String
"-hide-package" SDoc -> SDoc -> SDoc
<+> String -> SDoc
text String
str

-- | The 'HscTarget' value corresponding to the default way to create
-- object files on the current platform.

defaultHscTarget :: Platform -> PlatformMisc -> HscTarget
defaultHscTarget :: Platform -> PlatformMisc -> HscTarget
defaultHscTarget Platform
platform PlatformMisc
pMisc
  | Platform -> Bool
platformUnregisterised Platform
platform = HscTarget
HscC
  | PlatformMisc -> Bool
platformMisc_ghcWithNativeCodeGen PlatformMisc
pMisc = HscTarget
HscAsm
  | Bool
otherwise = HscTarget
HscLlvm

defaultObjectTarget :: DynFlags -> HscTarget
defaultObjectTarget :: DynFlags -> HscTarget
defaultObjectTarget DynFlags
dflags = Platform -> PlatformMisc -> HscTarget
defaultHscTarget
  (DynFlags -> Platform
targetPlatform DynFlags
dflags)
  (DynFlags -> PlatformMisc
platformMisc DynFlags
dflags)

data DynLibLoader
  = Deployable
  | SystemDependent
  deriving DynLibLoader -> DynLibLoader -> Bool
(DynLibLoader -> DynLibLoader -> Bool)
-> (DynLibLoader -> DynLibLoader -> Bool) -> Eq DynLibLoader
forall a. (a -> a -> Bool) -> (a -> a -> Bool) -> Eq a
/= :: DynLibLoader -> DynLibLoader -> Bool
$c/= :: DynLibLoader -> DynLibLoader -> Bool
== :: DynLibLoader -> DynLibLoader -> Bool
$c== :: DynLibLoader -> DynLibLoader -> Bool
Eq

data RtsOptsEnabled
  = RtsOptsNone | RtsOptsIgnore | RtsOptsIgnoreAll | RtsOptsSafeOnly
  | RtsOptsAll
  deriving (Int -> RtsOptsEnabled -> ShowS
[RtsOptsEnabled] -> ShowS
RtsOptsEnabled -> String
(Int -> RtsOptsEnabled -> ShowS)
-> (RtsOptsEnabled -> String)
-> ([RtsOptsEnabled] -> ShowS)
-> Show RtsOptsEnabled
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
showList :: [RtsOptsEnabled] -> ShowS
$cshowList :: [RtsOptsEnabled] -> ShowS
show :: RtsOptsEnabled -> String
$cshow :: RtsOptsEnabled -> String
showsPrec :: Int -> RtsOptsEnabled -> ShowS
$cshowsPrec :: Int -> RtsOptsEnabled -> ShowS
Show)

shouldUseColor :: DynFlags -> Bool
shouldUseColor :: DynFlags -> Bool
shouldUseColor DynFlags
dflags = Bool -> OverridingBool -> Bool
overrideWith (DynFlags -> Bool
canUseColor DynFlags
dflags) (DynFlags -> OverridingBool
useColor DynFlags
dflags)

shouldUseHexWordLiterals :: DynFlags -> Bool
shouldUseHexWordLiterals :: DynFlags -> Bool
shouldUseHexWordLiterals DynFlags
dflags =
  GeneralFlag
Opt_HexWordLiterals GeneralFlag -> EnumSet GeneralFlag -> Bool
forall a. Enum a => a -> EnumSet a -> Bool
`EnumSet.member` DynFlags -> EnumSet GeneralFlag
generalFlags DynFlags
dflags

-- | Are we building with @-fPIE@ or @-fPIC@ enabled?
positionIndependent :: DynFlags -> Bool
positionIndependent :: DynFlags -> Bool
positionIndependent DynFlags
dflags = GeneralFlag -> DynFlags -> Bool
gopt GeneralFlag
Opt_PIC DynFlags
dflags Bool -> Bool -> Bool
|| GeneralFlag -> DynFlags -> Bool
gopt GeneralFlag
Opt_PIE DynFlags
dflags

-----------------------------------------------------------------------------
-- Ways

-- The central concept of a "way" is that all objects in a given
-- program must be compiled in the same "way".  Certain options change
-- parameters of the virtual machine, eg. profiling adds an extra word
-- to the object header, so profiling objects cannot be linked with
-- non-profiling objects.

-- After parsing the command-line options, we determine which "way" we
-- are building - this might be a combination way, eg. profiling+threaded.

-- We then find the "build-tag" associated with this way, and this
-- becomes the suffix used to find .hi files and libraries used in
-- this compilation.

data Way
  = WayCustom String -- for GHC API clients building custom variants
  | WayThreaded
  | WayDebug
  | WayProf
  | WayEventLog
  | WayDyn
  deriving (Way -> Way -> Bool
(Way -> Way -> Bool) -> (Way -> Way -> Bool) -> Eq Way
forall a. (a -> a -> Bool) -> (a -> a -> Bool) -> Eq a
/= :: Way -> Way -> Bool
$c/= :: Way -> Way -> Bool
== :: Way -> Way -> Bool
$c== :: Way -> Way -> Bool
Eq, Eq Way
Eq Way
-> (Way -> Way -> Ordering)
-> (Way -> Way -> Bool)
-> (Way -> Way -> Bool)
-> (Way -> Way -> Bool)
-> (Way -> Way -> Bool)
-> (Way -> Way -> Way)
-> (Way -> Way -> Way)
-> Ord Way
Way -> Way -> Bool
Way -> Way -> Ordering
Way -> Way -> Way
forall a.
Eq a
-> (a -> a -> Ordering)
-> (a -> a -> Bool)
-> (a -> a -> Bool)
-> (a -> a -> Bool)
-> (a -> a -> Bool)
-> (a -> a -> a)
-> (a -> a -> a)
-> Ord a
min :: Way -> Way -> Way
$cmin :: Way -> Way -> Way
max :: Way -> Way -> Way
$cmax :: Way -> Way -> Way
>= :: Way -> Way -> Bool
$c>= :: Way -> Way -> Bool
> :: Way -> Way -> Bool
$c> :: Way -> Way -> Bool
<= :: Way -> Way -> Bool
$c<= :: Way -> Way -> Bool
< :: Way -> Way -> Bool
$c< :: Way -> Way -> Bool
compare :: Way -> Way -> Ordering
$ccompare :: Way -> Way -> Ordering
$cp1Ord :: Eq Way
Ord, Int -> Way -> ShowS
[Way] -> ShowS
Way -> String
(Int -> Way -> ShowS)
-> (Way -> String) -> ([Way] -> ShowS) -> Show Way
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
showList :: [Way] -> ShowS
$cshowList :: [Way] -> ShowS
show :: Way -> String
$cshow :: Way -> String
showsPrec :: Int -> Way -> ShowS
$cshowsPrec :: Int -> Way -> ShowS
Show)

allowed_combination :: [Way] -> Bool
allowed_combination :: [Way] -> Bool
allowed_combination [Way]
way = [Bool] -> Bool
forall (t :: * -> *). Foldable t => t Bool -> Bool
and [ Way
x Way -> Way -> Bool
`allowedWith` Way
y
                              | Way
x <- [Way]
way, Way
y <- [Way]
way, Way
x Way -> Way -> Bool
forall a. Ord a => a -> a -> Bool
< Way
y ]
  where
        -- Note ordering in these tests: the left argument is
        -- <= the right argument, according to the Ord instance
        -- on Way above.

        -- dyn is allowed with everything
        Way
_ allowedWith :: Way -> Way -> Bool
`allowedWith` Way
WayDyn                  = Bool
True
        Way
WayDyn `allowedWith` Way
_                  = Bool
True

        -- debug is allowed with everything
        Way
_ `allowedWith` Way
WayDebug                = Bool
True
        Way
WayDebug `allowedWith` Way
_                = Bool
True

        (WayCustom {}) `allowedWith` Way
_          = Bool
True
        Way
WayThreaded `allowedWith` Way
WayProf       = Bool
True
        Way
WayThreaded `allowedWith` Way
WayEventLog   = Bool
True
        Way
WayProf     `allowedWith` Way
WayEventLog   = Bool
True
        Way
_ `allowedWith` Way
_                       = Bool
False

mkBuildTag :: [Way] -> String
mkBuildTag :: [Way] -> String
mkBuildTag [Way]
ways = [String] -> String
forall (t :: * -> *) a. Foldable t => t [a] -> [a]
concat (String -> [String] -> [String]
forall a. a -> [a] -> [a]
intersperse String
"_" ((Way -> String) -> [Way] -> [String]
forall a b. (a -> b) -> [a] -> [b]
map Way -> String
wayTag [Way]
ways))

wayTag :: Way -> String
wayTag :: Way -> String
wayTag (WayCustom String
xs) = String
xs
wayTag Way
WayThreaded = String
"thr"
wayTag Way
WayDebug    = String
"debug"
wayTag Way
WayDyn      = String
"dyn"
wayTag Way
WayProf     = String
"p"
wayTag Way
WayEventLog = String
"l"

wayRTSOnly :: Way -> Bool
wayRTSOnly :: Way -> Bool
wayRTSOnly (WayCustom {}) = Bool
False
wayRTSOnly Way
WayThreaded = Bool
True
wayRTSOnly Way
WayDebug    = Bool
True
wayRTSOnly Way
WayDyn      = Bool
False
wayRTSOnly Way
WayProf     = Bool
False
wayRTSOnly Way
WayEventLog = Bool
True

wayDesc :: Way -> String
wayDesc :: Way -> String
wayDesc (WayCustom String
xs) = String
xs
wayDesc Way
WayThreaded = String
"Threaded"
wayDesc Way
WayDebug    = String
"Debug"
wayDesc Way
WayDyn      = String
"Dynamic"
wayDesc Way
WayProf     = String
"Profiling"
wayDesc Way
WayEventLog = String
"RTS Event Logging"

-- Turn these flags on when enabling this way
wayGeneralFlags :: Platform -> Way -> [GeneralFlag]
wayGeneralFlags :: Platform -> Way -> [GeneralFlag]
wayGeneralFlags Platform
_ (WayCustom {}) = []
wayGeneralFlags Platform
_ Way
WayThreaded = []
wayGeneralFlags Platform
_ Way
WayDebug    = []
wayGeneralFlags Platform
_ Way
WayDyn      = [GeneralFlag
Opt_PIC, GeneralFlag
Opt_ExternalDynamicRefs]
    -- We could get away without adding -fPIC when compiling the
    -- modules of a program that is to be linked with -dynamic; the
    -- program itself does not need to be position-independent, only
    -- the libraries need to be.  HOWEVER, GHCi links objects into a
    -- .so before loading the .so using the system linker.  Since only
    -- PIC objects can be linked into a .so, we have to compile even
    -- modules of the main program with -fPIC when using -dynamic.
wayGeneralFlags Platform
_ Way
WayProf     = [GeneralFlag
Opt_SccProfilingOn]
wayGeneralFlags Platform
_ Way
WayEventLog = []

-- Turn these flags off when enabling this way
wayUnsetGeneralFlags :: Platform -> Way -> [GeneralFlag]
wayUnsetGeneralFlags :: Platform -> Way -> [GeneralFlag]
wayUnsetGeneralFlags Platform
_ (WayCustom {}) = []
wayUnsetGeneralFlags Platform
_ Way
WayThreaded = []
wayUnsetGeneralFlags Platform
_ Way
WayDebug    = []
wayUnsetGeneralFlags Platform
_ Way
WayDyn      = [-- There's no point splitting
                                      -- when we're going to be dynamically
                                      -- linking. Plus it breaks compilation
                                      -- on OSX x86.
                                      GeneralFlag
Opt_SplitSections]
wayUnsetGeneralFlags Platform
_ Way
WayProf     = []
wayUnsetGeneralFlags Platform
_ Way
WayEventLog = []

wayOptc :: Platform -> Way -> [String]
wayOptc :: Platform -> Way -> [String]
wayOptc Platform
_ (WayCustom {}) = []
wayOptc Platform
platform Way
WayThreaded = case Platform -> OS
platformOS Platform
platform of
                               OS
OSOpenBSD -> [String
"-pthread"]
                               OS
OSNetBSD  -> [String
"-pthread"]
                               OS
_         -> []
wayOptc Platform
_ Way
WayDebug      = []
wayOptc Platform
_ Way
WayDyn        = []
wayOptc Platform
_ Way
WayProf       = [String
"-DPROFILING"]
wayOptc Platform
_ Way
WayEventLog   = [String
"-DTRACING"]

wayOptl :: Platform -> Way -> [String]
wayOptl :: Platform -> Way -> [String]
wayOptl Platform
_ (WayCustom {}) = []
wayOptl Platform
platform Way
WayThreaded =
        case Platform -> OS
platformOS Platform
platform of
        OS
OSFreeBSD  -> [String
"-pthread"]
        OS
OSOpenBSD  -> [String
"-pthread"]
        OS
OSNetBSD   -> [String
"-pthread"]
        OS
_          -> []
wayOptl Platform
_ Way
WayDebug      = []
wayOptl Platform
_ Way
WayDyn        = []
wayOptl Platform
_ Way
WayProf       = []
wayOptl Platform
_ Way
WayEventLog   = []

wayOptP :: Platform -> Way -> [String]
wayOptP :: Platform -> Way -> [String]
wayOptP Platform
_ (WayCustom {}) = []
wayOptP Platform
_ Way
WayThreaded = []
wayOptP Platform
_ Way
WayDebug    = []
wayOptP Platform
_ Way
WayDyn      = []
wayOptP Platform
_ Way
WayProf     = [String
"-DPROFILING"]
wayOptP Platform
_ Way
WayEventLog = [String
"-DTRACING"]

whenGeneratingDynamicToo :: MonadIO m => DynFlags -> m () -> m ()
whenGeneratingDynamicToo :: DynFlags -> m () -> m ()
whenGeneratingDynamicToo DynFlags
dflags m ()
f = DynFlags -> m () -> m () -> m ()
forall (m :: * -> *) a. MonadIO m => DynFlags -> m a -> m a -> m a
ifGeneratingDynamicToo DynFlags
dflags m ()
f (() -> m ()
forall (m :: * -> *) a. Monad m => a -> m a
return ())

ifGeneratingDynamicToo :: MonadIO m => DynFlags -> m a -> m a -> m a
ifGeneratingDynamicToo :: DynFlags -> m a -> m a -> m a
ifGeneratingDynamicToo DynFlags
dflags m a
f m a
g = DynFlags -> m a -> m a -> m a -> m a
forall (m :: * -> *) a.
MonadIO m =>
DynFlags -> m a -> m a -> m a -> m a
generateDynamicTooConditional DynFlags
dflags m a
f m a
g m a
g

whenCannotGenerateDynamicToo :: MonadIO m => DynFlags -> m () -> m ()
whenCannotGenerateDynamicToo :: DynFlags -> m () -> m ()
whenCannotGenerateDynamicToo DynFlags
dflags m ()
f
    = DynFlags -> m () -> m () -> m ()
forall (m :: * -> *) a. MonadIO m => DynFlags -> m a -> m a -> m a
ifCannotGenerateDynamicToo DynFlags
dflags m ()
f (() -> m ()
forall (m :: * -> *) a. Monad m => a -> m a
return ())

ifCannotGenerateDynamicToo :: MonadIO m => DynFlags -> m a -> m a -> m a
ifCannotGenerateDynamicToo :: DynFlags -> m a -> m a -> m a
ifCannotGenerateDynamicToo DynFlags
dflags m a
f m a
g
    = DynFlags -> m a -> m a -> m a -> m a
forall (m :: * -> *) a.
MonadIO m =>
DynFlags -> m a -> m a -> m a -> m a
generateDynamicTooConditional DynFlags
dflags m a
g m a
f m a
g

generateDynamicTooConditional :: MonadIO m
                              => DynFlags -> m a -> m a -> m a -> m a
generateDynamicTooConditional :: DynFlags -> m a -> m a -> m a -> m a
generateDynamicTooConditional DynFlags
dflags m a
canGen m a
cannotGen m a
notTryingToGen
    = if GeneralFlag -> DynFlags -> Bool
gopt GeneralFlag
Opt_BuildDynamicToo DynFlags
dflags
      then do let ref :: IORef Bool
ref = DynFlags -> IORef Bool
canGenerateDynamicToo DynFlags
dflags
              Bool
b <- IO Bool -> m Bool
forall (m :: * -> *) a. MonadIO m => IO a -> m a
liftIO (IO Bool -> m Bool) -> IO Bool -> m Bool
forall a b. (a -> b) -> a -> b
$ IORef Bool -> IO Bool
forall a. IORef a -> IO a
readIORef IORef Bool
ref
              if Bool
b then m a
canGen else m a
cannotGen
      else m a
notTryingToGen

dynamicTooMkDynamicDynFlags :: DynFlags -> DynFlags
dynamicTooMkDynamicDynFlags :: DynFlags -> DynFlags
dynamicTooMkDynamicDynFlags DynFlags
dflags0
    = let dflags1 :: DynFlags
dflags1 = Way -> DynFlags -> DynFlags
addWay' Way
WayDyn DynFlags
dflags0
          dflags2 :: DynFlags
dflags2 = DynFlags
dflags1 {
                        outputFile :: Maybe String
outputFile = DynFlags -> Maybe String
dynOutputFile DynFlags
dflags1,
                        hiSuf :: String
hiSuf = DynFlags -> String
dynHiSuf DynFlags
dflags1,
                        objectSuf :: String
objectSuf = DynFlags -> String
dynObjectSuf DynFlags
dflags1
                    }
          dflags3 :: DynFlags
dflags3 = DynFlags -> DynFlags
updateWays DynFlags
dflags2
          dflags4 :: DynFlags
dflags4 = DynFlags -> GeneralFlag -> DynFlags
gopt_unset DynFlags
dflags3 GeneralFlag
Opt_BuildDynamicToo
      in DynFlags
dflags4

-- | Compute the path of the dynamic object corresponding to an object file.
dynamicOutputFile :: DynFlags -> FilePath -> FilePath
dynamicOutputFile :: DynFlags -> ShowS
dynamicOutputFile DynFlags
dflags String
outputFile = ShowS
dynOut String
outputFile
  where
    dynOut :: ShowS
dynOut = (String -> ShowS) -> String -> ShowS
forall a b c. (a -> b -> c) -> b -> a -> c
flip String -> ShowS
addExtension (DynFlags -> String
dynObjectSuf DynFlags
dflags) ShowS -> ShowS -> ShowS
forall b c a. (b -> c) -> (a -> b) -> a -> c
. ShowS
dropExtension

-----------------------------------------------------------------------------

-- | Used by 'GHC.runGhc' to partially initialize a new 'DynFlags' value
initDynFlags :: DynFlags -> IO DynFlags
initDynFlags :: DynFlags -> IO DynFlags
initDynFlags DynFlags
dflags = do
 let -- We can't build with dynamic-too on Windows, as labels before
     -- the fork point are different depending on whether we are
     -- building dynamically or not.
     platformCanGenerateDynamicToo :: Bool
platformCanGenerateDynamicToo
         = Platform -> OS
platformOS (DynFlags -> Platform
targetPlatform DynFlags
dflags) OS -> OS -> Bool
forall a. Eq a => a -> a -> Bool
/= OS
OSMinGW32
 IORef Bool
refCanGenerateDynamicToo <- Bool -> IO (IORef Bool)
forall a. a -> IO (IORef a)
newIORef Bool
platformCanGenerateDynamicToo
 IORef Int
refNextTempSuffix <- Int -> IO (IORef Int)
forall a. a -> IO (IORef a)
newIORef Int
0
 IORef FilesToClean
refFilesToClean <- FilesToClean -> IO (IORef FilesToClean)
forall a. a -> IO (IORef a)
newIORef FilesToClean
emptyFilesToClean
 IORef (Map String String)
refDirsToClean <- Map String String -> IO (IORef (Map String String))
forall a. a -> IO (IORef a)
newIORef Map String String
forall k a. Map k a
Map.empty
 IORef (Set String)
refGeneratedDumps <- Set String -> IO (IORef (Set String))
forall a. a -> IO (IORef a)
newIORef Set String
forall a. Set a
Set.empty
 IORef (Maybe LinkerInfo)
refRtldInfo <- Maybe LinkerInfo -> IO (IORef (Maybe LinkerInfo))
forall a. a -> IO (IORef a)
newIORef Maybe LinkerInfo
forall a. Maybe a
Nothing
 IORef (Maybe CompilerInfo)
refRtccInfo <- Maybe CompilerInfo -> IO (IORef (Maybe CompilerInfo))
forall a. a -> IO (IORef a)
newIORef Maybe CompilerInfo
forall a. Maybe a
Nothing
 IORef (ModuleEnv Int)
wrapperNum <- ModuleEnv Int -> IO (IORef (ModuleEnv Int))
forall a. a -> IO (IORef a)
newIORef ModuleEnv Int
forall a. ModuleEnv a
emptyModuleEnv
 Bool
canUseUnicode <- do let enc :: TextEncoding
enc = TextEncoding
localeEncoding
                         str :: String
str = String
"‘’"
                     (TextEncoding -> String -> (CString -> IO Bool) -> IO Bool
forall a. TextEncoding -> String -> (CString -> IO a) -> IO a
withCString TextEncoding
enc String
str ((CString -> IO Bool) -> IO Bool)
-> (CString -> IO Bool) -> IO Bool
forall a b. (a -> b) -> a -> b
$ \CString
cstr ->
                          do String
str' <- TextEncoding -> CString -> IO String
peekCString TextEncoding
enc CString
cstr
                             Bool -> IO Bool
forall (m :: * -> *) a. Monad m => a -> m a
return (String
str String -> String -> Bool
forall a. Eq a => a -> a -> Bool
== String
str'))
                         IO Bool -> (IOError -> IO Bool) -> IO Bool
forall a. IO a -> (IOError -> IO a) -> IO a
`catchIOError` \IOError
_ -> Bool -> IO Bool
forall (m :: * -> *) a. Monad m => a -> m a
return Bool
False
 Maybe String
maybeGhcNoUnicodeEnv <- String -> IO (Maybe String)
lookupEnv String
"GHC_NO_UNICODE"
 let adjustNoUnicode :: Maybe a -> Bool
adjustNoUnicode (Just a
_) = Bool
False
     adjustNoUnicode Maybe a
Nothing = Bool
True
 let useUnicode' :: Bool
useUnicode' = (Maybe String -> Bool
forall a. Maybe a -> Bool
adjustNoUnicode Maybe String
maybeGhcNoUnicodeEnv) Bool -> Bool -> Bool
&& Bool
canUseUnicode
 Bool
canUseColor <- IO Bool
stderrSupportsAnsiColors
 Maybe String
maybeGhcColorsEnv  <- String -> IO (Maybe String)
lookupEnv String
"GHC_COLORS"
 Maybe String
maybeGhcColoursEnv <- String -> IO (Maybe String)
lookupEnv String
"GHC_COLOURS"
 let adjustCols :: Maybe String
-> (OverridingBool, Scheme) -> (OverridingBool, Scheme)
adjustCols (Just String
env) = String -> (OverridingBool, Scheme) -> (OverridingBool, Scheme)
Col.parseScheme String
env
     adjustCols Maybe String
Nothing    = (OverridingBool, Scheme) -> (OverridingBool, Scheme)
forall a. a -> a
id
 let (OverridingBool
useColor', Scheme
colScheme') =
       (Maybe String
-> (OverridingBool, Scheme) -> (OverridingBool, Scheme)
adjustCols Maybe String
maybeGhcColoursEnv ((OverridingBool, Scheme) -> (OverridingBool, Scheme))
-> ((OverridingBool, Scheme) -> (OverridingBool, Scheme))
-> (OverridingBool, Scheme)
-> (OverridingBool, Scheme)
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Maybe String
-> (OverridingBool, Scheme) -> (OverridingBool, Scheme)
adjustCols Maybe String
maybeGhcColorsEnv)
       (DynFlags -> OverridingBool
useColor DynFlags
dflags, DynFlags -> Scheme
colScheme DynFlags
dflags)
 DynFlags -> IO DynFlags
forall (m :: * -> *) a. Monad m => a -> m a
return DynFlags
dflags{
        canGenerateDynamicToo :: IORef Bool
canGenerateDynamicToo = IORef Bool
refCanGenerateDynamicToo,
        nextTempSuffix :: IORef Int
nextTempSuffix = IORef Int
refNextTempSuffix,
        filesToClean :: IORef FilesToClean
filesToClean   = IORef FilesToClean
refFilesToClean,
        dirsToClean :: IORef (Map String String)
dirsToClean    = IORef (Map String String)
refDirsToClean,
        generatedDumps :: IORef (Set String)
generatedDumps = IORef (Set String)
refGeneratedDumps,
        nextWrapperNum :: IORef (ModuleEnv Int)
nextWrapperNum = IORef (ModuleEnv Int)
wrapperNum,
        useUnicode :: Bool
useUnicode    = Bool
useUnicode',
        useColor :: OverridingBool
useColor      = OverridingBool
useColor',
        canUseColor :: Bool
canUseColor   = Bool
canUseColor,
        colScheme :: Scheme
colScheme     = Scheme
colScheme',
        rtldInfo :: IORef (Maybe LinkerInfo)
rtldInfo      = IORef (Maybe LinkerInfo)
refRtldInfo,
        rtccInfo :: IORef (Maybe CompilerInfo)
rtccInfo      = IORef (Maybe CompilerInfo)
refRtccInfo
        }

-- | The normal 'DynFlags'. Note that they are not suitable for use in this form
-- and must be fully initialized by 'GHC.runGhc' first.
defaultDynFlags :: Settings -> LlvmConfig -> DynFlags
defaultDynFlags :: Settings -> LlvmConfig -> DynFlags
defaultDynFlags Settings
mySettings LlvmConfig
llvmConfig =
-- See Note [Updating flag description in the User's Guide]
     DynFlags :: GhcMode
-> GhcLink
-> HscTarget
-> GhcNameVersion
-> FileSettings
-> Platform
-> ToolSettings
-> PlatformMisc
-> PlatformConstants
-> [(String, String)]
-> IntegerLibrary
-> LlvmConfig
-> Int
-> Int
-> Int
-> Int
-> Int
-> Maybe String
-> Maybe String
-> [Int]
-> Maybe Int
-> Bool
-> Maybe Int
-> Maybe Int
-> Maybe Int
-> Maybe Int
-> Maybe Int
-> Int
-> Int
-> Int
-> Maybe Int
-> Maybe Int
-> Int
-> Word
-> Maybe Int
-> Maybe Int
-> Maybe Int
-> Maybe Int
-> Bool
-> Maybe Int
-> Int
-> [String]
-> Module
-> Maybe String
-> IntWithInf
-> IntWithInf
-> InstalledUnitId
-> Maybe ComponentId
-> Maybe [(ModuleName, Module)]
-> [Way]
-> String
-> Maybe (String, Int)
-> Maybe String
-> Maybe String
-> Maybe String
-> Maybe String
-> Maybe String
-> Maybe String
-> String
-> String
-> String
-> String
-> IORef Bool
-> String
-> String
-> Maybe String
-> Maybe String
-> Maybe String
-> DynLibLoader
-> Maybe String
-> Maybe String
-> [Option]
-> IncludeSpecs
-> [String]
-> [String]
-> [String]
-> Maybe String
-> RtsOptsEnabled
-> Bool
-> String
-> [ModuleName]
-> [(ModuleName, String)]
-> [String]
-> [LoadedPlugin]
-> [StaticPlugin]
-> Hooks
-> String
-> Bool
-> Bool
-> [ModuleName]
-> [String]
-> [PackageDBFlag]
-> [IgnorePackageFlag]
-> [PackageFlag]
-> [PackageFlag]
-> [TrustFlag]
-> Maybe String
-> Maybe [(String, [PackageConfig])]
-> PackageState
-> IORef FilesToClean
-> IORef (Map String String)
-> IORef Int
-> IORef (Set String)
-> EnumSet DumpFlag
-> EnumSet GeneralFlag
-> EnumSet WarningFlag
-> EnumSet WarningFlag
-> Maybe Language
-> SafeHaskellMode
-> Bool
-> Bool
-> SrcSpan
-> SrcSpan
-> SrcSpan
-> SrcSpan
-> SrcSpan
-> SrcSpan
-> SrcSpan
-> SrcSpan
-> [OnOff Extension]
-> EnumSet Extension
-> Int
-> Int
-> Int
-> Int
-> Float
-> Int
-> Bool
-> Int
-> Int
-> LogAction
-> FlushOut
-> FlushErr
-> Maybe String
-> Maybe String
-> [String]
-> Int
-> Int
-> Bool
-> OverridingBool
-> Bool
-> Scheme
-> ProfAuto
-> Maybe String
-> IORef (ModuleEnv Int)
-> Maybe SseVersion
-> Maybe BmiVersion
-> Bool
-> Bool
-> Bool
-> Bool
-> Bool
-> Bool
-> IORef (Maybe LinkerInfo)
-> IORef (Maybe CompilerInfo)
-> Int
-> Int
-> Int
-> Bool
-> Maybe Int
-> Int
-> Int
-> CfgWeights
-> DynFlags
DynFlags {
        ghcMode :: GhcMode
ghcMode                 = GhcMode
CompManager,
        ghcLink :: GhcLink
ghcLink                 = GhcLink
LinkBinary,
        hscTarget :: HscTarget
hscTarget               = Platform -> PlatformMisc -> HscTarget
defaultHscTarget (Settings -> Platform
sTargetPlatform Settings
mySettings) (Settings -> PlatformMisc
sPlatformMisc Settings
mySettings),
        integerLibrary :: IntegerLibrary
integerLibrary          = Settings -> IntegerLibrary
sIntegerLibraryType Settings
mySettings,
        verbosity :: Int
verbosity               = Int
0,
        optLevel :: Int
optLevel                = Int
0,
        debugLevel :: Int
debugLevel              = Int
0,
        simplPhases :: Int
simplPhases             = Int
2,
        maxSimplIterations :: Int
maxSimplIterations      = Int
4,
        ruleCheck :: Maybe String
ruleCheck               = Maybe String
forall a. Maybe a
Nothing,
        inlineCheck :: Maybe String
inlineCheck             = Maybe String
forall a. Maybe a
Nothing,
        binBlobThreshold :: Word
binBlobThreshold        = Word
500000, -- 500K is a good default (see #16190)
        maxRelevantBinds :: Maybe Int
maxRelevantBinds        = Int -> Maybe Int
forall a. a -> Maybe a
Just Int
6,
        maxValidHoleFits :: Maybe Int
maxValidHoleFits   = Int -> Maybe Int
forall a. a -> Maybe a
Just Int
6,
        maxRefHoleFits :: Maybe Int
maxRefHoleFits     = Int -> Maybe Int
forall a. a -> Maybe a
Just Int
6,
        refLevelHoleFits :: Maybe Int
refLevelHoleFits   = Maybe Int
forall a. Maybe a
Nothing,
        maxUncoveredPatterns :: Int
maxUncoveredPatterns    = Int
4,
        maxPmCheckModels :: Int
maxPmCheckModels        = Int
100,
        simplTickFactor :: Int
simplTickFactor         = Int
100,
        specConstrThreshold :: Maybe Int
specConstrThreshold     = Int -> Maybe Int
forall a. a -> Maybe a
Just Int
2000,
        specConstrCount :: Maybe Int
specConstrCount         = Int -> Maybe Int
forall a. a -> Maybe a
Just Int
3,
        specConstrRecursive :: Int
specConstrRecursive     = Int
3,
        liberateCaseThreshold :: Maybe Int
liberateCaseThreshold   = Int -> Maybe Int
forall a. a -> Maybe a
Just Int
2000,
        floatLamArgs :: Maybe Int
floatLamArgs            = Int -> Maybe Int
forall a. a -> Maybe a
Just Int
0, -- Default: float only if no fvs
        liftLamsRecArgs :: Maybe Int
liftLamsRecArgs         = Int -> Maybe Int
forall a. a -> Maybe a
Just Int
5, -- Default: the number of available argument hardware registers on x86_64
        liftLamsNonRecArgs :: Maybe Int
liftLamsNonRecArgs      = Int -> Maybe Int
forall a. a -> Maybe a
Just Int
5, -- Default: the number of available argument hardware registers on x86_64
        liftLamsKnown :: Bool
liftLamsKnown           = Bool
False,  -- Default: don't turn known calls into unknown ones
        cmmProcAlignment :: Maybe Int
cmmProcAlignment        = Maybe Int
forall a. Maybe a
Nothing,

        historySize :: Int
historySize             = Int
20,
        strictnessBefore :: [Int]
strictnessBefore        = [],

        parMakeCount :: Maybe Int
parMakeCount            = Int -> Maybe Int
forall a. a -> Maybe a
Just Int
1,

        enableTimeStats :: Bool
enableTimeStats         = Bool
False,
        ghcHeapSize :: Maybe Int
ghcHeapSize             = Maybe Int
forall a. Maybe a
Nothing,

        importPaths :: [String]
importPaths             = [String
"."],
        mainModIs :: Module
mainModIs               = Module
mAIN,
        mainFunIs :: Maybe String
mainFunIs               = Maybe String
forall a. Maybe a
Nothing,
        reductionDepth :: IntWithInf
reductionDepth          = Int -> IntWithInf
treatZeroAsInf Int
mAX_REDUCTION_DEPTH,
        solverIterations :: IntWithInf
solverIterations        = Int -> IntWithInf
treatZeroAsInf Int
mAX_SOLVER_ITERATIONS,

        thisInstalledUnitId :: InstalledUnitId
thisInstalledUnitId     = UnitId -> InstalledUnitId
toInstalledUnitId UnitId
mainUnitId,
        thisUnitIdInsts_ :: Maybe [(ModuleName, Module)]
thisUnitIdInsts_        = Maybe [(ModuleName, Module)]
forall a. Maybe a
Nothing,
        thisComponentId_ :: Maybe ComponentId
thisComponentId_        = Maybe ComponentId
forall a. Maybe a
Nothing,

        objectDir :: Maybe String
objectDir               = Maybe String
forall a. Maybe a
Nothing,
        dylibInstallName :: Maybe String
dylibInstallName        = Maybe String
forall a. Maybe a
Nothing,
        hiDir :: Maybe String
hiDir                   = Maybe String
forall a. Maybe a
Nothing,
        hieDir :: Maybe String
hieDir                  = Maybe String
forall a. Maybe a
Nothing,
        stubDir :: Maybe String
stubDir                 = Maybe String
forall a. Maybe a
Nothing,
        dumpDir :: Maybe String
dumpDir                 = Maybe String
forall a. Maybe a
Nothing,

        objectSuf :: String
objectSuf               = Phase -> String
phaseInputExt Phase
StopLn,
        hcSuf :: String
hcSuf                   = Phase -> String
phaseInputExt Phase
HCc,
        hiSuf :: String
hiSuf                   = String
"hi",
        hieSuf :: String
hieSuf                  = String
"hie",

        canGenerateDynamicToo :: IORef Bool
canGenerateDynamicToo   = String -> IORef Bool
forall a. String -> a
panic String
"defaultDynFlags: No canGenerateDynamicToo",
        dynObjectSuf :: String
dynObjectSuf            = String
"dyn_" String -> ShowS
forall a. [a] -> [a] -> [a]
++ Phase -> String
phaseInputExt Phase
StopLn,
        dynHiSuf :: String
dynHiSuf                = String
"dyn_hi",

        pluginModNames :: [ModuleName]
pluginModNames          = [],
        pluginModNameOpts :: [(ModuleName, String)]
pluginModNameOpts       = [],
        frontendPluginOpts :: [String]
frontendPluginOpts      = [],
        cachedPlugins :: [LoadedPlugin]
cachedPlugins           = [],
        staticPlugins :: [StaticPlugin]
staticPlugins           = [],
        hooks :: Hooks
hooks                   = Hooks
emptyHooks,

        outputFile :: Maybe String
outputFile              = Maybe String
forall a. Maybe a
Nothing,
        dynOutputFile :: Maybe String
dynOutputFile           = Maybe String
forall a. Maybe a
Nothing,
        outputHi :: Maybe String
outputHi                = Maybe String
forall a. Maybe a
Nothing,
        dynLibLoader :: DynLibLoader
dynLibLoader            = DynLibLoader
SystemDependent,
        dumpPrefix :: Maybe String
dumpPrefix              = Maybe String
forall a. Maybe a
Nothing,
        dumpPrefixForce :: Maybe String
dumpPrefixForce         = Maybe String
forall a. Maybe a
Nothing,
        ldInputs :: [Option]
ldInputs                = [],
        includePaths :: IncludeSpecs
includePaths            = [String] -> [String] -> IncludeSpecs
IncludeSpecs [] [],
        libraryPaths :: [String]
libraryPaths            = [],
        frameworkPaths :: [String]
frameworkPaths          = [],
        cmdlineFrameworks :: [String]
cmdlineFrameworks       = [],
        rtsOpts :: Maybe String
rtsOpts                 = Maybe String
forall a. Maybe a
Nothing,
        rtsOptsEnabled :: RtsOptsEnabled
rtsOptsEnabled          = RtsOptsEnabled
RtsOptsSafeOnly,
        rtsOptsSuggestions :: Bool
rtsOptsSuggestions      = Bool
True,

        hpcDir :: String
hpcDir                  = String
".hpc",

        packageDBFlags :: [PackageDBFlag]
packageDBFlags          = [],
        packageFlags :: [PackageFlag]
packageFlags            = [],
        pluginPackageFlags :: [PackageFlag]
pluginPackageFlags      = [],
        ignorePackageFlags :: [IgnorePackageFlag]
ignorePackageFlags      = [],
        trustFlags :: [TrustFlag]
trustFlags              = [],
        packageEnv :: Maybe String
packageEnv              = Maybe String
forall a. Maybe a
Nothing,
        pkgDatabase :: Maybe [(String, [PackageConfig])]
pkgDatabase             = Maybe [(String, [PackageConfig])]
forall a. Maybe a
Nothing,
        -- This gets filled in with GHC.setSessionDynFlags
        pkgState :: PackageState
pkgState                = PackageState
emptyPackageState,
        ways :: [Way]
ways                    = Settings -> [Way]
defaultWays Settings
mySettings,
        buildTag :: String
buildTag                = [Way] -> String
mkBuildTag (Settings -> [Way]
defaultWays Settings
mySettings),
        splitInfo :: Maybe (String, Int)
splitInfo               = Maybe (String, Int)
forall a. Maybe a
Nothing,

        ghcNameVersion :: GhcNameVersion
ghcNameVersion = Settings -> GhcNameVersion
sGhcNameVersion Settings
mySettings,
        fileSettings :: FileSettings
fileSettings = Settings -> FileSettings
sFileSettings Settings
mySettings,
        toolSettings :: ToolSettings
toolSettings = Settings -> ToolSettings
sToolSettings Settings
mySettings,
        targetPlatform :: Platform
targetPlatform = Settings -> Platform
sTargetPlatform Settings
mySettings,
        platformMisc :: PlatformMisc
platformMisc = Settings -> PlatformMisc
sPlatformMisc Settings
mySettings,
        platformConstants :: PlatformConstants
platformConstants = Settings -> PlatformConstants
sPlatformConstants Settings
mySettings,
        rawSettings :: [(String, String)]
rawSettings = Settings -> [(String, String)]
sRawSettings Settings
mySettings,

        -- See Note [LLVM configuration].
        llvmConfig :: LlvmConfig
llvmConfig              = LlvmConfig
llvmConfig,

        -- ghc -M values
        depMakefile :: String
depMakefile       = String
"Makefile",
        depIncludePkgDeps :: Bool
depIncludePkgDeps = Bool
False,
        depIncludeCppDeps :: Bool
depIncludeCppDeps = Bool
False,
        depExcludeMods :: [ModuleName]
depExcludeMods    = [],
        depSuffixes :: [String]
depSuffixes       = [],
        -- end of ghc -M values
        nextTempSuffix :: IORef Int
nextTempSuffix = String -> IORef Int
forall a. String -> a
panic String
"defaultDynFlags: No nextTempSuffix",
        filesToClean :: IORef FilesToClean
filesToClean   = String -> IORef FilesToClean
forall a. String -> a
panic String
"defaultDynFlags: No filesToClean",
        dirsToClean :: IORef (Map String String)
dirsToClean    = String -> IORef (Map String String)
forall a. String -> a
panic String
"defaultDynFlags: No dirsToClean",
        generatedDumps :: IORef (Set String)
generatedDumps = String -> IORef (Set String)
forall a. String -> a
panic String
"defaultDynFlags: No generatedDumps",
        ghcVersionFile :: Maybe String
ghcVersionFile = Maybe String
forall a. Maybe a
Nothing,
        haddockOptions :: Maybe String
haddockOptions = Maybe String
forall a. Maybe a
Nothing,
        dumpFlags :: EnumSet DumpFlag
dumpFlags = EnumSet DumpFlag
forall a. EnumSet a
EnumSet.empty,
        generalFlags :: EnumSet GeneralFlag
generalFlags = [GeneralFlag] -> EnumSet GeneralFlag
forall a. Enum a => [a] -> EnumSet a
EnumSet.fromList (Settings -> [GeneralFlag]
defaultFlags Settings
mySettings),
        warningFlags :: EnumSet WarningFlag
warningFlags = [WarningFlag] -> EnumSet WarningFlag
forall a. Enum a => [a] -> EnumSet a
EnumSet.fromList [WarningFlag]
standardWarnings,
        fatalWarningFlags :: EnumSet WarningFlag
fatalWarningFlags = EnumSet WarningFlag
forall a. EnumSet a
EnumSet.empty,
        ghciScripts :: [String]
ghciScripts = [],
        language :: Maybe Language
language = Maybe Language
forall a. Maybe a
Nothing,
        safeHaskell :: SafeHaskellMode
safeHaskell = SafeHaskellMode
Sf_None,
        safeInfer :: Bool
safeInfer   = Bool
True,
        safeInferred :: Bool
safeInferred = Bool
True,
        thOnLoc :: SrcSpan
thOnLoc = SrcSpan
noSrcSpan,
        newDerivOnLoc :: SrcSpan
newDerivOnLoc = SrcSpan
noSrcSpan,
        overlapInstLoc :: SrcSpan
overlapInstLoc = SrcSpan
noSrcSpan,
        incoherentOnLoc :: SrcSpan
incoherentOnLoc = SrcSpan
noSrcSpan,
        pkgTrustOnLoc :: SrcSpan
pkgTrustOnLoc = SrcSpan
noSrcSpan,
        warnSafeOnLoc :: SrcSpan
warnSafeOnLoc = SrcSpan
noSrcSpan,
        warnUnsafeOnLoc :: SrcSpan
warnUnsafeOnLoc = SrcSpan
noSrcSpan,
        trustworthyOnLoc :: SrcSpan
trustworthyOnLoc = SrcSpan
noSrcSpan,
        extensions :: [OnOff Extension]
extensions = [],
        extensionFlags :: EnumSet Extension
extensionFlags = Maybe Language -> [OnOff Extension] -> EnumSet Extension
flattenExtensionFlags Maybe Language
forall a. Maybe a
Nothing [],

        -- The ufCreationThreshold threshold must be reasonably high to
        -- take account of possible discounts.
        -- E.g. 450 is not enough in 'fulsom' for Interval.sqr to inline
        -- into Csg.calc (The unfolding for sqr never makes it into the
        -- interface file.)
        ufCreationThreshold :: Int
ufCreationThreshold = Int
750,
        ufUseThreshold :: Int
ufUseThreshold      = Int
60,
        ufFunAppDiscount :: Int
ufFunAppDiscount    = Int
60,
        -- Be fairly keen to inline a function if that means
        -- we'll be able to pick the right method from a dictionary
        ufDictDiscount :: Int
ufDictDiscount      = Int
30,
        ufKeenessFactor :: Float
ufKeenessFactor     = Float
1.5,
        ufDearOp :: Int
ufDearOp            = Int
40,
        ufVeryAggressive :: Bool
ufVeryAggressive    = Bool
False,

        maxWorkerArgs :: Int
maxWorkerArgs = Int
10,

        ghciHistSize :: Int
ghciHistSize = Int
50, -- keep a log of length 50 by default

        -- Logging

        log_action :: LogAction
log_action = LogAction
defaultLogAction,

        flushOut :: FlushOut
flushOut = FlushOut
defaultFlushOut,
        flushErr :: FlushErr
flushErr = FlushErr
defaultFlushErr,
        pprUserLength :: Int
pprUserLength = Int
5,
        pprCols :: Int
pprCols = Int
100,
        useUnicode :: Bool
useUnicode = Bool
False,
        useColor :: OverridingBool
useColor = OverridingBool
Auto,
        canUseColor :: Bool
canUseColor = Bool
False,
        colScheme :: Scheme
colScheme = Scheme
Col.defaultScheme,
        profAuto :: ProfAuto
profAuto = ProfAuto
NoProfAuto,
        interactivePrint :: Maybe String
interactivePrint = Maybe String
forall a. Maybe a
Nothing,
        nextWrapperNum :: IORef (ModuleEnv Int)
nextWrapperNum = String -> IORef (ModuleEnv Int)
forall a. String -> a
panic String
"defaultDynFlags: No nextWrapperNum",
        sseVersion :: Maybe SseVersion
sseVersion = Maybe SseVersion
forall a. Maybe a
Nothing,
        bmiVersion :: Maybe BmiVersion
bmiVersion = Maybe BmiVersion
forall a. Maybe a
Nothing,
        avx :: Bool
avx = Bool
False,
        avx2 :: Bool
avx2 = Bool
False,
        avx512cd :: Bool
avx512cd = Bool
False,
        avx512er :: Bool
avx512er = Bool
False,
        avx512f :: Bool
avx512f = Bool
False,
        avx512pf :: Bool
avx512pf = Bool
False,
        rtldInfo :: IORef (Maybe LinkerInfo)
rtldInfo = String -> IORef (Maybe LinkerInfo)
forall a. String -> a
panic String
"defaultDynFlags: no rtldInfo",
        rtccInfo :: IORef (Maybe CompilerInfo)
rtccInfo = String -> IORef (Maybe CompilerInfo)
forall a. String -> a
panic String
"defaultDynFlags: no rtccInfo",

        maxInlineAllocSize :: Int
maxInlineAllocSize = Int
128,
        maxInlineMemcpyInsns :: Int
maxInlineMemcpyInsns = Int
32,
        maxInlineMemsetInsns :: Int
maxInlineMemsetInsns = Int
32,

        initialUnique :: Int
initialUnique = Int
0,
        uniqueIncrement :: Int
uniqueIncrement = Int
1,

        reverseErrors :: Bool
reverseErrors = Bool
False,
        maxErrors :: Maybe Int
maxErrors     = Maybe Int
forall a. Maybe a
Nothing,
        cfgWeightInfo :: CfgWeights
cfgWeightInfo = CfgWeights
defaultCfgWeights
      }

defaultWays :: Settings -> [Way]
defaultWays :: Settings -> [Way]
defaultWays Settings
settings = if PlatformConstants -> Bool
pc_DYNAMIC_BY_DEFAULT (Settings -> PlatformConstants
sPlatformConstants Settings
settings)
                       then [Way
WayDyn]
                       else []

interpWays :: [Way]
interpWays :: [Way]
interpWays
  | Bool
dynamicGhc = [Way
WayDyn]
  | Bool
rtsIsProfiled = [Way
WayProf]
  | Bool
otherwise = []

interpreterProfiled :: DynFlags -> Bool
interpreterProfiled :: DynFlags -> Bool
interpreterProfiled DynFlags
dflags
  | GeneralFlag -> DynFlags -> Bool
gopt GeneralFlag
Opt_ExternalInterpreter DynFlags
dflags = GeneralFlag -> DynFlags -> Bool
gopt GeneralFlag
Opt_SccProfilingOn DynFlags
dflags
  | Bool
otherwise = Bool
rtsIsProfiled

interpreterDynamic :: DynFlags -> Bool
interpreterDynamic :: DynFlags -> Bool
interpreterDynamic DynFlags
dflags
  | GeneralFlag -> DynFlags -> Bool
gopt GeneralFlag
Opt_ExternalInterpreter DynFlags
dflags = Way
WayDyn Way -> [Way] -> Bool
forall (t :: * -> *) a. (Foldable t, Eq a) => a -> t a -> Bool
`elem` DynFlags -> [Way]
ways DynFlags
dflags
  | Bool
otherwise = Bool
dynamicGhc

--------------------------------------------------------------------------
--
-- Note [JSON Error Messages]
--
-- When the user requests the compiler output to be dumped as json
-- we used to collect them all in an IORef and then print them at the end.
-- This doesn't work very well with GHCi. (See #14078) So instead we now
-- use the simpler method of just outputting a JSON document inplace to
-- stdout.
--
-- Before the compiler calls log_action, it has already turned the `ErrMsg`
-- into a formatted message. This means that we lose some possible
-- information to provide to the user but refactoring log_action is quite
-- invasive as it is called in many places. So, for now I left it alone
-- and we can refine its behaviour as users request different output.

type FatalMessager = String -> IO ()

type LogAction = DynFlags
              -> WarnReason
              -> Severity
              -> SrcSpan
              -> PprStyle
              -> MsgDoc
              -> IO ()

defaultFatalMessager :: FatalMessager
defaultFatalMessager :: FatalMessager
defaultFatalMessager = Handle -> FatalMessager
hPutStrLn Handle
stderr


-- See Note [JSON Error Messages]
--
jsonLogAction :: LogAction
jsonLogAction :: LogAction
jsonLogAction DynFlags
dflags WarnReason
reason Severity
severity SrcSpan
srcSpan PprStyle
_style SDoc
msg
  = do
    DynFlags -> Handle -> SDoc -> PprStyle -> IO ()
defaultLogActionHPutStrDoc DynFlags
dflags Handle
stdout (SDoc
doc SDoc -> SDoc -> SDoc
$$ String -> SDoc
text String
"")
                               (CodeStyle -> PprStyle
mkCodeStyle CodeStyle
CStyle)
    where
      doc :: SDoc
doc = JsonDoc -> SDoc
renderJSON (JsonDoc -> SDoc) -> JsonDoc -> SDoc
forall a b. (a -> b) -> a -> b
$
              [(String, JsonDoc)] -> JsonDoc
JSObject [ ( String
"span", SrcSpan -> JsonDoc
forall a. ToJson a => a -> JsonDoc
json SrcSpan
srcSpan )
                       , ( String
"doc" , String -> JsonDoc
JSString (DynFlags -> SDoc -> String
showSDoc DynFlags
dflags SDoc
msg) )
                       , ( String
"severity", Severity -> JsonDoc
forall a. ToJson a => a -> JsonDoc
json Severity
severity )
                       , ( String
"reason" ,   WarnReason -> JsonDoc
forall a. ToJson a => a -> JsonDoc
json WarnReason
reason )
                       ]


defaultLogAction :: LogAction
defaultLogAction :: LogAction
defaultLogAction DynFlags
dflags WarnReason
reason Severity
severity SrcSpan
srcSpan PprStyle
style SDoc
msg
    = case Severity
severity of
      Severity
SevOutput      -> SDoc -> PprStyle -> IO ()
printOut SDoc
msg PprStyle
style
      Severity
SevDump        -> SDoc -> PprStyle -> IO ()
printOut (SDoc
msg SDoc -> SDoc -> SDoc
$$ SDoc
blankLine) PprStyle
style
      Severity
SevInteractive -> SDoc -> PprStyle -> IO ()
putStrSDoc SDoc
msg PprStyle
style
      Severity
SevInfo        -> SDoc -> PprStyle -> IO ()
printErrs SDoc
msg PprStyle
style
      Severity
SevFatal       -> SDoc -> PprStyle -> IO ()
printErrs SDoc
msg PprStyle
style
      Severity
SevWarning     -> IO ()
printWarns
      Severity
SevError       -> IO ()
printWarns
    where
      printOut :: SDoc -> PprStyle -> IO ()
printOut   = DynFlags -> Handle -> SDoc -> PprStyle -> IO ()
defaultLogActionHPrintDoc  DynFlags
dflags Handle
stdout
      printErrs :: SDoc -> PprStyle -> IO ()
printErrs  = DynFlags -> Handle -> SDoc -> PprStyle -> IO ()
defaultLogActionHPrintDoc  DynFlags
dflags Handle
stderr
      putStrSDoc :: SDoc -> PprStyle -> IO ()
putStrSDoc = DynFlags -> Handle -> SDoc -> PprStyle -> IO ()
defaultLogActionHPutStrDoc DynFlags
dflags Handle
stdout
      -- Pretty print the warning flag, if any (#10752)
      message :: SDoc
message = Maybe String -> Severity -> SrcSpan -> SDoc -> SDoc
mkLocMessageAnn Maybe String
flagMsg Severity
severity SrcSpan
srcSpan SDoc
msg

      printWarns :: IO ()
printWarns = do
        Handle -> Char -> IO ()
hPutChar Handle
stderr Char
'\n'
        SDoc
caretDiagnostic <-
            if GeneralFlag -> DynFlags -> Bool
gopt GeneralFlag
Opt_DiagnosticsShowCaret DynFlags
dflags
            then Severity -> SrcSpan -> IO SDoc
getCaretDiagnostic Severity
severity SrcSpan
srcSpan
            else SDoc -> IO SDoc
forall (f :: * -> *) a. Applicative f => a -> f a
pure SDoc
empty
        SDoc -> PprStyle -> IO ()
printErrs (SDoc
message SDoc -> SDoc -> SDoc
$+$ SDoc
caretDiagnostic)
            (Bool -> PprStyle -> PprStyle
setStyleColoured Bool
True PprStyle
style)
        -- careful (#2302): printErrs prints in UTF-8,
        -- whereas converting to string first and using
        -- hPutStr would just emit the low 8 bits of
        -- each unicode char.

      flagMsg :: Maybe String
flagMsg =
        case WarnReason
reason of
          WarnReason
NoReason -> Maybe String
forall a. Maybe a
Nothing
          Reason WarningFlag
wflag -> do
            FlagSpec WarningFlag
spec <- WarningFlag -> Maybe (FlagSpec WarningFlag)
flagSpecOf WarningFlag
wflag
            String -> Maybe String
forall (m :: * -> *) a. Monad m => a -> m a
return (String
"-W" String -> ShowS
forall a. [a] -> [a] -> [a]
++ FlagSpec WarningFlag -> String
forall flag. FlagSpec flag -> String
flagSpecName FlagSpec WarningFlag
spec String -> ShowS
forall a. [a] -> [a] -> [a]
++ WarningFlag -> String
warnFlagGrp WarningFlag
wflag)
          ErrReason Maybe WarningFlag
Nothing ->
            String -> Maybe String
forall (m :: * -> *) a. Monad m => a -> m a
return String
"-Werror"
          ErrReason (Just WarningFlag
wflag) -> do
            FlagSpec WarningFlag
spec <- WarningFlag -> Maybe (FlagSpec WarningFlag)
flagSpecOf WarningFlag
wflag
            String -> Maybe String
forall (m :: * -> *) a. Monad m => a -> m a
return (String -> Maybe String) -> String -> Maybe String
forall a b. (a -> b) -> a -> b
$
              String
"-W" String -> ShowS
forall a. [a] -> [a] -> [a]
++ FlagSpec WarningFlag -> String
forall flag. FlagSpec flag -> String
flagSpecName FlagSpec WarningFlag
spec String -> ShowS
forall a. [a] -> [a] -> [a]
++ WarningFlag -> String
warnFlagGrp WarningFlag
wflag String -> ShowS
forall a. [a] -> [a] -> [a]
++
              String
", -Werror=" String -> ShowS
forall a. [a] -> [a] -> [a]
++ FlagSpec WarningFlag -> String
forall flag. FlagSpec flag -> String
flagSpecName FlagSpec WarningFlag
spec

      warnFlagGrp :: WarningFlag -> String
warnFlagGrp WarningFlag
flag
          | GeneralFlag -> DynFlags -> Bool
gopt GeneralFlag
Opt_ShowWarnGroups DynFlags
dflags =
                case WarningFlag -> [String]
smallestGroups WarningFlag
flag of
                    [] -> String
""
                    [String]
groups -> String
" (in " String -> ShowS
forall a. [a] -> [a] -> [a]
++ String -> [String] -> String
forall a. [a] -> [[a]] -> [a]
intercalate String
", " (ShowS -> [String] -> [String]
forall a b. (a -> b) -> [a] -> [b]
map (String
"-W"String -> ShowS
forall a. [a] -> [a] -> [a]
++) [String]
groups) String -> ShowS
forall a. [a] -> [a] -> [a]
++ String
")"
          | Bool
otherwise = String
""

-- | Like 'defaultLogActionHPutStrDoc' but appends an extra newline.
defaultLogActionHPrintDoc :: DynFlags -> Handle -> SDoc -> PprStyle -> IO ()
defaultLogActionHPrintDoc :: DynFlags -> Handle -> SDoc -> PprStyle -> IO ()
defaultLogActionHPrintDoc DynFlags
dflags Handle
h SDoc
d PprStyle
sty
 = DynFlags -> Handle -> SDoc -> PprStyle -> IO ()
defaultLogActionHPutStrDoc DynFlags
dflags Handle
h (SDoc
d SDoc -> SDoc -> SDoc
$$ String -> SDoc
text String
"") PprStyle
sty

defaultLogActionHPutStrDoc :: DynFlags -> Handle -> SDoc -> PprStyle -> IO ()
defaultLogActionHPutStrDoc :: DynFlags -> Handle -> SDoc -> PprStyle -> IO ()
defaultLogActionHPutStrDoc DynFlags
dflags Handle
h SDoc
d PprStyle
sty
  -- Don't add a newline at the end, so that successive
  -- calls to this log-action can output all on the same line
  = Mode -> DynFlags -> Handle -> PprStyle -> SDoc -> IO ()
printSDoc Mode
Pretty.PageMode DynFlags
dflags Handle
h PprStyle
sty SDoc
d

newtype FlushOut = FlushOut (IO ())

defaultFlushOut :: FlushOut
defaultFlushOut :: FlushOut
defaultFlushOut = IO () -> FlushOut
FlushOut (IO () -> FlushOut) -> IO () -> FlushOut
forall a b. (a -> b) -> a -> b
$ Handle -> IO ()
hFlush Handle
stdout

newtype FlushErr = FlushErr (IO ())

defaultFlushErr :: FlushErr
defaultFlushErr :: FlushErr
defaultFlushErr = IO () -> FlushErr
FlushErr (IO () -> FlushErr) -> IO () -> FlushErr
forall a b. (a -> b) -> a -> b
$ Handle -> IO ()
hFlush Handle
stderr

{-
Note [Verbosity levels]
~~~~~~~~~~~~~~~~~~~~~~~
    0   |   print errors & warnings only
    1   |   minimal verbosity: print "compiling M ... done." for each module.
    2   |   equivalent to -dshow-passes
    3   |   equivalent to existing "ghc -v"
    4   |   "ghc -v -ddump-most"
    5   |   "ghc -v -ddump-all"
-}

data OnOff a = On a
             | Off a
  deriving (OnOff a -> OnOff a -> Bool
(OnOff a -> OnOff a -> Bool)
-> (OnOff a -> OnOff a -> Bool) -> Eq (OnOff a)
forall a. Eq a => OnOff a -> OnOff a -> Bool
forall a. (a -> a -> Bool) -> (a -> a -> Bool) -> Eq a
/= :: OnOff a -> OnOff a -> Bool
$c/= :: forall a. Eq a => OnOff a -> OnOff a -> Bool
== :: OnOff a -> OnOff a -> Bool
$c== :: forall a. Eq a => OnOff a -> OnOff a -> Bool
Eq, Int -> OnOff a -> ShowS
[OnOff a] -> ShowS
OnOff a -> String
(Int -> OnOff a -> ShowS)
-> (OnOff a -> String) -> ([OnOff a] -> ShowS) -> Show (OnOff a)
forall a. Show a => Int -> OnOff a -> ShowS
forall a. Show a => [OnOff a] -> ShowS
forall a. Show a => OnOff a -> String
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
showList :: [OnOff a] -> ShowS
$cshowList :: forall a. Show a => [OnOff a] -> ShowS
show :: OnOff a -> String
$cshow :: forall a. Show a => OnOff a -> String
showsPrec :: Int -> OnOff a -> ShowS
$cshowsPrec :: forall a. Show a => Int -> OnOff a -> ShowS
Show)

instance Outputable a => Outputable (OnOff a) where
  ppr :: OnOff a -> SDoc
ppr (On a
x)  = String -> SDoc
text String
"On" SDoc -> SDoc -> SDoc
<+> a -> SDoc
forall a. Outputable a => a -> SDoc
ppr a
x
  ppr (Off a
x) = String -> SDoc
text String
"Off" SDoc -> SDoc -> SDoc
<+> a -> SDoc
forall a. Outputable a => a -> SDoc
ppr a
x

-- OnOffs accumulate in reverse order, so we use foldr in order to
-- process them in the right order
flattenExtensionFlags :: Maybe Language -> [OnOff LangExt.Extension] -> EnumSet LangExt.Extension
flattenExtensionFlags :: Maybe Language -> [OnOff Extension] -> EnumSet Extension
flattenExtensionFlags Maybe Language
ml = (OnOff Extension -> EnumSet Extension -> EnumSet Extension)
-> EnumSet Extension -> [OnOff Extension] -> EnumSet Extension
forall (t :: * -> *) a b.
Foldable t =>
(a -> b -> b) -> b -> t a -> b
foldr OnOff Extension -> EnumSet Extension -> EnumSet Extension
forall a. Enum a => OnOff a -> EnumSet a -> EnumSet a
f EnumSet Extension
defaultExtensionFlags
    where f :: OnOff a -> EnumSet a -> EnumSet a
f (On a
f)  EnumSet a
flags = a -> EnumSet a -> EnumSet a
forall a. Enum a => a -> EnumSet a -> EnumSet a
EnumSet.insert a
f EnumSet a
flags
          f (Off a
f) EnumSet a
flags = a -> EnumSet a -> EnumSet a
forall a. Enum a => a -> EnumSet a -> EnumSet a
EnumSet.delete a
f EnumSet a
flags
          defaultExtensionFlags :: EnumSet Extension
defaultExtensionFlags = [Extension] -> EnumSet Extension
forall a. Enum a => [a] -> EnumSet a
EnumSet.fromList (Maybe Language -> [Extension]
languageExtensions Maybe Language
ml)

-- | The language extensions implied by the various language variants.
-- When updating this be sure to update the flag documentation in
-- @docs/users-guide/glasgow_exts.rst@.
languageExtensions :: Maybe Language -> [LangExt.Extension]

languageExtensions :: Maybe Language -> [Extension]
languageExtensions Maybe Language
Nothing
    -- Nothing => the default case
    = Extension
LangExt.NondecreasingIndentation -- This has been on by default for some time
    Extension -> [Extension] -> [Extension]
forall a. a -> [a] -> [a]
: Extension -> [Extension] -> [Extension]
forall a. Eq a => a -> [a] -> [a]
delete Extension
LangExt.DatatypeContexts  -- The Haskell' committee decided to
                                       -- remove datatype contexts from the
                                       -- language:
   -- http://www.haskell.org/pipermail/haskell-prime/2011-January/003335.html
      (Maybe Language -> [Extension]
languageExtensions (Language -> Maybe Language
forall a. a -> Maybe a
Just Language
Haskell2010))

   -- NB: MonoPatBinds is no longer the default

languageExtensions (Just Language
Haskell98)
    = [Extension
LangExt.ImplicitPrelude,
       -- See Note [When is StarIsType enabled]
       Extension
LangExt.StarIsType,
       Extension
LangExt.CUSKs,
       Extension
LangExt.MonomorphismRestriction,
       Extension
LangExt.NPlusKPatterns,
       Extension
LangExt.DatatypeContexts,
       Extension
LangExt.TraditionalRecordSyntax,
       Extension
LangExt.NondecreasingIndentation
           -- strictly speaking non-standard, but we always had this
           -- on implicitly before the option was added in 7.1, and
           -- turning it off breaks code, so we're keeping it on for
           -- backwards compatibility.  Cabal uses -XHaskell98 by
           -- default unless you specify another language.
      ]

languageExtensions (Just Language
Haskell2010)
    = [Extension
LangExt.ImplicitPrelude,
       -- See Note [When is StarIsType enabled]
       Extension
LangExt.StarIsType,
       Extension
LangExt.CUSKs,
       Extension
LangExt.MonomorphismRestriction,
       Extension
LangExt.DatatypeContexts,
       Extension
LangExt.TraditionalRecordSyntax,
       Extension
LangExt.EmptyDataDecls,
       Extension
LangExt.ForeignFunctionInterface,
       Extension
LangExt.PatternGuards,
       Extension
LangExt.DoAndIfThenElse,
       Extension
LangExt.RelaxedPolyRec]

hasPprDebug :: DynFlags -> Bool
hasPprDebug :: DynFlags -> Bool
hasPprDebug = DumpFlag -> DynFlags -> Bool
dopt DumpFlag
Opt_D_ppr_debug

hasNoDebugOutput :: DynFlags -> Bool
hasNoDebugOutput :: DynFlags -> Bool
hasNoDebugOutput = DumpFlag -> DynFlags -> Bool
dopt DumpFlag
Opt_D_no_debug_output

hasNoStateHack :: DynFlags -> Bool
hasNoStateHack :: DynFlags -> Bool
hasNoStateHack = GeneralFlag -> DynFlags -> Bool
gopt GeneralFlag
Opt_G_NoStateHack

hasNoOptCoercion :: DynFlags -> Bool
hasNoOptCoercion :: DynFlags -> Bool
hasNoOptCoercion = GeneralFlag -> DynFlags -> Bool
gopt GeneralFlag
Opt_G_NoOptCoercion


-- | Test whether a 'DumpFlag' is set
dopt :: DumpFlag -> DynFlags -> Bool
dopt :: DumpFlag -> DynFlags -> Bool
dopt DumpFlag
f DynFlags
dflags = (DumpFlag
f DumpFlag -> EnumSet DumpFlag -> Bool
forall a. Enum a => a -> EnumSet a -> Bool
`EnumSet.member` DynFlags -> EnumSet DumpFlag
dumpFlags DynFlags
dflags)
             Bool -> Bool -> Bool
|| (DynFlags -> Int
verbosity DynFlags
dflags Int -> Int -> Bool
forall a. Ord a => a -> a -> Bool
>= Int
4 Bool -> Bool -> Bool
&& DumpFlag -> Bool
enableIfVerbose DumpFlag
f)
    where enableIfVerbose :: DumpFlag -> Bool
enableIfVerbose DumpFlag
Opt_D_dump_tc_trace               = Bool
False
          enableIfVerbose DumpFlag
Opt_D_dump_rn_trace               = Bool
False
          enableIfVerbose DumpFlag
Opt_D_dump_cs_trace               = Bool
False
          enableIfVerbose DumpFlag
Opt_D_dump_if_trace               = Bool
False
          enableIfVerbose DumpFlag
Opt_D_dump_vt_trace               = Bool
False
          enableIfVerbose DumpFlag
Opt_D_dump_tc                     = Bool
False
          enableIfVerbose DumpFlag
Opt_D_dump_rn                     = Bool
False
          enableIfVerbose DumpFlag
Opt_D_dump_rn_stats               = Bool
False
          enableIfVerbose DumpFlag
Opt_D_dump_hi_diffs               = Bool
False
          enableIfVerbose DumpFlag
Opt_D_verbose_core2core           = Bool
False
          enableIfVerbose DumpFlag
Opt_D_verbose_stg2stg             = Bool
False
          enableIfVerbose DumpFlag
Opt_D_dump_splices                = Bool
False
          enableIfVerbose DumpFlag
Opt_D_th_dec_file                 = Bool
False
          enableIfVerbose DumpFlag
Opt_D_dump_rule_firings           = Bool
False
          enableIfVerbose DumpFlag
Opt_D_dump_rule_rewrites          = Bool
False
          enableIfVerbose DumpFlag
Opt_D_dump_simpl_trace            = Bool
False
          enableIfVerbose DumpFlag
Opt_D_dump_rtti                   = Bool
False
          enableIfVerbose DumpFlag
Opt_D_dump_inlinings              = Bool
False
          enableIfVerbose DumpFlag
Opt_D_dump_core_stats             = Bool
False
          enableIfVerbose DumpFlag
Opt_D_dump_asm_stats              = Bool
False
          enableIfVerbose DumpFlag
Opt_D_dump_types                  = Bool
False
          enableIfVerbose DumpFlag
Opt_D_dump_simpl_iterations       = Bool
False
          enableIfVerbose DumpFlag
Opt_D_dump_ticked                 = Bool
False
          enableIfVerbose DumpFlag
Opt_D_dump_view_pattern_commoning = Bool
False
          enableIfVerbose DumpFlag
Opt_D_dump_mod_cycles             = Bool
False
          enableIfVerbose DumpFlag
Opt_D_dump_mod_map                = Bool
False
          enableIfVerbose DumpFlag
Opt_D_dump_ec_trace               = Bool
False
          enableIfVerbose DumpFlag
_                                 = Bool
True

-- | Set a 'DumpFlag'
dopt_set :: DynFlags -> DumpFlag -> DynFlags
dopt_set :: DynFlags -> DumpFlag -> DynFlags
dopt_set DynFlags
dfs DumpFlag
f = DynFlags
dfs{ dumpFlags :: EnumSet DumpFlag
dumpFlags = DumpFlag -> EnumSet DumpFlag -> EnumSet DumpFlag
forall a. Enum a => a -> EnumSet a -> EnumSet a
EnumSet.insert DumpFlag
f (DynFlags -> EnumSet DumpFlag
dumpFlags DynFlags
dfs) }

-- | Unset a 'DumpFlag'
dopt_unset :: DynFlags -> DumpFlag -> DynFlags
dopt_unset :: DynFlags -> DumpFlag -> DynFlags
dopt_unset DynFlags
dfs DumpFlag
f = DynFlags
dfs{ dumpFlags :: EnumSet DumpFlag
dumpFlags = DumpFlag -> EnumSet DumpFlag -> EnumSet DumpFlag
forall a. Enum a => a -> EnumSet a -> EnumSet a
EnumSet.delete DumpFlag
f (DynFlags -> EnumSet DumpFlag
dumpFlags DynFlags
dfs) }

-- | Test whether a 'GeneralFlag' is set
gopt :: GeneralFlag -> DynFlags -> Bool
gopt :: GeneralFlag -> DynFlags -> Bool
gopt GeneralFlag
f DynFlags
dflags  = GeneralFlag
f GeneralFlag -> EnumSet GeneralFlag -> Bool
forall a. Enum a => a -> EnumSet a -> Bool
`EnumSet.member` DynFlags -> EnumSet GeneralFlag
generalFlags DynFlags
dflags

-- | Set a 'GeneralFlag'
gopt_set :: DynFlags -> GeneralFlag -> DynFlags
gopt_set :: DynFlags -> GeneralFlag -> DynFlags
gopt_set DynFlags
dfs GeneralFlag
f = DynFlags
dfs{ generalFlags :: EnumSet GeneralFlag
generalFlags = GeneralFlag -> EnumSet GeneralFlag -> EnumSet GeneralFlag
forall a. Enum a => a -> EnumSet a -> EnumSet a
EnumSet.insert GeneralFlag
f (DynFlags -> EnumSet GeneralFlag
generalFlags DynFlags
dfs) }

-- | Unset a 'GeneralFlag'
gopt_unset :: DynFlags -> GeneralFlag -> DynFlags
gopt_unset :: DynFlags -> GeneralFlag -> DynFlags
gopt_unset DynFlags
dfs GeneralFlag
f = DynFlags
dfs{ generalFlags :: EnumSet GeneralFlag
generalFlags = GeneralFlag -> EnumSet GeneralFlag -> EnumSet GeneralFlag
forall a. Enum a => a -> EnumSet a -> EnumSet a
EnumSet.delete GeneralFlag
f (DynFlags -> EnumSet GeneralFlag
generalFlags DynFlags
dfs) }

-- | Test whether a 'WarningFlag' is set
wopt :: WarningFlag -> DynFlags -> Bool
wopt :: WarningFlag -> DynFlags -> Bool
wopt WarningFlag
f DynFlags
dflags  = WarningFlag
f WarningFlag -> EnumSet WarningFlag -> Bool
forall a. Enum a => a -> EnumSet a -> Bool
`EnumSet.member` DynFlags -> EnumSet WarningFlag
warningFlags DynFlags
dflags

-- | Set a 'WarningFlag'
wopt_set :: DynFlags -> WarningFlag -> DynFlags
wopt_set :: DynFlags -> WarningFlag -> DynFlags
wopt_set DynFlags
dfs WarningFlag
f = DynFlags
dfs{ warningFlags :: EnumSet WarningFlag
warningFlags = WarningFlag -> EnumSet WarningFlag -> EnumSet WarningFlag
forall a. Enum a => a -> EnumSet a -> EnumSet a
EnumSet.insert WarningFlag
f (DynFlags -> EnumSet WarningFlag
warningFlags DynFlags
dfs) }

-- | Unset a 'WarningFlag'
wopt_unset :: DynFlags -> WarningFlag -> DynFlags
wopt_unset :: DynFlags -> WarningFlag -> DynFlags
wopt_unset DynFlags
dfs WarningFlag
f = DynFlags
dfs{ warningFlags :: EnumSet WarningFlag
warningFlags = WarningFlag -> EnumSet WarningFlag -> EnumSet WarningFlag
forall a. Enum a => a -> EnumSet a -> EnumSet a
EnumSet.delete WarningFlag
f (DynFlags -> EnumSet WarningFlag
warningFlags DynFlags
dfs) }

-- | Test whether a 'WarningFlag' is set as fatal
wopt_fatal :: WarningFlag -> DynFlags -> Bool
wopt_fatal :: WarningFlag -> DynFlags -> Bool
wopt_fatal WarningFlag
f DynFlags
dflags = WarningFlag
f WarningFlag -> EnumSet WarningFlag -> Bool
forall a. Enum a => a -> EnumSet a -> Bool
`EnumSet.member` DynFlags -> EnumSet WarningFlag
fatalWarningFlags DynFlags
dflags

-- | Mark a 'WarningFlag' as fatal (do not set the flag)
wopt_set_fatal :: DynFlags -> WarningFlag -> DynFlags
wopt_set_fatal :: DynFlags -> WarningFlag -> DynFlags
wopt_set_fatal DynFlags
dfs WarningFlag
f
    = DynFlags
dfs { fatalWarningFlags :: EnumSet WarningFlag
fatalWarningFlags = WarningFlag -> EnumSet WarningFlag -> EnumSet WarningFlag
forall a. Enum a => a -> EnumSet a -> EnumSet a
EnumSet.insert WarningFlag
f (DynFlags -> EnumSet WarningFlag
fatalWarningFlags DynFlags
dfs) }

-- | Mark a 'WarningFlag' as not fatal
wopt_unset_fatal :: DynFlags -> WarningFlag -> DynFlags
wopt_unset_fatal :: DynFlags -> WarningFlag -> DynFlags
wopt_unset_fatal DynFlags
dfs WarningFlag
f
    = DynFlags
dfs { fatalWarningFlags :: EnumSet WarningFlag
fatalWarningFlags = WarningFlag -> EnumSet WarningFlag -> EnumSet WarningFlag
forall a. Enum a => a -> EnumSet a -> EnumSet a
EnumSet.delete WarningFlag
f (DynFlags -> EnumSet WarningFlag
fatalWarningFlags DynFlags
dfs) }

-- | Test whether a 'LangExt.Extension' is set
xopt :: LangExt.Extension -> DynFlags -> Bool
xopt :: Extension -> DynFlags -> Bool
xopt Extension
f DynFlags
dflags = Extension
f Extension -> EnumSet Extension -> Bool
forall a. Enum a => a -> EnumSet a -> Bool
`EnumSet.member` DynFlags -> EnumSet Extension
extensionFlags DynFlags
dflags

-- | Set a 'LangExt.Extension'
xopt_set :: DynFlags -> LangExt.Extension -> DynFlags
xopt_set :: DynFlags -> Extension -> DynFlags
xopt_set DynFlags
dfs Extension
f
    = let onoffs :: [OnOff Extension]
onoffs = Extension -> OnOff Extension
forall a. a -> OnOff a
On Extension
f OnOff Extension -> [OnOff Extension] -> [OnOff Extension]
forall a. a -> [a] -> [a]
: DynFlags -> [OnOff Extension]
extensions DynFlags
dfs
      in DynFlags
dfs { extensions :: [OnOff Extension]
extensions = [OnOff Extension]
onoffs,
               extensionFlags :: EnumSet Extension
extensionFlags = Maybe Language -> [OnOff Extension] -> EnumSet Extension
flattenExtensionFlags (DynFlags -> Maybe Language
language DynFlags
dfs) [OnOff Extension]
onoffs }

-- | Unset a 'LangExt.Extension'
xopt_unset :: DynFlags -> LangExt.Extension -> DynFlags
xopt_unset :: DynFlags -> Extension -> DynFlags
xopt_unset DynFlags
dfs Extension
f
    = let onoffs :: [OnOff Extension]
onoffs = Extension -> OnOff Extension
forall a. a -> OnOff a
Off Extension
f OnOff Extension -> [OnOff Extension] -> [OnOff Extension]
forall a. a -> [a] -> [a]
: DynFlags -> [OnOff Extension]
extensions DynFlags
dfs
      in DynFlags
dfs { extensions :: [OnOff Extension]
extensions = [OnOff Extension]
onoffs,
               extensionFlags :: EnumSet Extension
extensionFlags = Maybe Language -> [OnOff Extension] -> EnumSet Extension
flattenExtensionFlags (DynFlags -> Maybe Language
language DynFlags
dfs) [OnOff Extension]
onoffs }

-- | Set or unset a 'LangExt.Extension', unless it has been explicitly
--   set or unset before.
xopt_set_unlessExplSpec
        :: LangExt.Extension
        -> (DynFlags -> LangExt.Extension -> DynFlags)
        -> DynFlags -> DynFlags
xopt_set_unlessExplSpec :: Extension
-> (DynFlags -> Extension -> DynFlags) -> DynFlags -> DynFlags
xopt_set_unlessExplSpec Extension
ext DynFlags -> Extension -> DynFlags
setUnset DynFlags
dflags =
    let referedExts :: [Extension]
referedExts = OnOff Extension -> Extension
forall p. OnOff p -> p
stripOnOff (OnOff Extension -> Extension) -> [OnOff Extension] -> [Extension]
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> DynFlags -> [OnOff Extension]
extensions DynFlags
dflags
        stripOnOff :: OnOff p -> p
stripOnOff (On p
x)  = p
x
        stripOnOff (Off p
x) = p
x
    in
        if Extension
ext Extension -> [Extension] -> Bool
forall (t :: * -> *) a. (Foldable t, Eq a) => a -> t a -> Bool
`elem` [Extension]
referedExts then DynFlags
dflags else DynFlags -> Extension -> DynFlags
setUnset DynFlags
dflags Extension
ext

lang_set :: DynFlags -> Maybe Language -> DynFlags
lang_set :: DynFlags -> Maybe Language -> DynFlags
lang_set DynFlags
dflags Maybe Language
lang =
   DynFlags
dflags {
            language :: Maybe Language
language = Maybe Language
lang,
            extensionFlags :: EnumSet Extension
extensionFlags = Maybe Language -> [OnOff Extension] -> EnumSet Extension
flattenExtensionFlags Maybe Language
lang (DynFlags -> [OnOff Extension]
extensions DynFlags
dflags)
          }

-- | An internal helper to check whether to use unicode syntax for output.
--
-- Note: You should very likely be using 'Outputable.unicodeSyntax' instead
-- of this function.
useUnicodeSyntax :: DynFlags -> Bool
useUnicodeSyntax :: DynFlags -> Bool
useUnicodeSyntax = GeneralFlag -> DynFlags -> Bool
gopt GeneralFlag
Opt_PrintUnicodeSyntax

useStarIsType :: DynFlags -> Bool
useStarIsType :: DynFlags -> Bool
useStarIsType = Extension -> DynFlags -> Bool
xopt Extension
LangExt.StarIsType

-- | Set the Haskell language standard to use
setLanguage :: Language -> DynP ()
setLanguage :: Language -> DynP ()
setLanguage Language
l = (DynFlags -> DynFlags) -> DynP ()
upd (DynFlags -> Maybe Language -> DynFlags
`lang_set` Language -> Maybe Language
forall a. a -> Maybe a
Just Language
l)

-- | Some modules have dependencies on others through the DynFlags rather than textual imports
dynFlagDependencies :: DynFlags -> [ModuleName]
dynFlagDependencies :: DynFlags -> [ModuleName]
dynFlagDependencies = DynFlags -> [ModuleName]
pluginModNames

-- | Is the -fpackage-trust mode on
packageTrustOn :: DynFlags -> Bool
packageTrustOn :: DynFlags -> Bool
packageTrustOn = GeneralFlag -> DynFlags -> Bool
gopt GeneralFlag
Opt_PackageTrust

-- | Is Safe Haskell on in some way (including inference mode)
safeHaskellOn :: DynFlags -> Bool
safeHaskellOn :: DynFlags -> Bool
safeHaskellOn DynFlags
dflags = DynFlags -> Bool
safeHaskellModeEnabled DynFlags
dflags Bool -> Bool -> Bool
|| DynFlags -> Bool
safeInferOn DynFlags
dflags

safeHaskellModeEnabled :: DynFlags -> Bool
safeHaskellModeEnabled :: DynFlags -> Bool
safeHaskellModeEnabled DynFlags
dflags = DynFlags -> SafeHaskellMode
safeHaskell DynFlags
dflags SafeHaskellMode -> [SafeHaskellMode] -> Bool
forall (t :: * -> *) a. (Foldable t, Eq a) => a -> t a -> Bool
`elem` [SafeHaskellMode
Sf_Unsafe, SafeHaskellMode
Sf_Trustworthy
                                                   , SafeHaskellMode
Sf_Safe ]


-- | Is the Safe Haskell safe language in use
safeLanguageOn :: DynFlags -> Bool
safeLanguageOn :: DynFlags -> Bool
safeLanguageOn DynFlags
dflags = DynFlags -> SafeHaskellMode
safeHaskell DynFlags
dflags SafeHaskellMode -> SafeHaskellMode -> Bool
forall a. Eq a => a -> a -> Bool
== SafeHaskellMode
Sf_Safe

-- | Is the Safe Haskell safe inference mode active
safeInferOn :: DynFlags -> Bool
safeInferOn :: DynFlags -> Bool
safeInferOn = DynFlags -> Bool
safeInfer

-- | Test if Safe Imports are on in some form
safeImportsOn :: DynFlags -> Bool
safeImportsOn :: DynFlags -> Bool
safeImportsOn DynFlags
dflags = DynFlags -> SafeHaskellMode
safeHaskell DynFlags
dflags SafeHaskellMode -> SafeHaskellMode -> Bool
forall a. Eq a => a -> a -> Bool
== SafeHaskellMode
Sf_Unsafe Bool -> Bool -> Bool
||
                       DynFlags -> SafeHaskellMode
safeHaskell DynFlags
dflags SafeHaskellMode -> SafeHaskellMode -> Bool
forall a. Eq a => a -> a -> Bool
== SafeHaskellMode
Sf_Trustworthy Bool -> Bool -> Bool
||
                       DynFlags -> SafeHaskellMode
safeHaskell DynFlags
dflags SafeHaskellMode -> SafeHaskellMode -> Bool
forall a. Eq a => a -> a -> Bool
== SafeHaskellMode
Sf_Safe

-- | Set a 'Safe Haskell' flag
setSafeHaskell :: SafeHaskellMode -> DynP ()
setSafeHaskell :: SafeHaskellMode -> DynP ()
setSafeHaskell SafeHaskellMode
s = (DynFlags -> DynP DynFlags) -> DynP ()
updM DynFlags -> DynP DynFlags
f
    where f :: DynFlags -> DynP DynFlags
f DynFlags
dfs = do
              let sf :: SafeHaskellMode
sf = DynFlags -> SafeHaskellMode
safeHaskell DynFlags
dfs
              SafeHaskellMode
safeM <- SafeHaskellMode -> SafeHaskellMode -> DynP SafeHaskellMode
combineSafeFlags SafeHaskellMode
sf SafeHaskellMode
s
              case SafeHaskellMode
s of
                SafeHaskellMode
Sf_Safe -> DynFlags -> DynP DynFlags
forall (m :: * -> *) a. Monad m => a -> m a
return (DynFlags -> DynP DynFlags) -> DynFlags -> DynP DynFlags
forall a b. (a -> b) -> a -> b
$ DynFlags
dfs { safeHaskell :: SafeHaskellMode
safeHaskell = SafeHaskellMode
safeM, safeInfer :: Bool
safeInfer = Bool
False }
                -- leave safe inferrence on in Trustworthy mode so we can warn
                -- if it could have been inferred safe.
                SafeHaskellMode
Sf_Trustworthy -> do
                  SrcSpan
l <- EwM (CmdLineP DynFlags) SrcSpan
forall (m :: * -> *). Monad m => EwM m SrcSpan
getCurLoc
                  DynFlags -> DynP DynFlags
forall (m :: * -> *) a. Monad m => a -> m a
return (DynFlags -> DynP DynFlags) -> DynFlags -> DynP DynFlags
forall a b. (a -> b) -> a -> b
$ DynFlags
dfs { safeHaskell :: SafeHaskellMode
safeHaskell = SafeHaskellMode
safeM, trustworthyOnLoc :: SrcSpan
trustworthyOnLoc = SrcSpan
l }
                -- leave safe inference on in Unsafe mode as well.
                SafeHaskellMode
_ -> DynFlags -> DynP DynFlags
forall (m :: * -> *) a. Monad m => a -> m a
return (DynFlags -> DynP DynFlags) -> DynFlags -> DynP DynFlags
forall a b. (a -> b) -> a -> b
$ DynFlags
dfs { safeHaskell :: SafeHaskellMode
safeHaskell = SafeHaskellMode
safeM }

-- | Are all direct imports required to be safe for this Safe Haskell mode?
-- Direct imports are when the code explicitly imports a module
safeDirectImpsReq :: DynFlags -> Bool
safeDirectImpsReq :: DynFlags -> Bool
safeDirectImpsReq DynFlags
d = DynFlags -> Bool
safeLanguageOn DynFlags
d

-- | Are all implicit imports required to be safe for this Safe Haskell mode?
-- Implicit imports are things in the prelude. e.g System.IO when print is used.
safeImplicitImpsReq :: DynFlags -> Bool
safeImplicitImpsReq :: DynFlags -> Bool
safeImplicitImpsReq DynFlags
d = DynFlags -> Bool
safeLanguageOn DynFlags
d

-- | Combine two Safe Haskell modes correctly. Used for dealing with multiple flags.
-- This makes Safe Haskell very much a monoid but for now I prefer this as I don't
-- want to export this functionality from the module but do want to export the
-- type constructors.
combineSafeFlags :: SafeHaskellMode -> SafeHaskellMode -> DynP SafeHaskellMode
combineSafeFlags :: SafeHaskellMode -> SafeHaskellMode -> DynP SafeHaskellMode
combineSafeFlags SafeHaskellMode
a SafeHaskellMode
b | SafeHaskellMode
a SafeHaskellMode -> SafeHaskellMode -> Bool
forall a. Eq a => a -> a -> Bool
== SafeHaskellMode
Sf_None         = SafeHaskellMode -> DynP SafeHaskellMode
forall (m :: * -> *) a. Monad m => a -> m a
return SafeHaskellMode
b
                     | SafeHaskellMode
b SafeHaskellMode -> SafeHaskellMode -> Bool
forall a. Eq a => a -> a -> Bool
== SafeHaskellMode
Sf_None         = SafeHaskellMode -> DynP SafeHaskellMode
forall (m :: * -> *) a. Monad m => a -> m a
return SafeHaskellMode
a
                     | SafeHaskellMode
a SafeHaskellMode -> SafeHaskellMode -> Bool
forall a. Eq a => a -> a -> Bool
== SafeHaskellMode
Sf_Ignore Bool -> Bool -> Bool
|| SafeHaskellMode
b SafeHaskellMode -> SafeHaskellMode -> Bool
forall a. Eq a => a -> a -> Bool
== SafeHaskellMode
Sf_Ignore = SafeHaskellMode -> DynP SafeHaskellMode
forall (m :: * -> *) a. Monad m => a -> m a
return SafeHaskellMode
Sf_Ignore
                     | SafeHaskellMode
a SafeHaskellMode -> SafeHaskellMode -> Bool
forall a. Eq a => a -> a -> Bool
== SafeHaskellMode
b               = SafeHaskellMode -> DynP SafeHaskellMode
forall (m :: * -> *) a. Monad m => a -> m a
return SafeHaskellMode
a
                     | Bool
otherwise            = String -> DynP ()
forall (m :: * -> *). Monad m => String -> EwM m ()
addErr String
errm DynP () -> DynP SafeHaskellMode -> DynP SafeHaskellMode
forall (m :: * -> *) a b. Monad m => m a -> m b -> m b
>> SafeHaskellMode -> DynP SafeHaskellMode
forall (f :: * -> *) a. Applicative f => a -> f a
pure SafeHaskellMode
a
    where errm :: String
errm = String
"Incompatible Safe Haskell flags! ("
                    String -> ShowS
forall a. [a] -> [a] -> [a]
++ SafeHaskellMode -> String
forall a. Show a => a -> String
show SafeHaskellMode
a String -> ShowS
forall a. [a] -> [a] -> [a]
++ String
", " String -> ShowS
forall a. [a] -> [a] -> [a]
++ SafeHaskellMode -> String
forall a. Show a => a -> String
show SafeHaskellMode
b String -> ShowS
forall a. [a] -> [a] -> [a]
++ String
")"

-- | A list of unsafe flags under Safe Haskell. Tuple elements are:
--     * name of the flag
--     * function to get srcspan that enabled the flag
--     * function to test if the flag is on
--     * function to turn the flag off
unsafeFlags, unsafeFlagsForInfer
  :: [(String, DynFlags -> SrcSpan, DynFlags -> Bool, DynFlags -> DynFlags)]
unsafeFlags :: [(String, DynFlags -> SrcSpan, DynFlags -> Bool,
  DynFlags -> DynFlags)]
unsafeFlags = [ (String
"-XGeneralizedNewtypeDeriving", DynFlags -> SrcSpan
newDerivOnLoc,
                    Extension -> DynFlags -> Bool
xopt Extension
LangExt.GeneralizedNewtypeDeriving,
                    (DynFlags -> Extension -> DynFlags)
-> Extension -> DynFlags -> DynFlags
forall a b c. (a -> b -> c) -> b -> a -> c
flip DynFlags -> Extension -> DynFlags
xopt_unset Extension
LangExt.GeneralizedNewtypeDeriving)
              , (String
"-XTemplateHaskell", DynFlags -> SrcSpan
thOnLoc,
                    Extension -> DynFlags -> Bool
xopt Extension
LangExt.TemplateHaskell,
                    (DynFlags -> Extension -> DynFlags)
-> Extension -> DynFlags -> DynFlags
forall a b c. (a -> b -> c) -> b -> a -> c
flip DynFlags -> Extension -> DynFlags
xopt_unset Extension
LangExt.TemplateHaskell)
              ]
unsafeFlagsForInfer :: [(String, DynFlags -> SrcSpan, DynFlags -> Bool,
  DynFlags -> DynFlags)]
unsafeFlagsForInfer = [(String, DynFlags -> SrcSpan, DynFlags -> Bool,
  DynFlags -> DynFlags)]
unsafeFlags


-- | Retrieve the options corresponding to a particular @opt_*@ field in the correct order
getOpts :: DynFlags             -- ^ 'DynFlags' to retrieve the options from
        -> (DynFlags -> [a])    -- ^ Relevant record accessor: one of the @opt_*@ accessors
        -> [a]                  -- ^ Correctly ordered extracted options
getOpts :: DynFlags -> (DynFlags -> [a]) -> [a]
getOpts DynFlags
dflags DynFlags -> [a]
opts = [a] -> [a]
forall a. [a] -> [a]
reverse (DynFlags -> [a]
opts DynFlags
dflags)
        -- We add to the options from the front, so we need to reverse the list

-- | Gets the verbosity flag for the current verbosity level. This is fed to
-- other tools, so GHC-specific verbosity flags like @-ddump-most@ are not included
getVerbFlags :: DynFlags -> [String]
getVerbFlags :: DynFlags -> [String]
getVerbFlags DynFlags
dflags
  | DynFlags -> Int
verbosity DynFlags
dflags Int -> Int -> Bool
forall a. Ord a => a -> a -> Bool
>= Int
4 = [String
"-v"]
  | Bool
otherwise             = []

setObjectDir, setHiDir, setHieDir, setStubDir, setDumpDir, setOutputDir,
         setDynObjectSuf, setDynHiSuf,
         setDylibInstallName,
         setObjectSuf,