Skip to main content

ext_php_rs/
error.rs

1//! Error and result types returned from the library functions.
2
3use std::{
4    ffi::{CString, NulError, c_int},
5    num::TryFromIntError,
6};
7
8use crate::{
9    exception::PhpException,
10    ffi::php_error_docref,
11    flags::{ClassFlags, DataType, ErrorType, ZvalTypeFlags},
12    zend::{CatchError, ExecutorGlobals},
13};
14
15/// The main result type which is passed by the library.
16pub type Result<T, E = Error> = std::result::Result<T, E>;
17
18const _: fn() = || {
19    fn assert_send_sync<T: Send + Sync + 'static>() {}
20    assert_send_sync::<Error>();
21};
22
23const _: () = assert!(
24    size_of::<Error>() == size_of::<String>() + size_of::<usize>(),
25    "Error is returned by every Result in the crate, including the conversion paths: a variant that grows it past a String payload is paid for on every call"
26);
27
28/// The main error type which is passed by the library inside the custom
29/// [`Result`] type.
30#[derive(Debug, thiserror::Error)]
31#[non_exhaustive]
32pub enum Error {
33    /// An incorrect number of arguments was given to a PHP function.
34    ///
35    /// The enum carries two integers - the first representing the number of
36    /// arguments that were received, and the second representing the minimum
37    /// number of arguments expected.
38    #[error("expected at least {1} arguments, got {0} arguments")]
39    IncorrectArguments(usize, usize),
40    /// There was an error converting a Zval into a primitive type.
41    ///
42    /// The enum carries the data type of the Zval.
43    #[error("could not convert value of type {0}")]
44    ZvalConversion(DataType),
45    /// The function type read from the engine is not one this crate models.
46    ///
47    /// The enum carries the raw value read from `zend_function.type`.
48    #[error("unknown function type {0}")]
49    UnknownFunctionType(u8),
50    /// Attempted to convert a [`ZvalTypeFlags`] struct to a [`DataType`].
51    /// The flags did not contain a datatype.
52    ///
53    /// The enum carries the flags that were attempted to be converted to a
54    /// [`DataType`].
55    #[error("type flags did not contain a datatype: {0:?}")]
56    InvalidTypeToDatatype(ZvalTypeFlags),
57    /// The Rust value of a class object could not be borrowed.
58    #[error(transparent)]
59    Borrow(#[from] crate::types::BorrowError),
60    /// The function called was called in an invalid scope (calling
61    /// class-related functions inside of a non-class bound function).
62    #[error("invalid scope")]
63    InvalidScope,
64    /// The pointer inside a given type was invalid, either null or pointing to
65    /// garbage.
66    #[error("invalid pointer")]
67    InvalidPointer,
68    /// A class declared two properties with the same name, for example a
69    /// `#[php(prop)]` field and a `#[php(getter)]` method.
70    #[error("property `{property}` is declared twice")]
71    DuplicateProperty {
72        /// `Class::$property` that was declared twice.
73        property: String,
74    },
75    /// A class or enum declared two methods whose names differ only by ASCII
76    /// case. PHP method names ignore case.
77    #[error("method `{method}` is declared twice")]
78    DuplicateMethod {
79        /// `Class::method` that was declared twice.
80        method: String,
81    },
82    /// A class declared two constants, or an enum two cases, with the same
83    /// name.
84    #[error("constant `{constant}` is declared twice")]
85    DuplicateConstant {
86        /// `Class::CONSTANT` that was declared twice.
87        constant: String,
88    },
89    /// A module declared two functions whose names differ only by ASCII case.
90    #[error("function `{function}` is declared twice")]
91    DuplicateFunction {
92        /// Name of the function that was declared twice.
93        function: String,
94    },
95    /// A class, interface or enum with this name, ignoring ASCII case, is
96    /// already registered with the engine.
97    #[error("class `{class}` is already registered")]
98    DuplicateClass {
99        /// Name of the class that was registered twice.
100        class: String,
101    },
102    /// The given property name does not exist.
103    #[error("property `{property}` does not exist on the object")]
104    InvalidProperty {
105        /// Name of the property that was looked up.
106        property: String,
107    },
108    /// A union type PHP cannot declare: a member that is not a scalar type or
109    /// `null`, or a union without a type to join (an untyped argument, a
110    /// return type never set).
111    #[error("invalid union type: {0}")]
112    InvalidUnionType(String),
113    /// A typed property was declared without a type, or with one a property
114    /// cannot have (`void`, `callable`, ...).
115    #[error("property `{property}` has no type a property can be declared with")]
116    InvalidPropertyType {
117        /// Name of the property.
118        property: String,
119    },
120    /// The enum has no case matching the given name or discriminant.
121    #[error("enum has no case matching `{case}`")]
122    InvalidEnumCase {
123        /// Name or discriminant that was looked up.
124        case: String,
125    },
126    /// The string could not be converted into a C-string due to the presence of
127    /// a NUL character.
128    #[error("string contains a NUL byte at position {position}")]
129    InvalidCString {
130        /// Byte offset of the first NUL character.
131        position: usize,
132    },
133    /// The string could not be converted into a valid Utf8 string
134    #[error("invalid UTF-8 byte sequence")]
135    InvalidUtf8,
136    /// Could not call the given function.
137    #[error("could not call the given function")]
138    Callable,
139    /// An object was expected.
140    #[error("an object was expected")]
141    Object,
142    /// The object's class does not implement `__toString()`, so it cannot be
143    /// converted into a string.
144    ///
145    /// The enum carries the name of the class.
146    #[error("{0} does not implement __toString()")]
147    NotStringable(String),
148    /// An invalid exception type was thrown.
149    #[error("invalid exception type was thrown: {0:?}")]
150    InvalidException(ClassFlags),
151    /// Converting integer arguments resulted in an overflow.
152    #[error("converting integer arguments resulted in an overflow")]
153    IntegerOverflow,
154    /// The engine did not run a [`try_catch`] closure to completion.
155    ///
156    /// [`try_catch`]: crate::zend::try_catch
157    #[error("try_catch did not run the closure to completion")]
158    Catch(#[from] CatchError),
159    /// A PHP exception is pending in the executor globals.
160    ///
161    /// The exception is left where the engine put it, so it propagates on its
162    /// own once control returns to PHP. Take ownership of it with
163    /// [`ExecutorGlobals::take_exception`] to handle it from Rust.
164    ///
165    /// The enum carries the class name of the pending exception.
166    #[error("a PHP exception of class {class} is pending")]
167    ExceptionPending {
168        /// Class name of the pending exception.
169        class: String,
170    },
171    /// A failure occurred while registering the stream wrapper
172    #[error("a failure occurred while registering the stream wrapper")]
173    StreamWrapperRegistrationFailure,
174    /// A failure occurred while unregistering the stream wrapper
175    #[error("a failure occurred while unregistering the stream wrapper")]
176    StreamWrapperUnregistrationFailure,
177    /// The SAPI write function is not available
178    #[error("the SAPI write function is not available")]
179    SapiWriteUnavailable,
180    /// The engine refused to start an output handler: no request is active,
181    /// or a registered conflict check rejected the handler name.
182    #[error("the engine refused to start the output handler")]
183    OutputHandlerStartFailed,
184    /// The engine refused to change the response headers: no request is
185    /// active, a `SapiGlobals` guard is alive, or the header is invalid or
186    /// comes after the headers were sent.
187    #[error("the engine refused to change the response headers")]
188    ResponseHeaderFailed,
189    /// A module loaded with `dl()` has a `sapi_activate_function`. PHP unloads
190    /// such a module at the end of the request, while the SAPI keeps the hook.
191    #[error("a module loaded with dl() cannot have a sapi_activate_function")]
192    SapiActivateUnderDl,
193    /// Failed to make an object lazy (PHP 8.4+)
194    #[error("failed to make the object lazy")]
195    LazyObjectFailed,
196    /// The engine failed to load an auto-global.
197    ///
198    /// The enum carries the name of the auto-global.
199    #[error("the engine failed to load the `{0}` auto-global")]
200    AutoGlobalLoadFailed(&'static str),
201}
202
203impl Error {
204    /// Builds an [`Error::ExceptionPending`] from the exception the engine is
205    /// currently holding, leaving the exception where it is.
206    ///
207    /// Returns [`None`] when no exception is pending.
208    pub(crate) fn pending_exception() -> Option<Self> {
209        ExecutorGlobals::pending_exception_class().map(|class| Self::ExceptionPending { class })
210    }
211}
212
213impl From<TryFromIntError> for Error {
214    fn from(_: TryFromIntError) -> Self {
215        Self::IntegerOverflow
216    }
217}
218
219impl From<NulError> for Error {
220    fn from(value: NulError) -> Self {
221        Self::InvalidCString {
222            position: value.nul_position(),
223        }
224    }
225}
226
227impl From<Error> for PhpException {
228    fn from(err: Error) -> Self {
229        match err {
230            Error::Borrow(err) => err.into(),
231            err => Self::from_message(err.to_string()),
232        }
233    }
234}
235
236/// Trigger an error that is reported in PHP the same way `trigger_error()` is.
237///
238/// See specific error type descriptions at <https://www.php.net/manual/en/errorfunc.constants.php>.
239///
240/// Does nothing if `message` contains a NUL byte, or if the error type bits do not
241/// fit in a C `int`.
242pub fn php_error(type_: &ErrorType, message: &str) {
243    let Ok(c_string) = CString::new(message) else {
244        return;
245    };
246    let Ok(bits) = c_int::try_from(type_.bits()) else {
247        return;
248    };
249
250    // SAFETY: `php_error_docref` is declared `PHP_ATTRIBUTE_FORMAT(printf, 3, 4)`, so
251    // `message` must be passed as a `%s` argument and never as the format itself,
252    // which would interpret `%` sequences in it as varargs directives. Both pointers
253    // are NUL-terminated and outlive the call.
254    unsafe {
255        php_error_docref(std::ptr::null(), bits, c"%s".as_ptr(), c_string.as_ptr());
256    }
257}
258
259#[cfg(test)]
260mod tests {
261    use std::error::Error as _;
262
263    use super::*;
264
265    #[test]
266    fn exception_pending_names_the_class() {
267        let err = Error::ExceptionPending {
268            class: "RuntimeException".into(),
269        };
270
271        assert_eq!(
272            err.to_string(),
273            "a PHP exception of class RuntimeException is pending"
274        );
275    }
276
277    #[test]
278    fn catch_error_is_chained_as_a_source() {
279        let err: Error = CatchError::Bailout.into();
280
281        assert_eq!(
282            err.to_string(),
283            "try_catch did not run the closure to completion"
284        );
285        assert_eq!(
286            err.source().map(ToString::to_string),
287            Some("the engine bailed out".to_string())
288        );
289    }
290
291    #[test]
292    fn invalid_cstring_reports_the_nul_position() {
293        let err: Error = CString::new("a\0b")
294            .expect_err("the string has a NUL")
295            .into();
296
297        assert_eq!(err.to_string(), "string contains a NUL byte at position 1");
298    }
299
300    #[test]
301    fn invalid_property_names_the_property() {
302        let err = Error::InvalidProperty {
303            property: "age".into(),
304        };
305
306        assert_eq!(
307            err.to_string(),
308            "property `age` does not exist on the object"
309        );
310    }
311
312    #[test]
313    fn messages_are_lowercase_fragments() {
314        assert_eq!(Error::InvalidScope.to_string(), "invalid scope");
315    }
316}