Skip to main content

ext_php_rs/
args.rs

1//! Builder and objects relating to function and method arguments.
2
3use std::{ffi::CString, ptr};
4
5use crate::{
6    convert::{FromZvalMut, IntoZvalDyn},
7    describe::{Parameter, abi},
8    error::{Error, Result},
9    ffi::{zend_internal_arg_info, zend_wrong_parameters_count_error},
10    flags::DataType,
11    types::Zval,
12    zend::ZendType,
13};
14
15/// Argument info tables of a class's or enum's methods, one per method.
16///
17/// The Zend engine borrows these for the life of the process, so they must be
18/// parked in something that lives that long.
19pub type ArgInfoTables = Box<[Box<[ArgInfo]>]>;
20
21/// Represents an argument to a function.
22#[must_use]
23#[derive(Debug)]
24#[allow(clippy::struct_excessive_bools)]
25pub struct Arg<'a> {
26    name: String,
27    r#type: DataType,
28    as_ref: bool,
29    allow_null: bool,
30    pub(crate) variadic: bool,
31    pub(crate) sensitive: bool,
32    default_value: Option<String>,
33    zval: Option<&'a mut Zval>,
34    variadic_zvals: Vec<Option<&'a mut Zval>>,
35}
36
37impl<'a> Arg<'a> {
38    /// Creates a new argument.
39    ///
40    /// # Parameters
41    ///
42    /// * `name` - The name of the parameter.
43    /// * `_type` - The type of the parameter.
44    pub fn new<T: Into<String>>(name: T, r#type: DataType) -> Self {
45        Arg {
46            name: name.into(),
47            r#type,
48            as_ref: false,
49            allow_null: false,
50            variadic: false,
51            sensitive: false,
52            default_value: None,
53            zval: None,
54            variadic_zvals: vec![],
55        }
56    }
57
58    /// Creates an argument whose type, nullability and pass-by-reference
59    /// flag come from the Rust type it is extracted into.
60    ///
61    /// # Parameters
62    ///
63    /// * `name` - The name of the parameter.
64    pub fn of<T: FromZvalMut<'a>>(name: impl Into<String>) -> Self {
65        Arg {
66            name: name.into(),
67            r#type: T::TYPE,
68            as_ref: T::BY_REF,
69            allow_null: T::NULLABLE,
70            variadic: false,
71            sensitive: false,
72            default_value: None,
73            zval: None,
74            variadic_zvals: vec![],
75        }
76    }
77
78    /// Sets the argument as a reference.
79    #[allow(clippy::wrong_self_convention)]
80    pub fn as_ref(mut self) -> Self {
81        self.as_ref = true;
82        self
83    }
84
85    /// Sets the argument as variadic.
86    pub fn is_variadic(mut self) -> Self {
87        self.variadic = true;
88        self
89    }
90
91    /// Marks the argument `#[\SensitiveParameter]`: exception traces show a
92    /// `SensitiveParameterValue` in its place instead of the value. It has no
93    /// effect before PHP 8.2, which introduced the attribute.
94    pub fn sensitive(mut self) -> Self {
95        self.sensitive = true;
96        self
97    }
98
99    /// Sets the argument as nullable.
100    pub fn allow_null(mut self) -> Self {
101        self.allow_null = true;
102        self
103    }
104
105    /// Sets the default value for the argument.
106    pub fn default<T: Into<String>>(mut self, default: T) -> Self {
107        self.default_value = Some(default.into());
108        self
109    }
110
111    /// Attempts to consume the argument, converting the inner type into `T`.
112    /// Upon success, the result is returned in a [`Result`].
113    ///
114    /// As this function consumes, it cannot return a reference to the
115    /// underlying zval.
116    ///
117    /// # Errors
118    ///
119    /// If the conversion fails (or the argument contains no value), the
120    /// argument is returned in an [`Err`] variant.
121    pub fn consume<T>(mut self) -> Result<T, Self>
122    where
123        for<'b> T: FromZvalMut<'b>,
124    {
125        self.zval
126            .as_mut()
127            .and_then(|zv| T::from_zval_mut(zv.dereference_mut()))
128            .ok_or(self)
129    }
130
131    /// Attempts to retrieve the value of the argument.
132    /// This will be None until the [`ArgParser`] is used to parse
133    /// the arguments.
134    pub fn val<T>(&'a mut self) -> Option<T>
135    where
136        T: FromZvalMut<'a>,
137    {
138        self.zval
139            .as_mut()
140            .and_then(|zv| T::from_zval_mut(zv.dereference_mut()))
141    }
142
143    /// Gets all the variadic values for this Rust argument. The result does not
144    /// contain a value that cannot be converted into `T`.
145    /// [`try_variadic_vals`](Self::try_variadic_vals) rejects it.
146    pub fn variadic_vals<T>(&'a mut self) -> Vec<T>
147    where
148        T: FromZvalMut<'a>,
149    {
150        self.variadic_zvals
151            .iter_mut()
152            .filter_map(|zv| zv.as_mut())
153            .filter_map(|zv| T::from_zval_mut(zv.dereference_mut()))
154            .collect()
155    }
156
157    /// Gets all the variadic values for this Rust argument. Returns `None` if
158    /// one of the values cannot be converted into `T`.
159    pub fn try_variadic_vals<T>(&'a mut self) -> Option<Vec<T>>
160    where
161        T: FromZvalMut<'a>,
162    {
163        self.variadic_zvals
164            .iter_mut()
165            .filter_map(|zv| zv.as_mut())
166            .map(|zv| T::from_zval_mut(zv.dereference_mut()))
167            .collect()
168    }
169
170    /// Attempts to return a reference to the arguments internal Zval.
171    ///
172    /// # Returns
173    ///
174    /// * `Some(&Zval)` - The internal zval.
175    /// * `None` - The argument was empty.
176    // TODO: Figure out if we can change this
177    #[allow(clippy::mut_mut)]
178    pub fn zval(&mut self) -> Option<&mut &'a mut Zval> {
179        self.zval.as_mut()
180    }
181
182    /// Attempts to call the argument as a callable with a list of arguments to
183    /// pass to the function. Note that a thrown exception inside the
184    /// callable is not detectable, therefore you should check if the return
185    /// value is valid rather than unwrapping. Returns a result containing the
186    /// return value of the function, or an error.
187    ///
188    /// You should not call this function directly, rather through the
189    /// [`call_user_func`](crate::call_user_func) macro.
190    ///
191    /// # Parameters
192    ///
193    /// * `params` - A list of parameters to call the function with.
194    ///
195    /// # Errors
196    ///
197    /// * `Error::Callable` - The argument is not callable.
198    // TODO: Measure this
199    #[allow(clippy::inline_always)]
200    #[inline(always)]
201    pub fn try_call(&self, params: Vec<&dyn IntoZvalDyn>) -> Result<Zval> {
202        self.zval.as_ref().ok_or(Error::Callable)?.try_call(params)
203    }
204
205    /// Returns the internal PHP argument info.
206    ///
207    /// An optional nullable argument without an explicit default reports
208    /// `null` as its default, the same way PHP declares `?T $x = null`.
209    pub(crate) fn as_arg_info(&self, optional: bool) -> Result<ArgInfo> {
210        let default_value = match &self.default_value {
211            Some(val) => Some(val.as_str()),
212            None if optional && self.allow_null && !self.variadic => Some("null"),
213            None => None,
214        };
215        Ok(ArgInfo {
216            name: CString::new(self.name.as_str())?.into_raw(),
217            type_: ZendType::empty_from_type(
218                self.r#type,
219                self.as_ref,
220                self.variadic,
221                self.allow_null,
222            )
223            .ok_or(Error::ZvalConversion(self.r#type))?,
224            default_value: match default_value {
225                Some(val) => CString::new(val)?.into_raw(),
226                None => ptr::null(),
227            },
228        })
229    }
230}
231
232impl From<Arg<'_>> for Parameter {
233    fn from(val: Arg<'_>) -> Self {
234        Parameter {
235            name: val.name.into(),
236            ty: Some(val.r#type).into(),
237            nullable: val.allow_null,
238            variadic: val.variadic,
239            default: val.default_value.map(abi::RString::from).into(),
240        }
241    }
242}
243
244/// Internal argument information used by Zend.
245pub type ArgInfo = zend_internal_arg_info;
246
247/// Number of required parameters for a signature, given for every parameter
248/// whether it may be omitted (nullable or defaulted).
249///
250/// Follows the PHP rule: only the trailing run of omittable parameters is
251/// optional, an omittable parameter followed by a required one stays required.
252#[must_use]
253pub const fn required_count(omittable: &[bool]) -> usize {
254    let mut required = omittable.len();
255    while required > 0 && omittable[required - 1] {
256        required -= 1;
257    }
258    required
259}
260
261/// Parses the arguments of a function.
262#[must_use]
263pub struct ArgParser<'a, 'b> {
264    args: Vec<&'b mut Arg<'a>>,
265    min_num_args: Option<usize>,
266    arg_zvals: Vec<Option<&'a mut Zval>>,
267}
268
269impl<'a, 'b> ArgParser<'a, 'b> {
270    /// Builds a new function argument parser.
271    pub fn new(arg_zvals: Vec<Option<&'a mut Zval>>) -> Self {
272        ArgParser {
273            args: vec![],
274            min_num_args: None,
275            arg_zvals,
276        }
277    }
278
279    /// Adds a new argument to the parser.
280    ///
281    /// # Parameters
282    ///
283    /// * `arg` - The argument to add to the parser.
284    pub fn arg(mut self, arg: &'b mut Arg<'a>) -> Self {
285        self.args.push(arg);
286        self
287    }
288
289    /// Sets the next arguments to be added as not required.
290    pub fn not_required(mut self) -> Self {
291        self.min_num_args = Some(self.args.len());
292        self
293    }
294
295    /// Sets how many leading arguments are required, see [`required_count`].
296    pub fn required_args(mut self, count: usize) -> Self {
297        self.min_num_args = Some(count);
298        self
299    }
300
301    /// Uses the argument parser to parse the arguments contained in the given
302    /// `ExecuteData` object. Returns successfully if the arguments were
303    /// parsed.
304    ///
305    /// This function can only be safely called from within an exported PHP
306    /// function.
307    ///
308    /// # Parameters
309    ///
310    /// * `execute_data` - The execution data from the function.
311    ///
312    /// # Errors
313    ///
314    /// Returns an [`Error`] type if there were too many or too little arguments
315    /// passed to the function. The user has already been notified so you
316    /// should break execution after seeing an error type.
317    ///
318    /// Also returns an error if the number of min/max arguments exceeds
319    /// `u32::MAX`
320    pub fn parse(mut self) -> Result<()> {
321        let max_num_args = self.args.len();
322        let mut min_num_args = self.min_num_args.unwrap_or(max_num_args);
323        let num_args = self.arg_zvals.len();
324        let has_variadic = self.args.last().is_some_and(|arg| arg.variadic);
325        if has_variadic {
326            min_num_args = min_num_args.saturating_sub(1);
327        }
328
329        if num_args < min_num_args || (!has_variadic && num_args > max_num_args) {
330            // SAFETY: Exported C function is safe, return value is unused and parameters
331            // are copied.
332            unsafe {
333                zend_wrong_parameters_count_error(
334                    min_num_args.try_into()?,
335                    max_num_args.try_into()?,
336                );
337            };
338            return Err(Error::IncorrectArguments(num_args, min_num_args));
339        }
340
341        for (i, arg_zval) in self.arg_zvals.into_iter().enumerate() {
342            let arg = match self.args.get_mut(i) {
343                Some(arg) => Some(arg),
344                // Only select the last item if it's variadic
345                None => self.args.last_mut().filter(|arg| arg.variadic),
346            };
347            if let Some(arg) = arg {
348                if arg.variadic {
349                    arg.variadic_zvals.push(arg_zval);
350                } else {
351                    arg.zval = arg_zval;
352                }
353            }
354        }
355
356        Ok(())
357    }
358}
359
360#[cfg(test)]
361mod tests {
362    #![allow(clippy::unwrap_used)]
363    #[cfg(feature = "embed")]
364    use crate::embed::Embed;
365
366    use super::*;
367
368    #[test]
369    fn required_count_keeps_omittable_args_before_a_required_one() {
370        assert_eq!(required_count(&[]), 0);
371        assert_eq!(required_count(&[false, false]), 2);
372        assert_eq!(required_count(&[false, true]), 1);
373        assert_eq!(required_count(&[true, false, true, true]), 2);
374        assert_eq!(required_count(&[true, true]), 0);
375    }
376
377    #[test]
378    fn of_reads_metadata_from_the_type() {
379        let arg = Arg::of::<Option<i64>>("maybe");
380        assert_eq!(arg.r#type, DataType::Long);
381        assert!(arg.allow_null);
382        assert!(!arg.as_ref);
383        let arg = Arg::of::<&mut Zval>("target");
384        assert_eq!(arg.r#type, DataType::Mixed);
385        assert!(!arg.allow_null);
386        assert!(arg.as_ref);
387    }
388
389    fn default_of(arg: &Arg<'_>, optional: bool) -> Option<String> {
390        let info = arg.as_arg_info(optional).unwrap();
391        unsafe { drop(CString::from_raw(info.name.cast_mut())) };
392        if info.default_value.is_null() {
393            return None;
394        }
395        let default = unsafe { CString::from_raw(info.default_value.cast_mut()) };
396        Some(default.to_str().unwrap().to_string())
397    }
398
399    #[test]
400    fn optional_nullable_arg_reports_a_null_default() {
401        assert_eq!(
402            default_of(&Arg::of::<Option<i64>>("a"), true).as_deref(),
403            Some("null")
404        );
405        assert_eq!(default_of(&Arg::of::<Option<i64>>("a"), false), None);
406        assert_eq!(default_of(&Arg::of::<i64>("a"), true), None);
407        assert_eq!(
408            default_of(&Arg::of::<Option<i64>>("a").is_variadic(), true),
409            None
410        );
411        assert_eq!(
412            default_of(&Arg::of::<Option<i64>>("a").default("5"), true).as_deref(),
413            Some("5")
414        );
415    }
416
417    #[test]
418    fn test_new() {
419        let arg = Arg::new("test", DataType::Long);
420        assert_eq!(arg.name, "test");
421        assert_eq!(arg.r#type, DataType::Long);
422        assert!(!arg.as_ref);
423        assert!(!arg.allow_null);
424        assert!(!arg.variadic);
425        assert!(arg.default_value.is_none());
426        assert!(arg.zval.is_none());
427        assert!(arg.variadic_zvals.is_empty());
428    }
429
430    #[test]
431    fn test_as_ref() {
432        let arg = Arg::new("test", DataType::Long).as_ref();
433        assert!(arg.as_ref);
434    }
435
436    #[test]
437    fn test_is_variadic() {
438        let arg = Arg::new("test", DataType::Long).is_variadic();
439        assert!(arg.variadic);
440    }
441
442    #[test]
443    fn test_allow_null() {
444        let arg = Arg::new("test", DataType::Long).allow_null();
445        assert!(arg.allow_null);
446    }
447
448    #[test]
449    fn test_default() {
450        let arg = Arg::new("test", DataType::Long).default("default");
451        assert_eq!(arg.default_value, Some("default".to_string()));
452
453        // TODO: Validate type
454    }
455
456    #[test]
457    fn test_consume_no_value() {
458        let arg = Arg::new("test", DataType::Long);
459        let result: Result<i32, _> = arg.consume();
460        assert!(result.is_err());
461        assert_eq!(result.unwrap_err().name, "test");
462    }
463
464    #[test]
465    #[cfg(feature = "embed")]
466    fn test_consume() {
467        let mut arg = Arg::new("test", DataType::Long);
468        let mut zval = Zval::from(42);
469        arg.zval = Some(&mut zval);
470
471        let result: Result<i32, _> = arg.consume();
472        assert_eq!(result.unwrap(), 42);
473    }
474
475    #[test]
476    fn test_val_no_value() {
477        let mut arg = Arg::new("test", DataType::Long);
478        let result: Option<i32> = arg.val();
479        assert!(result.is_none());
480    }
481
482    #[test]
483    #[cfg(feature = "embed")]
484    fn test_val() {
485        let mut arg = Arg::new("test", DataType::Long);
486        let mut zval = Zval::from(42);
487        arg.zval = Some(&mut zval);
488
489        let result: Option<i32> = arg.val();
490        assert_eq!(result.unwrap(), 42);
491    }
492
493    #[test]
494    #[cfg(feature = "embed")]
495    fn test_variadic_vals() {
496        let mut arg = Arg::new("test", DataType::Long).is_variadic();
497        let mut zval1 = Zval::from(42);
498        let mut zval2 = Zval::from(43);
499        arg.variadic_zvals.push(Some(&mut zval1));
500        arg.variadic_zvals.push(Some(&mut zval2));
501
502        let result: Vec<i32> = arg.variadic_vals();
503        assert_eq!(result, vec![42, 43]);
504    }
505
506    #[test]
507    #[cfg(feature = "embed")]
508    fn try_variadic_vals_fails_when_a_value_does_not_convert() {
509        let mut arg = Arg::new("test", DataType::Long).is_variadic();
510        let mut long = Zval::from(42);
511        let mut double = Zval::from(1.5);
512        arg.variadic_zvals.push(Some(&mut long));
513        arg.variadic_zvals.push(Some(&mut double));
514
515        assert_eq!(arg.try_variadic_vals::<i64>(), None);
516    }
517
518    #[test]
519    fn test_zval_no_value() {
520        let mut arg = Arg::new("test", DataType::Long);
521        let result = arg.zval();
522        assert!(result.is_none());
523    }
524
525    #[test]
526    #[cfg(feature = "embed")]
527    fn test_zval() {
528        let mut arg = Arg::new("test", DataType::Long);
529        let mut zval = Zval::from(42);
530        arg.zval = Some(&mut zval);
531
532        let result = arg.zval();
533        assert!(result.is_some());
534        assert_eq!(result.unwrap().dereference_mut().long(), Some(42));
535    }
536
537    #[cfg(feature = "embed")]
538    #[test]
539    fn test_try_call_no_value() {
540        let arg = Arg::new("test", DataType::Long);
541        let result = arg.try_call(vec![]);
542        assert!(result.is_err());
543    }
544
545    #[test]
546    #[cfg(feature = "embed")]
547    fn test_try_call_not_callable() {
548        Embed::run(|| {
549            let mut arg = Arg::new("test", DataType::Long);
550            let mut zval = Zval::from(42);
551            arg.zval = Some(&mut zval);
552
553            let result = arg.try_call(vec![]);
554            assert!(result.is_err());
555        });
556    }
557
558    // TODO: Test the callable case
559
560    #[test]
561    #[cfg(feature = "embed")]
562    fn test_as_arg_info() {
563        let arg = Arg::new("test", DataType::Long);
564        let arg_info = arg.as_arg_info(false);
565        assert!(arg_info.is_ok());
566
567        let arg_info = arg_info.unwrap();
568        assert!(arg_info.default_value.is_null());
569
570        let r#type = arg_info.type_;
571        assert_eq!(r#type.type_mask, 16);
572
573        unsafe { drop(CString::from_raw(arg_info.name.cast_mut())) };
574    }
575
576    #[test]
577    #[cfg(feature = "embed")]
578    fn test_as_arg_info_with_default() {
579        let arg = Arg::new("test", DataType::Long).default("default");
580        let arg_info = arg.as_arg_info(false);
581        assert!(arg_info.is_ok());
582
583        let arg_info = arg_info.unwrap();
584        assert!(!arg_info.default_value.is_null());
585
586        let r#type = arg_info.type_;
587        assert_eq!(r#type.type_mask, 16);
588
589        unsafe {
590            drop(CString::from_raw(arg_info.name.cast_mut()));
591            drop(CString::from_raw(arg_info.default_value.cast_mut()));
592        }
593    }
594
595    #[test]
596    fn test_param_from_arg() {
597        let arg = Arg::new("test", DataType::Long)
598            .default("default")
599            .allow_null();
600        let param: Parameter = arg.into();
601        assert_eq!(param.name, "test".into());
602        assert_eq!(param.ty, abi::Option::Some(DataType::Long));
603        assert!(param.nullable);
604        assert_eq!(param.default, abi::Option::Some("default".into()));
605    }
606
607    #[test]
608    fn test_arg_parser_new() {
609        let arg_zvals = vec![None, None];
610        let parser = ArgParser::new(arg_zvals);
611        assert_eq!(parser.arg_zvals.len(), 2);
612        assert!(parser.args.is_empty());
613        assert!(parser.min_num_args.is_none());
614    }
615
616    #[test]
617    fn test_arg_parser_arg() {
618        let arg_zvals = vec![None, None];
619        let mut parser = ArgParser::new(arg_zvals);
620        let mut arg = Arg::new("test", DataType::Long);
621        parser = parser.arg(&mut arg);
622        assert_eq!(parser.args.len(), 1);
623        assert_eq!(parser.args[0].name, "test");
624        assert_eq!(parser.args[0].r#type, DataType::Long);
625    }
626
627    // TODO: test parse
628}