anvil-sdk 0.1.8

Safe Rust API for plugins of Anvil, the plugin loader for Europa Universalis IV
Documentation
//! Safe Rust API for plugins of [Anvil](https://github.com/happy-dwarf-team/anvil),
//! the native plugin loader for Europa Universalis IV 1.37.5.
//!
//! The crate sits on the raw bindings of [`anvil-sys`](sys) and adds what the C
//! ABI leaves to every plugin:
//!
//! - [`plugin!`]: exports `anvil_plugin_load`, creates the plugin with
//!   [`Plugin::load`] and turns an [`Error`] or a panic into the result Anvil
//!   rolls the plugin back on.
//! - Every callback Anvil or the game calls through an adapter of this crate
//!   (mid hooks, block replacements, events, settings, panel clicks, work for
//!   the main thread) runs under `catch_unwind`: a panic is logged once per
//!   callback and never crosses the FFI.
//! - [`Change`] is a handle whose `Drop` removes the change.
//! - Typed wrappers of the services Anvil ships: [`game`] (`anvil-game.game`),
//!   [`world`] (`anvil-game.world`), [`panel`] (`anvil-overlay.panel`),
//!   [`benchmark`] (`anvil.benchmark`), [`map`] (`anvil-map.modes`),
//!   [`script`] (`anvil-script.effects`, `anvil-script.day_end`) and
//!   [`log_throttle`] (`anvil-log-throttle.messages`).
//!
//! # Where `unsafe` stays
//!
//! Host and service calls are safe. What reaches the game's memory by address
//! or puts raw bytes and pointers into it stays an `unsafe fn` with its
//! contract: calling a hook's [`next`](FunctionHook::next) (the generated
//! function types are `unsafe extern "C" fn`), [`Host::function`],
//! [`Host::data`], writing the mid-hook context ([`Cpu::regs_mut`]), byte
//! patches, pointer swaps, call redirects, import replacements and changes at
//! raw addresses.
//!
//! # A plugin
//!
//! ```no_run
//! use anvil::{Change, Host, Plugin};
//!
//! #[allow(dead_code)]
//! mod sym {
//!     // anvil gen --lang rust symbols.toml writes this file (build.rs).
//!     pub const IDLE_EXIT: u32 = 0;
//! }
//!
//! struct Hello {
//!     // Dropping a Change removes it; the plugin is kept for the process.
//!     _idle_exit: Change,
//! }
//!
//! impl Plugin for Hello {
//!     fn load(host: &mut Host) -> anvil::Result<Self> {
//!         host.info(format_args!("hello from Rust on Anvil {}", host.anvil_version()));
//!         let log = *host;
//!         let idle_exit = host.mid_hook(sym::IDLE_EXIT, move |cpu| {
//!             log.info(format_args!("returning to the menu (rcx={:#x})", cpu.rcx));
//!         })?;
//!         Ok(Hello { _idle_exit: idle_exit })
//!     }
//! }
//!
//! anvil::plugin!(Hello);
//! ```
//!
//! Versions: this crate has its own `0.x` line; the source compatibility of
//! Anvil's ADR 0001 covers it from its 1.0.
#![deny(unsafe_op_in_unsafe_fn)]
#![warn(missing_docs, clippy::undocumented_unsafe_blocks)]

pub use anvil_sys as sys;

/// The function `$field` of a service table, when the table's `size` covers
/// it (the `ANVIL_*_HAS` macros of the C headers); else `Unsupported`.
macro_rules! function {
    ($table:expr, $ty:ty, $field:ident) => {{
        let table: &$ty = $table;
        let present = table.size as usize
            >= ::core::mem::offset_of!($ty, $field) + ::core::mem::size_of_val(&table.$field);
        $crate::error::need(
            if present { table.$field } else { None },
            stringify!($field),
        )
    }};
}

mod change;
mod cpu;
mod error;
mod event;
mod fnptr;
mod host;
mod panic;
mod text;

pub mod benchmark;
pub mod commands;
pub mod game;
pub mod input;
pub mod log_throttle;
pub mod map;
pub mod panel;
pub mod script;
pub mod world;

#[cfg(test)]
mod tests;

pub use change::{Change, FunctionHook, PointerSwap};
pub use cpu::Cpu;
pub use error::{Error, ErrorCode, Result};
pub use event::{Event, Payload, PLUGINS_LOADED, RESUMED, SUSPENDED};
pub use fnptr::FnPtr;
pub use host::{GameInfo, Host, Key, LogLevel};
pub use panic::catch_panic;
pub use text::Tag;

/// A plugin: one value, created by [`plugin!`] when Anvil loads the DLL and
/// kept for the life of the process.
///
/// Request the changes in [`load`](Plugin::load); Anvil enables them together
/// when it returns `Ok`. Return an error (or let a host call's error propagate
/// with `?`) to refuse loading: Anvil rolls back everything the plugin staged.
pub trait Plugin: Sized + 'static {
    /// Called once, in the phase `plugin.toml` names.
    fn load(host: &mut Host) -> Result<Self>;
}

/// Exports `anvil_plugin_load` for the plugin type: `anvil::plugin!(MyPlugin);`
/// once, at the root of the plugin's `cdylib`.
#[macro_export]
macro_rules! plugin {
    ($plugin:ty) => {
        /// The entry point Anvil calls once (generated by `anvil::plugin!`).
        ///
        /// # Safety
        /// Called by Anvil with its host table and this plugin's handle.
        #[unsafe(no_mangle)]
        pub unsafe extern "C" fn anvil_plugin_load(
            host: *const $crate::sys::AnvilHost,
            plugin: *mut $crate::sys::AnvilPlugin,
        ) -> $crate::sys::AnvilResult {
            // SAFETY: forwarded from Anvil, which calls this export once.
            unsafe { $crate::__private::load::<$plugin>(host, plugin) }
        }

        const _: $crate::sys::AnvilPluginLoadFn = anvil_plugin_load;
    };
}

#[doc(hidden)]
pub mod __private {
    use crate::sys::{
        AnvilHost, AnvilPlugin, AnvilResult, ANVIL_API_VERSION, ANVIL_ERROR_INTERNAL,
        ANVIL_ERROR_INVALID_ARGUMENT, ANVIL_ERROR_UNSUPPORTED, ANVIL_OK,
    };
    use crate::{host, panic, Host, LogLevel, Plugin};

    /// What `plugin!` exports.
    ///
    /// # Safety
    /// `table` is Anvil's host table (or null) and `plugin` this plugin's
    /// handle, both valid for the life of the process.
    pub unsafe fn load<P: Plugin>(
        table: *const AnvilHost,
        plugin: *mut AnvilPlugin,
    ) -> AnvilResult {
        // SAFETY: see the contract above.
        let Some(table) = (unsafe { table.as_ref() }) else {
            return ANVIL_ERROR_INVALID_ARGUMENT;
        };
        if table.api_version != ANVIL_API_VERSION
            || !host::covers_api_2_0(table)
            || plugin.is_null()
        {
            return ANVIL_ERROR_UNSUPPORTED;
        }
        host::install(table, plugin);
        panic::install_hook();
        let mut host = Host::from_parts(table, plugin);
        match panic::catch(|| P::load(&mut host)) {
            Ok(Ok(loaded)) => {
                // Kept for the process, as Anvil keeps the DLL: its changes stay.
                std::mem::forget(loaded);
                ANVIL_OK
            }
            Ok(Err(error)) => {
                host.log(LogLevel::Error, format_args!("load() failed: {error}"));
                error.code().result()
            }
            Err(message) => {
                host.log(LogLevel::Error, format_args!("load() panicked: {message}"));
                ANVIL_ERROR_INTERNAL
            }
        }
    }
}