    {-# LANGUAGE RankNTypes #-}
    {-# LANGUAGE CPP #-}

    #if defined(HAVE_INTERNAL_INTERPRETER) && defined(CAN_LOAD_DLL)
    {-# LANGUAGE MagicHash #-}
    {-# LANGUAGE LambdaCase #-}
    {-# LANGUAGE UnboxedTuples #-}
    #endif

    -- | Definitions for writing /plugins/ for GHC. Plugins can hook into
    -- several areas of the compiler. See the 'Plugin' type. These plugins
    -- include type-checker plugins, source plugins, and core-to-core plugins.

    module GHC.Driver.Plugins (
          -- * Plugins
          Plugins (..)
        , emptyPlugins
        , Plugin(..)
        , defaultPlugin
        , CommandLineOption
        , PsMessages(..)
        , ParsedResult(..)

          -- * External plugins
        , loadExternalPlugins

          -- ** Recompilation checking
        , purePlugin, impurePlugin, flagRecompile
        , PluginRecompile(..)

          -- * Plugin types
          -- ** Frontend plugins
        , FrontendPlugin(..), defaultFrontendPlugin, FrontendPluginAction
          -- ** Core plugins
          -- | Core plugins allow plugins to register as a Core-to-Core pass.
        , CorePlugin
          -- ** Typechecker plugins
          -- | Typechecker plugins allow plugins to provide evidence to the
          -- typechecker.
        , TcPlugin
          -- ** Source plugins
          -- | GHC offers a number of points where plugins can access and modify its
          -- front-end (\"source\") representation. These include:
          --
          -- - access to the parser result with 'parsedResultAction'
          -- - access to the renamed AST with 'renamedResultAction'
          -- - access to the typechecked AST with 'typeCheckResultAction'
          -- - access to the Template Haskell splices with 'spliceRunAction'
          -- - access to loaded interface files with 'interfaceLoadAction'
          --
        , keepRenamedSource
          -- ** Defaulting plugins
          -- | Defaulting plugins can add candidate types to the defaulting
          -- mechanism.
        , DefaultingPlugin
          -- ** Hole fit plugins
          -- | hole fit plugins allow plugins to change the behavior of valid hole
          -- fit suggestions
        , HoleFitPluginR
          -- ** Late plugins
          -- | Late plugins can access and modify the core of a module after
          -- optimizations have been applied and after interface creation.
        , LatePlugin

          -- * Internal
        , PluginWithArgs(..), pluginsWithArgs, pluginRecompile'
        , LoadedPlugin(..), lpModuleName
        , StaticPlugin(..)
        , ExternalPlugin(..)
        , mapPlugins, withPlugins, withPlugins_
        ) where

    import GHC.Prelude

    import GHC.Driver.Env
    import GHC.Driver.Monad
    import GHC.Driver.Phases
    import GHC.Driver.Plugins.External

    import GHC.Unit.Module
    import GHC.Unit.Module.ModIface
    import GHC.Unit.Module.ModSummary

    import GHC.Parser.Errors.Types (PsWarning, PsError)

    import qualified GHC.Tc.Types
    import GHC.Tc.Types ( TcGblEnv, IfM, TcM, tcg_rn_decls, tcg_rn_exports  )
    import GHC.Tc.Errors.Hole.Plugin ( HoleFitPluginR )

    import GHC.Core.Opt.Monad ( CoreM )
    import GHC.Core.Opt.Pipeline.Types ( CoreToDo )
    import GHC.Hs
    import GHC.Types.Error (Messages)
    import GHC.Linker.Types
    import GHC.Types.CostCentre.State
    import GHC.Types.Unique.DFM

    import GHC.Unit.Module.ModGuts (CgGuts)
    import GHC.Utils.Fingerprint
    import GHC.Utils.Outputable
    import GHC.Utils.Panic

    import Data.List (sort)

    --Qualified import so we can define a Semigroup instance
    -- but it doesn't clash with Outputable.<>
    import qualified Data.Semigroup

    import Control.Monad

    #if defined(HAVE_INTERNAL_INTERPRETER) && defined(CAN_LOAD_DLL)
    import GHCi.ObjLink
    import GHC.Exts (addrToAny#, Ptr(..))
    import GHC.Utils.Encoding
    #endif

    -- | Command line options gathered from the -PModule.Name:stuff syntax
    -- are given to you as this type
    type CommandLineOption = String

    -- | Errors and warnings produced by the parser
    data PsMessages = PsMessages { PsMessages -> Messages PsWarning
    psWarnings :: Messages PsWarning
                                 , PsMessages -> Messages PsWarning
    psErrors   :: Messages PsError
                                 }

    -- | Result of running the parser and the parser plugin
    data ParsedResult = ParsedResult
      { -- | Parsed module, potentially modified by a plugin
        ParsedResult -> HsParsedModule
    parsedResultModule :: HsParsedModule
      , -- | Warnings and errors from parser, potentially modified by a plugin
        ParsedResult -> PsMessages
    parsedResultMessages :: PsMessages
      }

    -- | 'Plugin' is the compiler plugin data type. Try to avoid
    -- constructing one of these directly, and just modify some fields of
    -- 'defaultPlugin' instead: this is to try and preserve source-code
    -- compatibility when we add fields to this.
    --
    -- Nonetheless, this API is preliminary and highly likely to change in
    -- the future.
    data Plugin = Plugin {
        Plugin -> CorePlugin
    installCoreToDos :: CorePlugin
        -- ^ Modify the Core pipeline that will be used for compilation.
        -- This is called as the Core pipeline is built for every module
        -- being compiled, and plugins get the opportunity to modify the
        -- pipeline in a nondeterministic order.
      , Plugin -> TcPlugin
    tcPlugin :: TcPlugin
        -- ^ An optional typechecker plugin, which may modify the
        -- behaviour of the constraint solver.
      , Plugin -> DefaultingPlugin
    defaultingPlugin :: DefaultingPlugin
        -- ^ An optional defaulting plugin, which may specify the
        -- additional type-defaulting rules.
      , Plugin -> HoleFitPlugin
    holeFitPlugin :: HoleFitPlugin
        -- ^ An optional plugin to handle hole fits, which may re-order
        --   or change the list of valid hole fits and refinement hole fits.

      , Plugin -> [CommandLineOption] -> HscEnv -> IO HscEnv
    driverPlugin :: [CommandLineOption] -> HscEnv -> IO HscEnv
        -- ^ An optional plugin to update 'HscEnv', right after plugin loading. This
        -- can be used to register hooks or tweak any field of 'DynFlags' before
        -- doing actual work on a module.
        --
        --   @since 8.10.1

      , Plugin -> LatePlugin
    latePlugin :: LatePlugin
        -- ^ A plugin that runs after interface creation and after late cost centre
        -- insertion. Useful for transformations that should not impact interfaces
        -- or optimization at all.
        --
        -- @since 9.10.1

      , Plugin -> [CommandLineOption] -> IO PluginRecompile
    pluginRecompile :: [CommandLineOption] -> IO PluginRecompile
        -- ^ Specify how the plugin should affect recompilation.
      , Plugin
    -> [CommandLineOption]
    -> ModSummary
    -> ParsedResult
    -> Hsc ParsedResult
    parsedResultAction :: [CommandLineOption] -> ModSummary
                           -> ParsedResult -> Hsc ParsedResult
        -- ^ Modify the module when it is parsed. This is called by
        -- "GHC.Driver.Main" when the parser has produced no or only non-fatal
        -- errors.
        -- Compilation will fail if the messages produced by this function contain
        -- any errors.
      , Plugin
    -> [CommandLineOption]
    -> TcGblEnv
    -> HsGroup GhcRn
    -> TcM (TcGblEnv, HsGroup GhcRn)
    renamedResultAction :: [CommandLineOption] -> TcGblEnv
                                    -> HsGroup GhcRn -> TcM (TcGblEnv, HsGroup GhcRn)
        -- ^ Modify each group after it is renamed. This is called after each
        -- `HsGroup` has been renamed.
      , Plugin
    -> [CommandLineOption] -> ModSummary -> TcGblEnv -> TcM TcGblEnv
    typeCheckResultAction :: [CommandLineOption] -> ModSummary -> TcGblEnv
                                   -> TcM TcGblEnv
        -- ^ Modify the module when it is type checked. This is called at the
        -- very end of typechecking.
      , Plugin
    -> [CommandLineOption] -> LHsExpr GhcTc -> TcM (LHsExpr GhcTc)
    spliceRunAction :: [CommandLineOption] -> LHsExpr GhcTc
                             -> TcM (LHsExpr GhcTc)
        -- ^ Modify the TH splice or quasiqoute before it is run.
      , Plugin
    -> forall lcl. [CommandLineOption] -> ModIface -> IfM lcl ModIface
    interfaceLoadAction :: forall lcl . [CommandLineOption] -> ModIface
                                              -> IfM lcl ModIface
        -- ^ Modify an interface that have been loaded. This is called by
        -- "GHC.Iface.Load" when an interface is successfully loaded. Not applied to
        -- the loading of the plugin interface. Tools that rely on information from
        -- modules other than the currently compiled one should implement this
        -- function.
      }

    -- Note [Source plugins]
    -- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    -- The `Plugin` datatype have been extended by fields that allow access to the
    -- different inner representations that are generated during the compilation
    -- process. These fields are `parsedResultAction`, `renamedResultAction`,
    -- `typeCheckResultAction`, `spliceRunAction` and `interfaceLoadAction`.
    --
    -- The main purpose of these plugins is to help tool developers. They allow
    -- development tools to extract the information about the source code of a big
    -- Haskell project during the normal build procedure. In this case the plugin
    -- acts as the tools access point to the compiler that can be controlled by
    -- compiler flags. This is important because the manipulation of compiler flags
    -- is supported by most build environment.
    --
    -- For the full discussion, check the full proposal at:
    -- https://gitlab.haskell.org/ghc/ghc/wikis/extended-plugins-proposal

    data PluginWithArgs = PluginWithArgs
      { PluginWithArgs -> Plugin
    paPlugin :: Plugin
        -- ^ the actual callable plugin
      , PluginWithArgs -> [CommandLineOption]
    paArguments :: [CommandLineOption]
        -- ^ command line arguments for the plugin
      }

    -- | A plugin with its arguments. The result of loading the plugin.
    data LoadedPlugin = LoadedPlugin
      { LoadedPlugin -> PluginWithArgs
    lpPlugin :: PluginWithArgs
      -- ^ the actual plugin together with its commandline arguments
      , LoadedPlugin -> ModIface
    lpModule :: ModIface
      -- ^ the module containing the plugin
      }

    -- | External plugin loaded directly from a library without loading module
    -- interfaces
    data ExternalPlugin = ExternalPlugin
      { ExternalPlugin -> PluginWithArgs
    epPlugin :: PluginWithArgs -- ^ Plugin with its arguments
      , ExternalPlugin -> CommandLineOption
    epUnit   :: String         -- ^ UnitId
      , ExternalPlugin -> CommandLineOption
    epModule :: String         -- ^ Module name
      }

    -- | A static plugin with its arguments. For registering compiled-in plugins
    -- through the GHC API.
    data StaticPlugin = StaticPlugin
      { StaticPlugin -> PluginWithArgs
    spPlugin :: PluginWithArgs
      -- ^ the actual plugin together with its commandline arguments
      , StaticPlugin -> Bool
    spInitialised :: Bool
      -- ^ has this plugin been initialised (i.e. driverPlugin has been run)
      }

    lpModuleName :: LoadedPlugin -> ModuleName
    lpModuleName :: LoadedPlugin -> ModuleName
    lpModuleName = GenModule Unit -> ModuleName
    forall unit. GenModule unit -> ModuleName
    moduleName (GenModule Unit -> ModuleName)
    -> (LoadedPlugin -> GenModule Unit) -> LoadedPlugin -> ModuleName
    forall b c a. (b -> c) -> (a -> b) -> a -> c
    . ModIface -> GenModule Unit
    forall (phase :: ModIfacePhase). ModIface_ phase -> GenModule Unit
    mi_module (ModIface -> GenModule Unit)
    -> (LoadedPlugin -> ModIface) -> LoadedPlugin -> GenModule Unit
    forall b c a. (b -> c) -> (a -> b) -> a -> c
    . LoadedPlugin -> ModIface
    lpModule

    pluginRecompile' :: PluginWithArgs -> IO PluginRecompile
    pluginRecompile' :: PluginWithArgs -> IO PluginRecompile
    pluginRecompile' (PluginWithArgs Plugin
    plugin [CommandLineOption]
    args) = Plugin -> [CommandLineOption] -> IO PluginRecompile
    pluginRecompile Plugin
    plugin [CommandLineOption]
    args

    data PluginRecompile = ForceRecompile | NoForceRecompile | MaybeRecompile Fingerprint

    instance Outputable PluginRecompile where
      ppr :: PluginRecompile -> SDoc
    ppr PluginRecompile
    ForceRecompile = CommandLineOption -> SDoc
    forall doc. IsLine doc => CommandLineOption -> doc
    text CommandLineOption
    "ForceRecompile"
      ppr PluginRecompile
    NoForceRecompile = CommandLineOption -> SDoc
    forall doc. IsLine doc => CommandLineOption -> doc
    text CommandLineOption
    "NoForceRecompile"
      ppr (MaybeRecompile Fingerprint
    fp) = CommandLineOption -> SDoc
    forall doc. IsLine doc => CommandLineOption -> doc
    text CommandLineOption
    "MaybeRecompile" SDoc -> SDoc -> SDoc
    forall doc. IsLine doc => doc -> doc -> doc
    <+> Fingerprint -> SDoc
    forall a. Outputable a => a -> SDoc
    ppr Fingerprint
    fp

    instance Semigroup PluginRecompile where
      PluginRecompile
    ForceRecompile <> :: PluginRecompile -> PluginRecompile -> PluginRecompile
    <> PluginRecompile
    _ = PluginRecompile
    ForceRecompile
      PluginRecompile
    NoForceRecompile <> PluginRecompile
    r = PluginRecompile
    r
      MaybeRecompile Fingerprint
    fp <> PluginRecompile
    NoForceRecompile   = Fingerprint -> PluginRecompile
    MaybeRecompile Fingerprint
    fp
      MaybeRecompile Fingerprint
    fp <> MaybeRecompile Fingerprint
    fp' = Fingerprint -> PluginRecompile
    MaybeRecompile ([Fingerprint] -> Fingerprint
    fingerprintFingerprints [Fingerprint
    fp, Fingerprint
    fp'])
      MaybeRecompile Fingerprint
    _fp <> PluginRecompile
    ForceRecompile     = PluginRecompile
    ForceRecompile

    instance Monoid PluginRecompile where
      mempty :: PluginRecompile
    mempty = PluginRecompile
    NoForceRecompile

    type CorePlugin = [CommandLineOption] -> [CoreToDo] -> CoreM [CoreToDo]
    type TcPlugin = [CommandLineOption] -> Maybe GHC.Tc.Types.TcPlugin
    type DefaultingPlugin = [CommandLineOption] -> Maybe GHC.Tc.Types.DefaultingPlugin
    type HoleFitPlugin = [CommandLineOption] -> Maybe HoleFitPluginR
    type LatePlugin = HscEnv -> [CommandLineOption] -> (CgGuts, CostCentreState) -> IO (CgGuts, CostCentreState)

    purePlugin, impurePlugin, flagRecompile :: [CommandLineOption] -> IO PluginRecompile
    purePlugin :: [CommandLineOption] -> IO PluginRecompile
    purePlugin [CommandLineOption]
    _args = PluginRecompile -> IO PluginRecompile
    forall a. a -> IO a
    forall (m :: * -> *) a. Monad m => a -> m a
    return PluginRecompile
    NoForceRecompile

    impurePlugin :: [CommandLineOption] -> IO PluginRecompile
    impurePlugin [CommandLineOption]
    _args = PluginRecompile -> IO PluginRecompile
    forall a. a -> IO a
    forall (m :: * -> *) a. Monad m => a -> m a
    return PluginRecompile
    ForceRecompile

    flagRecompile :: [CommandLineOption] -> IO PluginRecompile
    flagRecompile =
      PluginRecompile -> IO PluginRecompile
    forall a. a -> IO a
    forall (m :: * -> *) a. Monad m => a -> m a
    return (PluginRecompile -> IO PluginRecompile)
    -> ([CommandLineOption] -> PluginRecompile)
    -> [CommandLineOption]
    -> IO PluginRecompile
    forall b c a. (b -> c) -> (a -> b) -> a -> c
    . Fingerprint -> PluginRecompile
    MaybeRecompile (Fingerprint -> PluginRecompile)
    -> ([CommandLineOption] -> Fingerprint)
    -> [CommandLineOption]
    -> PluginRecompile
    forall b c a. (b -> c) -> (a -> b) -> a -> c
    . [Fingerprint] -> Fingerprint
    fingerprintFingerprints ([Fingerprint] -> Fingerprint)
    -> ([CommandLineOption] -> [Fingerprint])
    -> [CommandLineOption]
    -> Fingerprint
    forall b c a. (b -> c) -> (a -> b) -> a -> c
    . (CommandLineOption -> Fingerprint)
    -> [CommandLineOption] -> [Fingerprint]
    forall a b. (a -> b) -> [a] -> [b]
    map CommandLineOption -> Fingerprint
    fingerprintString ([CommandLineOption] -> [Fingerprint])
    -> ([CommandLineOption] -> [CommandLineOption])
    -> [CommandLineOption]
    -> [Fingerprint]
    forall b c a. (b -> c) -> (a -> b) -> a -> c
    . [CommandLineOption] -> [CommandLineOption]
    forall a. Ord a => [a] -> [a]
    sort

    -- | Default plugin: does nothing at all, except for marking that safe
    -- inference has failed unless @-fplugin-trustworthy@ is passed. For
    -- compatibility reason you should base all your plugin definitions on this
    -- default value.
    defaultPlugin :: Plugin
    defaultPlugin :: Plugin
    defaultPlugin = Plugin {
            installCoreToDos :: CorePlugin
    installCoreToDos      = ([CoreToDo] -> CoreM [CoreToDo]) -> CorePlugin
    forall a b. a -> b -> a
    const [CoreToDo] -> CoreM [CoreToDo]
    forall a. a -> CoreM a
    forall (m :: * -> *) a. Monad m => a -> m a
    return
          , tcPlugin :: TcPlugin
    tcPlugin              = Maybe TcPlugin -> TcPlugin
    forall a b. a -> b -> a
    const Maybe TcPlugin
    forall a. Maybe a
    Nothing
          , defaultingPlugin :: DefaultingPlugin
    defaultingPlugin      = Maybe DefaultingPlugin -> DefaultingPlugin
    forall a b. a -> b -> a
    const Maybe DefaultingPlugin
    forall a. Maybe a
    Nothing
          , holeFitPlugin :: HoleFitPlugin
    holeFitPlugin         = Maybe HoleFitPluginR -> HoleFitPlugin
    forall a b. a -> b -> a
    const Maybe HoleFitPluginR
    forall a. Maybe a
    Nothing
          , driverPlugin :: [CommandLineOption] -> HscEnv -> IO HscEnv
    driverPlugin          = (HscEnv -> IO HscEnv) -> [CommandLineOption] -> HscEnv -> IO HscEnv
    forall a b. a -> b -> a
    const HscEnv -> IO HscEnv
    forall a. a -> IO a
    forall (m :: * -> *) a. Monad m => a -> m a
    return
          , latePlugin :: LatePlugin
    latePlugin            = \HscEnv
    _ -> ((CgGuts, CostCentreState) -> IO (CgGuts, CostCentreState))
    -> [CommandLineOption]
    -> (CgGuts, CostCentreState)
    -> IO (CgGuts, CostCentreState)
    forall a b. a -> b -> a
    const (CgGuts, CostCentreState) -> IO (CgGuts, CostCentreState)
    forall a. a -> IO a
    forall (m :: * -> *) a. Monad m => a -> m a
    return
          , pluginRecompile :: [CommandLineOption] -> IO PluginRecompile
    pluginRecompile       = [CommandLineOption] -> IO PluginRecompile
    impurePlugin
          , renamedResultAction :: [CommandLineOption]
    -> TcGblEnv -> HsGroup GhcRn -> TcM (TcGblEnv, HsGroup GhcRn)
    renamedResultAction   = \[CommandLineOption]
    _ TcGblEnv
    env HsGroup GhcRn
    grp -> (TcGblEnv, HsGroup GhcRn) -> TcM (TcGblEnv, HsGroup GhcRn)
    forall a. a -> IOEnv (Env TcGblEnv TcLclEnv) a
    forall (m :: * -> *) a. Monad m => a -> m a
    return (TcGblEnv
    env, HsGroup GhcRn
    grp)
          , parsedResultAction :: [CommandLineOption]
    -> ModSummary -> ParsedResult -> Hsc ParsedResult
    parsedResultAction    = \[CommandLineOption]
    _ ModSummary
    _ -> ParsedResult -> Hsc ParsedResult
    forall a. a -> Hsc a
    forall (m :: * -> *) a. Monad m => a -> m a
    return
          , typeCheckResultAction :: [CommandLineOption] -> ModSummary -> TcGblEnv -> TcM TcGblEnv
    typeCheckResultAction = \[CommandLineOption]
    _ ModSummary
    _ -> TcGblEnv -> TcM TcGblEnv
    forall a. a -> IOEnv (Env TcGblEnv TcLclEnv) a
    forall (m :: * -> *) a. Monad m => a -> m a
    return
          , spliceRunAction :: [CommandLineOption] -> LHsExpr GhcTc -> TcM (LHsExpr GhcTc)
    spliceRunAction       = \[CommandLineOption]
    _ -> LHsExpr GhcTc -> TcM (LHsExpr GhcTc)
    GenLocated SrcSpanAnnA (HsExpr GhcTc)
    -> IOEnv
         (Env TcGblEnv TcLclEnv) (GenLocated SrcSpanAnnA (HsExpr GhcTc))
    forall a. a -> IOEnv (Env TcGblEnv TcLclEnv) a
    forall (m :: * -> *) a. Monad m => a -> m a
    return
          , interfaceLoadAction :: forall lcl. [CommandLineOption] -> ModIface -> IfM lcl ModIface
    interfaceLoadAction   = \[CommandLineOption]
    _ -> ModIface -> IfM lcl ModIface
    forall a. a -> IOEnv (Env IfGblEnv lcl) a
    forall (m :: * -> *) a. Monad m => a -> m a
    return
        }

    -- | A renamer plugin which mades the renamed source available in
    -- a typechecker plugin.
    keepRenamedSource :: [CommandLineOption] -> TcGblEnv
                      -> HsGroup GhcRn -> TcM (TcGblEnv, HsGroup GhcRn)
    keepRenamedSource :: [CommandLineOption]
    -> TcGblEnv -> HsGroup GhcRn -> TcM (TcGblEnv, HsGroup GhcRn)
    keepRenamedSource [CommandLineOption]
    _ TcGblEnv
    gbl_env HsGroup GhcRn
    group =
      (TcGblEnv, HsGroup GhcRn) -> TcM (TcGblEnv, HsGroup GhcRn)
    forall a. a -> IOEnv (Env TcGblEnv TcLclEnv) a
    forall (m :: * -> *) a. Monad m => a -> m a
    return (TcGblEnv
    gbl_env { tcg_rn_decls = update (tcg_rn_decls gbl_env)
                      , tcg_rn_exports = update_exports (tcg_rn_exports gbl_env) }, HsGroup GhcRn
    group)
      where
        update_exports :: Maybe [a] -> Maybe [a]
    update_exports Maybe [a]
    Nothing = [a] -> Maybe [a]
    forall a. a -> Maybe a
    Just []
        update_exports Maybe [a]
    m = Maybe [a]
    m

        update :: Maybe (HsGroup (GhcPass p)) -> Maybe (HsGroup (GhcPass p))
    update Maybe (HsGroup (GhcPass p))
    Nothing = HsGroup (GhcPass p) -> Maybe (HsGroup (GhcPass p))
    forall a. a -> Maybe a
    Just HsGroup (GhcPass p)
    forall (p :: Pass). HsGroup (GhcPass p)
    emptyRnGroup
        update Maybe (HsGroup (GhcPass p))
    m       = Maybe (HsGroup (GhcPass p))
    m

    type PluginOperation m a = Plugin -> [CommandLineOption] -> a -> m a
    type ConstPluginOperation m a = Plugin -> [CommandLineOption] -> a -> m ()

    data Plugins = Plugins
      { Plugins -> [StaticPlugin]
    staticPlugins :: ![StaticPlugin]
          -- ^ Static 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.

      , Plugins -> [ExternalPlugin]
    externalPlugins :: ![ExternalPlugin]
          -- ^ External plugins loaded directly from libraries without loading
          -- module interfaces.

      , Plugins -> [LoadedPlugin]
    loadedPlugins :: ![LoadedPlugin]
          -- ^ Plugins dynamically loaded after processing arguments. What
          -- will be loaded here is directed by DynFlags.pluginModNames.
          -- Arguments are loaded from DynFlags.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
          -- 'GHC.Runtime.Loader.initializePlugins'.
      , Plugins -> ([Linkable], PkgsLoaded)
    loadedPluginDeps :: !([Linkable], PkgsLoaded)
      -- ^ The object files required by the loaded plugins
      -- See Note [Plugin dependencies]
      }

    emptyPlugins :: Plugins
    emptyPlugins :: Plugins
    emptyPlugins = Plugins
      { staticPlugins :: [StaticPlugin]
    staticPlugins    = []
      , externalPlugins :: [ExternalPlugin]
    externalPlugins  = []
      , loadedPlugins :: [LoadedPlugin]
    loadedPlugins    = []
      , loadedPluginDeps :: ([Linkable], PkgsLoaded)
    loadedPluginDeps = ([], PkgsLoaded
    forall {k} (key :: k) elt. UniqDFM key elt
    emptyUDFM)
      }

    pluginsWithArgs :: Plugins -> [PluginWithArgs]
    pluginsWithArgs :: Plugins -> [PluginWithArgs]
    pluginsWithArgs Plugins
    plugins =
      (LoadedPlugin -> PluginWithArgs)
    -> [LoadedPlugin] -> [PluginWithArgs]
    forall a b. (a -> b) -> [a] -> [b]
    map LoadedPlugin -> PluginWithArgs
    lpPlugin (Plugins -> [LoadedPlugin]
    loadedPlugins Plugins
    plugins) [PluginWithArgs] -> [PluginWithArgs] -> [PluginWithArgs]
    forall a. [a] -> [a] -> [a]
    ++
      (ExternalPlugin -> PluginWithArgs)
    -> [ExternalPlugin] -> [PluginWithArgs]
    forall a b. (a -> b) -> [a] -> [b]
    map ExternalPlugin -> PluginWithArgs
    epPlugin (Plugins -> [ExternalPlugin]
    externalPlugins Plugins
    plugins) [PluginWithArgs] -> [PluginWithArgs] -> [PluginWithArgs]
    forall a. [a] -> [a] -> [a]
    ++
      (StaticPlugin -> PluginWithArgs)
    -> [StaticPlugin] -> [PluginWithArgs]
    forall a b. (a -> b) -> [a] -> [b]
    map StaticPlugin -> PluginWithArgs
    spPlugin (Plugins -> [StaticPlugin]
    staticPlugins Plugins
    plugins)

    -- | Perform an operation by using all of the plugins in turn.
    withPlugins :: Monad m => Plugins -> PluginOperation m a -> a -> m a
    withPlugins :: forall (m :: * -> *) a.
    Monad m =>
    Plugins -> PluginOperation m a -> a -> m a
    withPlugins Plugins
    plugins PluginOperation m a
    transformation a
    input = (a -> PluginWithArgs -> m a) -> a -> [PluginWithArgs] -> m a
    forall (t :: * -> *) (m :: * -> *) b a.
    (Foldable t, Monad m) =>
    (b -> a -> m b) -> b -> t a -> m b
    foldM a -> PluginWithArgs -> m a
    go a
    input (Plugins -> [PluginWithArgs]
    pluginsWithArgs Plugins
    plugins)
      where
        go :: a -> PluginWithArgs -> m a
    go a
    arg (PluginWithArgs Plugin
    p [CommandLineOption]
    opts) = PluginOperation m a
    transformation Plugin
    p [CommandLineOption]
    opts a
    arg

    mapPlugins :: Plugins -> (Plugin -> [CommandLineOption] -> a) -> [a]
    mapPlugins :: forall a. Plugins -> (Plugin -> [CommandLineOption] -> a) -> [a]
    mapPlugins Plugins
    plugins Plugin -> [CommandLineOption] -> a
    f = (PluginWithArgs -> a) -> [PluginWithArgs] -> [a]
    forall a b. (a -> b) -> [a] -> [b]
    map (\(PluginWithArgs Plugin
    p [CommandLineOption]
    opts) -> Plugin -> [CommandLineOption] -> a
    f Plugin
    p [CommandLineOption]
    opts) (Plugins -> [PluginWithArgs]
    pluginsWithArgs Plugins
    plugins)

    -- | Perform a constant operation by using all of the plugins in turn.
    withPlugins_ :: Monad m => Plugins -> ConstPluginOperation m a -> a -> m ()
    withPlugins_ :: forall (m :: * -> *) a.
    Monad m =>
    Plugins -> ConstPluginOperation m a -> a -> m ()
    withPlugins_ Plugins
    plugins ConstPluginOperation m a
    transformation a
    input
      = (PluginWithArgs -> m ()) -> [PluginWithArgs] -> m ()
    forall (t :: * -> *) (m :: * -> *) a b.
    (Foldable t, Monad m) =>
    (a -> m b) -> t a -> m ()
    mapM_ (\(PluginWithArgs Plugin
    p [CommandLineOption]
    opts) -> ConstPluginOperation m a
    transformation Plugin
    p [CommandLineOption]
    opts a
    input)
              (Plugins -> [PluginWithArgs]
    pluginsWithArgs Plugins
    plugins)

    type FrontendPluginAction = [String] -> [(String, Maybe Phase)] -> Ghc ()
    data FrontendPlugin = FrontendPlugin {
          FrontendPlugin -> FrontendPluginAction
    frontend :: FrontendPluginAction
        }
    defaultFrontendPlugin :: FrontendPlugin
    defaultFrontendPlugin :: FrontendPlugin
    defaultFrontendPlugin = FrontendPlugin { frontend :: FrontendPluginAction
    frontend = \[CommandLineOption]
    _ [(CommandLineOption, Maybe Phase)]
    _ -> () -> Ghc ()
    forall a. a -> Ghc a
    forall (m :: * -> *) a. Monad m => a -> m a
    return () }

    -- | Load external plugins
    loadExternalPlugins :: [ExternalPluginSpec] -> IO [ExternalPlugin]
    loadExternalPlugins :: [ExternalPluginSpec] -> IO [ExternalPlugin]
    loadExternalPlugins [] = [ExternalPlugin] -> IO [ExternalPlugin]
    forall a. a -> IO a
    forall (m :: * -> *) a. Monad m => a -> m a
    return []
    #if !defined(HAVE_INTERNAL_INTERPRETER)
    loadExternalPlugins [ExternalPluginSpec]
    _ = do
      CommandLineOption -> IO [ExternalPlugin]
    forall a. HasCallStack => CommandLineOption -> a
    panic CommandLineOption
    "loadExternalPlugins: can't load external plugins with GHC built without internal interpreter"
    #elif !defined(CAN_LOAD_DLL)
    loadExternalPlugins _ = do
      panic "loadExternalPlugins: loading shared libraries isn't supported by this compiler"
    #else
    loadExternalPlugins ps = do
      -- initialize the linker
      initObjLinker RetainCAFs
      -- load plugins
      forM ps $ \(ExternalPluginSpec path unit mod_name opts) -> do
        loadExternalPluginLib path
        -- lookup symbol
        let ztmp = zEncodeString mod_name ++ "_plugin_closure"
            symbol
              | null unit = ztmp
              | otherwise = zEncodeString unit ++ "_" ++ ztmp
        plugin <- lookupSymbol symbol >>= \case
          Nothing -> pprPanic "loadExternalPlugins"
                      (vcat [ text "Symbol not found"
                            , text "  Library path: " <> text path
                            , text "  Symbol      : " <> text symbol
                            ])
          Just (Ptr addr) -> case addrToAny# addr of
            (# a #) -> pure a

        pure $ ExternalPlugin (PluginWithArgs plugin opts) unit mod_name

    loadExternalPluginLib :: FilePath -> IO ()
    loadExternalPluginLib path = do
      -- load library
      loadDLL path >>= \case
        Left errmsg -> pprPanic "loadExternalPluginLib"
                         (vcat [ text "Can't load plugin library"
                               , text "  Library path: " <> text path
                               , text "  Error       : " <> text errmsg
                               ])
        Right _ -> do
          -- resolve objects
          resolveObjs >>= \case
            True -> return ()
            False -> pprPanic "loadExternalPluginLib" (text "Unable to resolve objects for library: " <> text path)

    #endif