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

-- | 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
      Plugin(..)
    , defaultPlugin
    , CommandLineOption
      -- ** 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
      -- ** Hole fit plugins
      -- | hole fit plugins allow plugins to change the behavior of valid hole
      -- fit suggestions
    , HoleFitPluginR

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

import GHC.Prelude

import GHC.Core.Opt.Monad ( CoreToDo, CoreM )
import qualified GHC.Tc.Types
import GHC.Tc.Types ( TcGblEnv, IfM, TcM, tcg_rn_decls, tcg_rn_exports  )
import GHC.Tc.Errors.Hole.FitTypes ( HoleFitPluginR )
import GHC.Hs
import GHC.Driver.Session
import GHC.Driver.Types
import GHC.Driver.Monad
import GHC.Driver.Phases
import GHC.Unit.Module
import GHC.Utils.Fingerprint
import Data.List (sort)
import GHC.Utils.Outputable (Outputable(..), text, (<+>))

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

import Control.Monad

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

-- | '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 -> 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 -> [String] -> DynFlags -> IO DynFlags
dynflagsPlugin :: [CommandLineOption] -> DynFlags -> IO DynFlags
    -- ^ An optional plugin to update 'DynFlags', 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 -> [String] -> IO PluginRecompile
pluginRecompile :: [CommandLineOption] -> IO PluginRecompile
    -- ^ Specify how the plugin should affect recompilation.
  , Plugin
-> [String] -> ModSummary -> HsParsedModule -> Hsc HsParsedModule
parsedResultAction :: [CommandLineOption] -> ModSummary -> HsParsedModule
                            -> Hsc HsParsedModule
    -- ^ Modify the module when it is parsed. This is called by
    -- "GHC.Driver.Main" when the parsing is successful.
  , Plugin
-> [String]
-> 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 -> [String] -> 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 -> [String] -> 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. [String] -> 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 -> [String]
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
  }

-- | 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
  }

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 [String]
args) = Plugin -> [String] -> IO PluginRecompile
pluginRecompile Plugin
plugin [String]
args

data PluginRecompile = ForceRecompile | NoForceRecompile | MaybeRecompile Fingerprint

instance Outputable PluginRecompile where
  ppr :: PluginRecompile -> SDoc
ppr PluginRecompile
ForceRecompile = String -> SDoc
text String
"ForceRecompile"
  ppr PluginRecompile
NoForceRecompile = String -> SDoc
text String
"NoForceRecompile"
  ppr (MaybeRecompile Fingerprint
fp) = String -> SDoc
text String
"MaybeRecompile" SDoc -> SDoc -> SDoc
<+> 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 HoleFitPlugin = [CommandLineOption] -> Maybe HoleFitPluginR

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

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

flagRecompile :: [String] -> IO PluginRecompile
flagRecompile =
  PluginRecompile -> IO PluginRecompile
forall (m :: * -> *) a. Monad m => a -> m a
return (PluginRecompile -> IO PluginRecompile)
-> ([String] -> PluginRecompile) -> [String] -> IO PluginRecompile
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Fingerprint -> PluginRecompile
MaybeRecompile (Fingerprint -> PluginRecompile)
-> ([String] -> Fingerprint) -> [String] -> PluginRecompile
forall b c a. (b -> c) -> (a -> b) -> a -> c
. [Fingerprint] -> Fingerprint
fingerprintFingerprints ([Fingerprint] -> Fingerprint)
-> ([String] -> [Fingerprint]) -> [String] -> Fingerprint
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (String -> Fingerprint) -> [String] -> [Fingerprint]
forall a b. (a -> b) -> [a] -> [b]
map String -> Fingerprint
fingerprintString ([String] -> [Fingerprint])
-> ([String] -> [String]) -> [String] -> [Fingerprint]
forall b c a. (b -> c) -> (a -> b) -> a -> c
. [String] -> [String]
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 :: CorePlugin
-> TcPlugin
-> HoleFitPlugin
-> ([String] -> DynFlags -> IO DynFlags)
-> ([String] -> IO PluginRecompile)
-> ([String] -> ModSummary -> HsParsedModule -> Hsc HsParsedModule)
-> ([String]
    -> TcGblEnv -> HsGroup GhcRn -> TcM (TcGblEnv, HsGroup GhcRn))
-> ([String] -> ModSummary -> TcGblEnv -> TcM TcGblEnv)
-> ([String] -> LHsExpr GhcTc -> TcM (LHsExpr GhcTc))
-> (forall lcl. [String] -> ModIface -> IfM lcl ModIface)
-> Plugin
Plugin {
        installCoreToDos :: CorePlugin
installCoreToDos      = ([CoreToDo] -> CoreM [CoreToDo]) -> CorePlugin
forall a b. a -> b -> a
const [CoreToDo] -> CoreM [CoreToDo]
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
      , holeFitPlugin :: HoleFitPlugin
holeFitPlugin         = Maybe HoleFitPluginR -> HoleFitPlugin
forall a b. a -> b -> a
const Maybe HoleFitPluginR
forall a. Maybe a
Nothing
      , dynflagsPlugin :: [String] -> DynFlags -> IO DynFlags
dynflagsPlugin        = (DynFlags -> IO DynFlags) -> [String] -> DynFlags -> IO DynFlags
forall a b. a -> b -> a
const DynFlags -> IO DynFlags
forall (m :: * -> *) a. Monad m => a -> m a
return
      , pluginRecompile :: [String] -> IO PluginRecompile
pluginRecompile       = [String] -> IO PluginRecompile
impurePlugin
      , renamedResultAction :: [String]
-> TcGblEnv -> HsGroup GhcRn -> TcM (TcGblEnv, HsGroup GhcRn)
renamedResultAction   = \[String]
_ TcGblEnv
env HsGroup GhcRn
grp -> (TcGblEnv, HsGroup GhcRn) -> TcM (TcGblEnv, HsGroup GhcRn)
forall (m :: * -> *) a. Monad m => a -> m a
return (TcGblEnv
env, HsGroup GhcRn
grp)
      , parsedResultAction :: [String] -> ModSummary -> HsParsedModule -> Hsc HsParsedModule
parsedResultAction    = \[String]
_ ModSummary
_ -> HsParsedModule -> Hsc HsParsedModule
forall (m :: * -> *) a. Monad m => a -> m a
return
      , typeCheckResultAction :: [String] -> ModSummary -> TcGblEnv -> TcM TcGblEnv
typeCheckResultAction = \[String]
_ ModSummary
_ -> TcGblEnv -> TcM TcGblEnv
forall (m :: * -> *) a. Monad m => a -> m a
return
      , spliceRunAction :: [String] -> LHsExpr GhcTc -> TcM (LHsExpr GhcTc)
spliceRunAction       = \[String]
_ -> LHsExpr GhcTc -> TcM (LHsExpr GhcTc)
forall (m :: * -> *) a. Monad m => a -> m a
return
      , interfaceLoadAction :: forall lcl. [String] -> ModIface -> IfM lcl ModIface
interfaceLoadAction   = \[String]
_ -> ModIface -> IfM lcl ModIface
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 :: [String]
-> TcGblEnv -> HsGroup GhcRn -> TcM (TcGblEnv, HsGroup GhcRn)
keepRenamedSource [String]
_ TcGblEnv
gbl_env HsGroup GhcRn
group =
  (TcGblEnv, HsGroup GhcRn) -> TcM (TcGblEnv, HsGroup GhcRn)
forall (m :: * -> *) a. Monad m => a -> m a
return (TcGblEnv
gbl_env { tcg_rn_decls :: Maybe (HsGroup GhcRn)
tcg_rn_decls = Maybe (HsGroup GhcRn) -> Maybe (HsGroup GhcRn)
forall {p :: Pass}.
Maybe (HsGroup (GhcPass p)) -> Maybe (HsGroup (GhcPass p))
update (TcGblEnv -> Maybe (HsGroup GhcRn)
tcg_rn_decls TcGblEnv
gbl_env)
                  , tcg_rn_exports :: Maybe [(Located (IE GhcRn), Avails)]
tcg_rn_exports = Maybe [(Located (IE GhcRn), Avails)]
-> Maybe [(Located (IE GhcRn), Avails)]
forall {a}. Maybe [a] -> Maybe [a]
update_exports (TcGblEnv -> Maybe [(Located (IE GhcRn), Avails)]
tcg_rn_exports TcGblEnv
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 ()

plugins :: DynFlags -> [PluginWithArgs]
plugins :: DynFlags -> [PluginWithArgs]
plugins DynFlags
df =
  (LoadedPlugin -> PluginWithArgs)
-> [LoadedPlugin] -> [PluginWithArgs]
forall a b. (a -> b) -> [a] -> [b]
map LoadedPlugin -> PluginWithArgs
lpPlugin (DynFlags -> [LoadedPlugin]
cachedPlugins DynFlags
df) [PluginWithArgs] -> [PluginWithArgs] -> [PluginWithArgs]
forall a. [a] -> [a] -> [a]
++
  (StaticPlugin -> PluginWithArgs)
-> [StaticPlugin] -> [PluginWithArgs]
forall a b. (a -> b) -> [a] -> [b]
map StaticPlugin -> PluginWithArgs
spPlugin (DynFlags -> [StaticPlugin]
staticPlugins DynFlags
df)

-- | Perform an operation by using all of the plugins in turn.
withPlugins :: Monad m => DynFlags -> PluginOperation m a -> a -> m a
withPlugins :: forall (m :: * -> *) a.
Monad m =>
DynFlags -> PluginOperation m a -> a -> m a
withPlugins DynFlags
df 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 (DynFlags -> [PluginWithArgs]
plugins DynFlags
df)
  where
    go :: a -> PluginWithArgs -> m a
go a
arg (PluginWithArgs Plugin
p [String]
opts) = PluginOperation m a
transformation Plugin
p [String]
opts a
arg

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

-- | Perform a constant operation by using all of the plugins in turn.
withPlugins_ :: Monad m => DynFlags -> ConstPluginOperation m a -> a -> m ()
withPlugins_ :: forall (m :: * -> *) a.
Monad m =>
DynFlags -> ConstPluginOperation m a -> a -> m ()
withPlugins_ DynFlags
df 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 [String]
opts) -> ConstPluginOperation m a
transformation Plugin
p [String]
opts a
input)
          (DynFlags -> [PluginWithArgs]
plugins DynFlags
df)

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