Skip to main content

anvil/
error.rs

1use std::borrow::Cow;
2use std::fmt;
3
4use crate::sys::{self, AnvilResult};
5
6/// The result of a host or service call.
7pub type Result<T, E = Error> = std::result::Result<T, E>;
8
9/// Why Anvil or a service refused a call: an `AnvilResult` other than
10/// `ANVIL_OK`.
11#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
12#[non_exhaustive]
13pub enum ErrorCode {
14    /// `ANVIL_ERROR_INVALID_ARGUMENT`.
15    InvalidArgument,
16    /// `ANVIL_ERROR_NOT_DECLARED`: an unknown symbol or setting, a raw pointer
17    /// into eu4.exe, or a symbol the game build declares absent.
18    NotDeclared,
19    /// `ANVIL_ERROR_WRONG_KIND`: e.g. a pointer swap on a function symbol.
20    WrongKind,
21    /// `ANVIL_ERROR_CONFLICT`: overlaps another change at a different address.
22    Conflict,
23    /// `ANVIL_ERROR_UNSAFE_SITE`.
24    UnsafeSite,
25    /// `ANVIL_ERROR_BYTES_MISMATCH`.
26    BytesMismatch,
27    /// `ANVIL_ERROR_OUT_OF_MEMORY`.
28    OutOfMemory,
29    /// `ANVIL_ERROR_WRONG_PHASE`: e.g. a group inside `load`, or a world read
30    /// off the game's main thread.
31    WrongPhase,
32    /// `ANVIL_ERROR_UNSUPPORTED`: also a function the running host or service
33    /// is too old to have.
34    Unsupported,
35    /// `ANVIL_ERROR_INTERNAL`.
36    Internal,
37    /// `ANVIL_ERROR_NOT_FOUND`.
38    NotFound,
39    /// `ANVIL_ERROR_ALREADY_EXISTS`.
40    AlreadyExists,
41    /// `ANVIL_ERROR_SUSPENDED`: the caller is suspended in this session
42    /// (ironman, multiplayer). Since Anvil 1.17.0.
43    Suspended,
44    /// `ANVIL_ERROR_LIMIT`: more than a service takes at once; nothing of the
45    /// call was done. Since Anvil 1.17.0.
46    Limit,
47    /// `ANVIL_ERROR_DISABLED`: the player turned this module off
48    /// ([`Host::module`](crate::Host::module)). Since Anvil 1.22.0 (working
49    /// number; ADR 0011).
50    Disabled,
51    /// A result this crate does not know.
52    Other(AnvilResult),
53}
54
55impl ErrorCode {
56    /// The code of `result`; `None` for `ANVIL_OK`.
57    pub const fn from_result(result: AnvilResult) -> Option<Self> {
58        Some(match result {
59            sys::ANVIL_OK => return None,
60            sys::ANVIL_ERROR_INVALID_ARGUMENT => Self::InvalidArgument,
61            sys::ANVIL_ERROR_NOT_DECLARED => Self::NotDeclared,
62            sys::ANVIL_ERROR_WRONG_KIND => Self::WrongKind,
63            sys::ANVIL_ERROR_CONFLICT => Self::Conflict,
64            sys::ANVIL_ERROR_UNSAFE_SITE => Self::UnsafeSite,
65            sys::ANVIL_ERROR_BYTES_MISMATCH => Self::BytesMismatch,
66            sys::ANVIL_ERROR_OUT_OF_MEMORY => Self::OutOfMemory,
67            sys::ANVIL_ERROR_WRONG_PHASE => Self::WrongPhase,
68            sys::ANVIL_ERROR_UNSUPPORTED => Self::Unsupported,
69            sys::ANVIL_ERROR_INTERNAL => Self::Internal,
70            sys::ANVIL_ERROR_NOT_FOUND => Self::NotFound,
71            sys::ANVIL_ERROR_ALREADY_EXISTS => Self::AlreadyExists,
72            sys::ANVIL_ERROR_SUSPENDED => Self::Suspended,
73            sys::ANVIL_ERROR_LIMIT => Self::Limit,
74            sys::ANVIL_ERROR_DISABLED => Self::Disabled,
75            other => Self::Other(other),
76        })
77    }
78
79    /// The `AnvilResult` of the code, never `ANVIL_OK`.
80    pub const fn result(self) -> AnvilResult {
81        match self {
82            Self::InvalidArgument => sys::ANVIL_ERROR_INVALID_ARGUMENT,
83            Self::NotDeclared => sys::ANVIL_ERROR_NOT_DECLARED,
84            Self::WrongKind => sys::ANVIL_ERROR_WRONG_KIND,
85            Self::Conflict => sys::ANVIL_ERROR_CONFLICT,
86            Self::UnsafeSite => sys::ANVIL_ERROR_UNSAFE_SITE,
87            Self::BytesMismatch => sys::ANVIL_ERROR_BYTES_MISMATCH,
88            Self::OutOfMemory => sys::ANVIL_ERROR_OUT_OF_MEMORY,
89            Self::WrongPhase => sys::ANVIL_ERROR_WRONG_PHASE,
90            Self::Unsupported => sys::ANVIL_ERROR_UNSUPPORTED,
91            Self::Internal => sys::ANVIL_ERROR_INTERNAL,
92            Self::NotFound => sys::ANVIL_ERROR_NOT_FOUND,
93            Self::AlreadyExists => sys::ANVIL_ERROR_ALREADY_EXISTS,
94            Self::Suspended => sys::ANVIL_ERROR_SUSPENDED,
95            Self::Limit => sys::ANVIL_ERROR_LIMIT,
96            Self::Disabled => sys::ANVIL_ERROR_DISABLED,
97            Self::Other(sys::ANVIL_OK) => sys::ANVIL_ERROR_INTERNAL,
98            Self::Other(other) => other,
99        }
100    }
101
102    /// The words Anvil's log uses for it, as `anvil.hpp`'s `result_name`.
103    pub const fn description(self) -> &'static str {
104        match self {
105            Self::InvalidArgument => "invalid argument",
106            Self::NotDeclared => "not declared in symbols.toml or settings.toml",
107            Self::WrongKind => "wrong kind of symbol or setting",
108            Self::Conflict => "conflict with another change",
109            Self::UnsafeSite => "unsafe site",
110            Self::BytesMismatch => "bytes mismatch",
111            Self::OutOfMemory => "out of memory",
112            Self::WrongPhase => "wrong phase",
113            Self::Unsupported => "unsupported",
114            Self::Internal => "internal error",
115            Self::NotFound => "not found",
116            Self::AlreadyExists => "already exists",
117            Self::Suspended => "suspended in this session",
118            Self::Limit => "over the limit",
119            Self::Disabled => "turned off by the player",
120            Self::Other(_) => "unknown result",
121        }
122    }
123}
124
125impl fmt::Display for ErrorCode {
126    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
127        f.write_str(self.description())
128    }
129}
130
131/// A call that failed: its [`ErrorCode`] and what was called, e.g.
132/// "hook_function symbol 0: conflict with another change".
133#[derive(Clone, Debug, PartialEq, Eq)]
134pub struct Error {
135    code: ErrorCode,
136    context: Cow<'static, str>,
137}
138
139impl Error {
140    /// An error of the plugin's own, e.g. to refuse loading from
141    /// [`Plugin::load`](crate::Plugin::load): `context` says why.
142    pub fn new(code: ErrorCode, context: impl Into<Cow<'static, str>>) -> Self {
143        Self {
144            code,
145            context: context.into(),
146        }
147    }
148
149    /// The code, which becomes `anvil_plugin_load`'s result when `load` returns it.
150    pub const fn code(&self) -> ErrorCode {
151        self.code
152    }
153
154    /// What failed, without the code's words.
155    pub fn context(&self) -> &str {
156        &self.context
157    }
158}
159
160impl fmt::Display for Error {
161    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
162        if self.context.is_empty() {
163            f.write_str(self.code.description())
164        } else {
165            write!(f, "{}: {}", self.context, self.code.description())
166        }
167    }
168}
169
170impl std::error::Error for Error {}
171
172/// `Ok` for `ANVIL_OK`, else the error with `context()` as its context (only
173/// built on failure).
174pub(crate) fn check<C: Into<Cow<'static, str>>>(
175    result: AnvilResult,
176    context: impl FnOnce() -> C,
177) -> Result<()> {
178    match ErrorCode::from_result(result) {
179        None => Ok(()),
180        Some(code) => Err(Error::new(code, context())),
181    }
182}
183
184/// The function `name` of a table, or `Unsupported` when it is missing.
185pub(crate) fn need<F>(function: Option<F>, name: &'static str) -> Result<F> {
186    function.ok_or_else(|| {
187        Error::new(
188            ErrorCode::Unsupported,
189            format!("{name}: not provided by this version"),
190        )
191    })
192}