ext_php_rs/builders/function.rs
1use crate::{
2 args::{Arg, ArgInfo},
3 describe::DocComments,
4 error::{Error, Result},
5 flags::{DataType, MethodFlags},
6 types::Zval,
7 zend::{ExecuteData, FunctionEntry, ZendType},
8};
9use std::{ffi::CString, mem, ptr};
10
11/// Function representation in Rust.
12#[cfg(not(windows))]
13pub type FunctionHandler = extern "C" fn(execute_data: &mut ExecuteData, retval: &mut Zval);
14#[cfg(windows)]
15pub type FunctionHandler =
16 extern "vectorcall" fn(execute_data: &mut ExecuteData, retval: &mut Zval);
17
18/// Function representation in Rust using pointers.
19#[cfg(not(windows))]
20type FunctionPointerHandler = extern "C" fn(execute_data: *mut ExecuteData, retval: *mut Zval);
21#[cfg(windows)]
22type FunctionPointerHandler =
23 extern "vectorcall" fn(execute_data: *mut ExecuteData, retval: *mut Zval);
24
25/// Builder for registering a function in PHP.
26#[must_use]
27#[derive(Debug)]
28pub struct FunctionBuilder<'a> {
29 pub(crate) name: String,
30 function: FunctionEntry,
31 pub(crate) args: Vec<Arg<'a>>,
32 n_req: Option<usize>,
33 pub(crate) retval: Option<DataType>,
34 ret_as_ref: bool,
35 pub(crate) ret_as_null: bool,
36 pub(crate) docs: DocComments,
37}
38
39impl<'a> FunctionBuilder<'a> {
40 /// Creates a new function builder, used to build functions
41 /// to be exported to PHP.
42 ///
43 /// # Parameters
44 ///
45 /// * `name` - The name of the function.
46 /// * `handler` - The handler to be called when the function is invoked from
47 /// PHP.
48 pub fn new<T: Into<String>>(name: T, handler: FunctionHandler) -> Self {
49 Self {
50 name: name.into(),
51 function: FunctionEntry {
52 fname: ptr::null(),
53 // SAFETY: `*mut T` and `&mut T` have the same ABI as long as `*mut T` is non-null,
54 // aligned and pointing to a `T`. PHP guarantees that these conditions will be met.
55 handler: Some(unsafe {
56 mem::transmute::<FunctionHandler, FunctionPointerHandler>(handler)
57 }),
58 arg_info: ptr::null(),
59 num_args: 0,
60 flags: 0, // TBD?
61 #[cfg(php84)]
62 doc_comment: ptr::null(),
63 #[cfg(php84)]
64 frameless_function_infos: ptr::null(),
65 },
66 args: vec![],
67 n_req: None,
68 retval: None,
69 ret_as_ref: false,
70 ret_as_null: false,
71 docs: &[],
72 }
73 }
74
75 /// Create a new function builder for an abstract function that can be used
76 /// on an abstract class or an interface.
77 ///
78 /// # Parameters
79 ///
80 /// * `name` - The name of the function.
81 pub fn new_abstract<T: Into<String>>(name: T) -> Self {
82 let mut function = FunctionEntry::end();
83 function.add_flags(MethodFlags::Abstract);
84 Self {
85 name: name.into(),
86 function,
87 args: vec![],
88 n_req: None,
89 retval: None,
90 ret_as_ref: false,
91 ret_as_null: false,
92 docs: &[],
93 }
94 }
95
96 /// Creates a constructor builder, used to build the constructor
97 /// for classes.
98 ///
99 /// # Parameters
100 ///
101 /// * `handler` - The handler to be called when the function is invoked from
102 /// PHP.
103 pub fn constructor(handler: FunctionHandler) -> Self {
104 Self::new("__construct", handler)
105 }
106
107 /// Adds an argument to the function.
108 ///
109 /// # Parameters
110 ///
111 /// * `arg` - The argument to add to the function.
112 pub fn arg(mut self, arg: Arg<'a>) -> Self {
113 self.args.push(arg);
114 self
115 }
116
117 /// Sets the rest of the given arguments as not required.
118 pub fn not_required(mut self) -> Self {
119 self.n_req = Some(self.args.len());
120 self
121 }
122
123 /// Sets how many leading arguments are required, see
124 /// [`required_count`](crate::args::required_count).
125 pub fn required_args(mut self, count: usize) -> Self {
126 self.n_req = Some(count);
127 self
128 }
129
130 /// Sets the return value of the function.
131 ///
132 /// # Parameters
133 ///
134 /// * `type_` - The return type of the function.
135 /// * `as_ref` - Whether the function returns a reference.
136 /// * `allow_null` - Whether the function return value is nullable.
137 pub fn returns(mut self, type_: DataType, as_ref: bool, allow_null: bool) -> Self {
138 self.retval = Some(type_);
139 self.ret_as_ref = as_ref;
140 self.ret_as_null = allow_null && type_ != DataType::Void && type_ != DataType::Mixed;
141 self
142 }
143
144 /// Sets the documentation for the function.
145 /// This is used to generate the PHP stubs for the function.
146 ///
147 /// # Parameters
148 ///
149 /// * `docs` - The documentation for the function.
150 pub fn docs(mut self, docs: DocComments) -> Self {
151 self.docs = docs;
152 self
153 }
154
155 /// Builds the function converting it into a Zend function entry.
156 ///
157 /// Returns a result containing the function entry if successful.
158 ///
159 /// # Errors
160 ///
161 /// * `Error::InvalidCString` - If the function name is not a valid C
162 /// string.
163 /// * `Error::IntegerOverflow` - If the number of arguments is too large.
164 /// * If arg info for an argument could not be created.
165 /// * If the function name contains NUL bytes.
166 ///
167 /// # Ownership
168 ///
169 /// The returned `Box<[ArgInfo]>` is what `FunctionEntry::arg_info` points at.
170 /// The Zend engine borrows it for the life of the process, so the caller must
171 /// park it somewhere that lives that long — see `ClassMetadata::arg_info` and
172 /// `StaticModuleEntry`. Dropping it dangles the registered function.
173 pub fn build(mut self) -> Result<(FunctionEntry, Box<[ArgInfo]>)> {
174 let mut args = Vec::with_capacity(self.args.len() + 1);
175 let mut n_req = self.n_req.unwrap_or(self.args.len());
176 let variadic = self.args.last().is_some_and(|arg| arg.variadic);
177
178 if variadic {
179 self.function.add_flags(MethodFlags::Variadic);
180 n_req = n_req.saturating_sub(1);
181 }
182
183 // argument header, retval etc
184 // The first argument is used as `zend_internal_function_info` for the function.
185 // That struct shares the same memory as `zend_internal_arg_info` which is used
186 // for the arguments.
187 args.push(ArgInfo {
188 // required_num_args
189 name: n_req as *const _,
190 type_: match self.retval {
191 Some(retval) => {
192 ZendType::empty_from_type(retval, self.ret_as_ref, false, self.ret_as_null)
193 .ok_or(Error::ZvalConversion(retval))?
194 }
195 None => ZendType::empty(false, false),
196 },
197 default_value: ptr::null(),
198 });
199
200 // arguments
201 args.extend(
202 self.args
203 .iter()
204 .enumerate()
205 .map(|(i, arg)| arg.as_arg_info(i >= n_req))
206 .collect::<Result<Vec<_>>>()?,
207 );
208
209 self.function.fname = CString::new(self.name)?.into_raw();
210 self.function.num_args = (args.len() - 1).try_into()?;
211
212 let args = args.into_boxed_slice();
213 self.function.arg_info = args.as_ptr();
214
215 Ok((self.function, args))
216 }
217}
218
219/// Frees a [`FunctionEntry`] table once the Zend engine has consumed it.
220///
221/// `zend_register_functions` interns every `fname`, and
222/// `do_register_internal_class` reads `zend_class_entry.info.internal.builtin_functions`
223/// exactly once and never frees it, so a class or enum method table is dead as
224/// soon as registration returns.
225///
226/// The `arg_info` arrays are deliberately left alone. The engine's copy of them
227/// is shallow, so `arg_info[i].name` and `.default_value` stay live for
228/// `ReflectionParameter`, and a function with no parameters and no return type
229/// keeps the array itself. They are owned by `ClassMetadata` or
230/// [`ModuleAllocations`](crate::zend::ModuleAllocations) instead.
231///
232/// # Safety
233///
234/// * `entries` must come from `Box::into_raw` on a NUL-terminated
235/// `Box<[FunctionEntry]>` whose entries were built by
236/// [`FunctionBuilder::build`].
237/// * Must be called exactly once, after the `zend_register_*` call that
238/// consumed the table.
239/// * Must never be called on a [`ModuleEntry::functions`] table: PHP re-reads
240/// that one from `module_destructor` after MSHUTDOWN and from
241/// `get_extension_funcs()` during a request.
242///
243/// [`ModuleEntry::functions`]: crate::zend::ModuleEntry
244pub(crate) unsafe fn free_registered_entries(entries: *mut [FunctionEntry]) {
245 let entries = unsafe { Box::from_raw(entries) };
246 for entry in &*entries {
247 if !entry.fname.is_null() {
248 drop(unsafe { CString::from_raw(entry.fname.cast_mut()) });
249 }
250 }
251}