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    /// Declared without a type, see [`Arg::untyped`].
33    untyped: bool,
34    /// The other members of a union type, see [`Arg::or`].
35    #[expect(
36        clippy::box_collection,
37        reason = "`Arg` travels in `Result::Err` (`consume`): a thin pointer keeps it under `result_large_err`"
38    )]
39    union: Option<Box<Vec<DataType>>>,
40    default_value: Option<String>,
41    zval: Option<&'a mut Zval>,
42    variadic_zvals: Vec<Option<&'a mut Zval>>,
43}
44
45impl<'a> Arg<'a> {
46    /// Creates a new argument.
47    ///
48    /// # Parameters
49    ///
50    /// * `name` - The name of the parameter.
51    /// * `_type` - The type of the parameter.
52    pub fn new<T: Into<String>>(name: T, r#type: DataType) -> Self {
53        Arg {
54            name: name.into(),
55            r#type,
56            untyped: false,
57            union: None,
58            as_ref: false,
59            allow_null: false,
60            variadic: false,
61            sensitive: false,
62            default_value: None,
63            zval: None,
64            variadic_zvals: vec![],
65        }
66    }
67
68    /// Creates an argument whose type, nullability and pass-by-reference
69    /// flag come from the Rust type it is extracted into.
70    ///
71    /// # Parameters
72    ///
73    /// * `name` - The name of the parameter.
74    pub fn of<T: FromZvalMut<'a>>(name: impl Into<String>) -> Self {
75        Self::typed(name, T::TYPE, T::NULLABLE, T::BY_REF)
76    }
77
78    pub(crate) fn typed(
79        name: impl Into<String>,
80        r#type: DataType,
81        allow_null: bool,
82        as_ref: bool,
83    ) -> Self {
84        Arg {
85            name: name.into(),
86            r#type,
87            as_ref,
88            allow_null,
89            variadic: false,
90            sensitive: false,
91            untyped: false,
92            union: None,
93            default_value: None,
94            zval: None,
95            variadic_zvals: vec![],
96        }
97    }
98
99    /// Creates an argument declared without a type, as PHP declares
100    /// `function f($value)`: reflection reports no type, and a method that
101    /// overrides it may declare its parameter with any type or none.
102    ///
103    /// The Rust side still converts the value as its own type, usually
104    /// `&Zval`.
105    pub fn untyped<T: Into<String>>(name: T) -> Self {
106        Self {
107            untyped: true,
108            ..Self::new(name, DataType::Mixed)
109        }
110    }
111
112    /// Adds `r#type` to the argument's type, making it a union:
113    /// `Arg::new("value", DataType::Long).or(DataType::Double)` declares
114    /// `int|float $value`.
115    ///
116    /// The argument's type and every member are `bool`, `int`, `float`,
117    /// `string`, `array` or `object`, and a member can also be `null`. Any
118    /// other type (a class, `iterable`, `resource`, `mixed`, ...), or a union
119    /// on an [`Arg::untyped`] argument, fails
120    /// [`FunctionBuilder::build`](crate::builders::FunctionBuilder::build) with
121    /// [`Error::InvalidUnionType`].
122    ///
123    /// The type is what reflection and PHP's inheritance checks see: release
124    /// builds of PHP do not check an internal function's arguments against
125    /// it, so the handler receives what the caller passed and must check it.
126    pub fn or(mut self, r#type: DataType) -> Self {
127        self.union.get_or_insert_with(Box::default).push(r#type);
128        self
129    }
130
131    /// Sets the argument as a reference.
132    #[allow(clippy::wrong_self_convention)]
133    pub fn as_ref(mut self) -> Self {
134        self.as_ref = true;
135        self
136    }
137
138    /// Sets the argument as variadic.
139    pub fn is_variadic(mut self) -> Self {
140        self.variadic = true;
141        self
142    }
143
144    /// Marks the argument `#[\SensitiveParameter]`: exception traces show a
145    /// `SensitiveParameterValue` in its place instead of the value. It has no
146    /// effect before PHP 8.2, which introduced the attribute.
147    pub fn sensitive(mut self) -> Self {
148        self.sensitive = true;
149        self
150    }
151
152    /// Sets the argument as nullable.
153    pub fn allow_null(mut self) -> Self {
154        self.allow_null = true;
155        self
156    }
157
158    /// Sets the default value for the argument.
159    pub fn default<T: Into<String>>(mut self, default: T) -> Self {
160        self.default_value = Some(default.into());
161        self
162    }
163
164    /// Attempts to consume the argument, converting the inner type into `T`.
165    /// Upon success, the result is returned in a [`Result`].
166    ///
167    /// As this function consumes, it cannot return a reference to the
168    /// underlying zval.
169    ///
170    /// # Errors
171    ///
172    /// If the conversion fails (or the argument contains no value), the
173    /// argument is returned in an [`Err`] variant.
174    pub fn consume<T>(mut self) -> Result<T, Self>
175    where
176        for<'b> T: FromZvalMut<'b>,
177    {
178        self.zval
179            .as_mut()
180            .and_then(|zv| T::from_zval_mut(zv.dereference_mut()))
181            .ok_or(self)
182    }
183
184    /// Attempts to retrieve the value of the argument.
185    /// This will be None until the [`ArgParser`] is used to parse
186    /// the arguments.
187    pub fn val<T>(&'a mut self) -> Option<T>
188    where
189        T: FromZvalMut<'a>,
190    {
191        self.zval
192            .as_mut()
193            .and_then(|zv| T::from_zval_mut(zv.dereference_mut()))
194    }
195
196    /// Gets all the variadic values for this Rust argument. The result does not
197    /// contain a value that cannot be converted into `T`.
198    /// [`try_variadic_vals`](Self::try_variadic_vals) rejects it.
199    pub fn variadic_vals<T>(&'a mut self) -> Vec<T>
200    where
201        T: FromZvalMut<'a>,
202    {
203        self.variadic_zvals
204            .iter_mut()
205            .filter_map(|zv| zv.as_mut())
206            .filter_map(|zv| T::from_zval_mut(zv.dereference_mut()))
207            .collect()
208    }
209
210    /// Gets all the variadic values for this Rust argument.
211    ///
212    /// # Errors
213    ///
214    /// Returns the error of the first value that cannot be converted into `T`,
215    /// see [`FromZvalMut::try_from_zval_mut`].
216    pub fn try_variadic_vals<T>(&'a mut self) -> Result<Vec<T>>
217    where
218        T: FromZvalMut<'a>,
219    {
220        self.variadic_zvals
221            .iter_mut()
222            .filter_map(|zv| zv.as_mut())
223            .map(|zv| T::try_from_zval_mut(zv.dereference_mut()))
224            .collect()
225    }
226
227    /// Attempts to return a reference to the arguments internal Zval.
228    ///
229    /// # Returns
230    ///
231    /// * `Some(&Zval)` - The internal zval.
232    /// * `None` - The argument was empty.
233    // TODO: Figure out if we can change this
234    #[allow(clippy::mut_mut)]
235    pub fn zval(&mut self) -> Option<&mut &'a mut Zval> {
236        self.zval.as_mut()
237    }
238
239    /// Attempts to call the argument as a callable with a list of arguments to
240    /// pass to the function. Note that a thrown exception inside the
241    /// callable is not detectable, therefore you should check if the return
242    /// value is valid rather than unwrapping. Returns a result containing the
243    /// return value of the function, or an error.
244    ///
245    /// You should not call this function directly, rather through the
246    /// [`call_user_func`](crate::call_user_func) macro.
247    ///
248    /// # Parameters
249    ///
250    /// * `params` - A list of parameters to call the function with.
251    ///
252    /// # Errors
253    ///
254    /// * `Error::Callable` - The argument is not callable.
255    // TODO: Measure this
256    #[allow(clippy::inline_always)]
257    #[inline(always)]
258    pub fn try_call(&self, params: Vec<&dyn IntoZvalDyn>) -> Result<Zval> {
259        self.zval.as_ref().ok_or(Error::Callable)?.try_call(params)
260    }
261
262    /// Returns the internal PHP argument info.
263    ///
264    /// An optional nullable argument without an explicit default reports
265    /// `null` as its default, the same way PHP declares `?T $x = null`.
266    pub(crate) fn as_arg_info(&self, optional: bool) -> Result<ArgInfo> {
267        let default_value = match &self.default_value {
268            Some(val) => Some(val.as_str()),
269            None if optional && self.allow_null && !self.variadic => Some("null"),
270            None => None,
271        };
272        let union = self.union.as_deref().map_or(&[][..], Vec::as_slice);
273        let declaration = format!("parameter ${}", self.name);
274        let type_ = if self.untyped {
275            if !union.is_empty() {
276                return Err(Error::InvalidUnionType(format!(
277                    "{declaration}: an untyped parameter has no type to join"
278                )));
279            }
280            ZendType::empty(self.as_ref, self.variadic)
281        } else {
282            let mut type_ =
283                ZendType::empty_from_type(self.r#type, self.as_ref, self.variadic, self.allow_null)
284                    .ok_or(Error::ZvalConversion(self.r#type))?;
285            ZendType::add_union(&mut type_, &declaration, self.r#type, union)?;
286            type_
287        };
288        Ok(ArgInfo {
289            name: CString::new(self.name.as_str())?.into_raw(),
290            type_,
291            default_value: match default_value {
292                Some(val) => CString::new(val)?.into_raw(),
293                None => ptr::null(),
294            },
295        })
296    }
297}
298
299impl From<Arg<'_>> for Parameter {
300    fn from(val: Arg<'_>) -> Self {
301        Parameter {
302            name: val.name.into(),
303            ty: if val.untyped { None } else { Some(val.r#type) }.into(),
304            nullable: val.allow_null,
305            variadic: val.variadic,
306            default: val.default_value.map(abi::RString::from).into(),
307        }
308    }
309}
310
311/// Internal argument information used by Zend.
312pub type ArgInfo = zend_internal_arg_info;
313
314/// Number of required parameters for a signature, given for every parameter
315/// whether it may be omitted (nullable or defaulted).
316///
317/// Follows the PHP rule: only the trailing run of omittable parameters is
318/// optional, an omittable parameter followed by a required one stays required.
319#[must_use]
320pub const fn required_count(omittable: &[bool]) -> usize {
321    let mut required = omittable.len();
322    while required > 0 && omittable[required - 1] {
323        required -= 1;
324    }
325    required
326}
327
328/// Parses the arguments of a function.
329#[must_use]
330pub struct ArgParser<'a, 'b> {
331    args: Vec<&'b mut Arg<'a>>,
332    min_num_args: Option<usize>,
333    arg_zvals: Vec<Option<&'a mut Zval>>,
334}
335
336impl<'a, 'b> ArgParser<'a, 'b> {
337    /// Builds a new function argument parser.
338    pub fn new(arg_zvals: Vec<Option<&'a mut Zval>>) -> Self {
339        ArgParser {
340            args: vec![],
341            min_num_args: None,
342            arg_zvals,
343        }
344    }
345
346    /// Adds a new argument to the parser.
347    ///
348    /// # Parameters
349    ///
350    /// * `arg` - The argument to add to the parser.
351    pub fn arg(mut self, arg: &'b mut Arg<'a>) -> Self {
352        self.args.push(arg);
353        self
354    }
355
356    /// Sets the next arguments to be added as not required.
357    pub fn not_required(mut self) -> Self {
358        self.min_num_args = Some(self.args.len());
359        self
360    }
361
362    /// Sets how many leading arguments are required, see [`required_count`].
363    pub fn required_args(mut self, count: usize) -> Self {
364        self.min_num_args = Some(count);
365        self
366    }
367
368    /// Uses the argument parser to parse the arguments contained in the given
369    /// `ExecuteData` object. Returns successfully if the arguments were
370    /// parsed.
371    ///
372    /// This function can only be safely called from within an exported PHP
373    /// function.
374    ///
375    /// # Parameters
376    ///
377    /// * `execute_data` - The execution data from the function.
378    ///
379    /// # Errors
380    ///
381    /// Returns an [`Error`] type if there were too many or too little arguments
382    /// passed to the function. The user has already been notified so you
383    /// should break execution after seeing an error type.
384    ///
385    /// Also returns an error if the number of min/max arguments exceeds
386    /// `u32::MAX`
387    pub fn parse(mut self) -> Result<()> {
388        let max_num_args = self.args.len();
389        let mut min_num_args = self.min_num_args.unwrap_or(max_num_args);
390        let num_args = self.arg_zvals.len();
391        let has_variadic = self.args.last().is_some_and(|arg| arg.variadic);
392        if has_variadic {
393            min_num_args = min_num_args.saturating_sub(1);
394        }
395
396        if num_args < min_num_args || (!has_variadic && num_args > max_num_args) {
397            // SAFETY: Exported C function is safe, return value is unused and parameters
398            // are copied.
399            unsafe {
400                zend_wrong_parameters_count_error(
401                    min_num_args.try_into()?,
402                    max_num_args.try_into()?,
403                );
404            };
405            return Err(Error::IncorrectArguments(num_args, min_num_args));
406        }
407
408        for (i, arg_zval) in self.arg_zvals.into_iter().enumerate() {
409            let arg = match self.args.get_mut(i) {
410                Some(arg) => Some(arg),
411                // Only select the last item if it's variadic
412                None => self.args.last_mut().filter(|arg| arg.variadic),
413            };
414            if let Some(arg) = arg {
415                if arg.variadic {
416                    arg.variadic_zvals.push(arg_zval);
417                } else {
418                    arg.zval = arg_zval;
419                }
420            }
421        }
422
423        Ok(())
424    }
425}
426
427#[cfg(test)]
428mod tests {
429    #![allow(clippy::unwrap_used)]
430    #[cfg(feature = "embed")]
431    use crate::embed::Embed;
432
433    use super::*;
434
435    #[test]
436    fn required_count_keeps_omittable_args_before_a_required_one() {
437        assert_eq!(required_count(&[]), 0);
438        assert_eq!(required_count(&[false, false]), 2);
439        assert_eq!(required_count(&[false, true]), 1);
440        assert_eq!(required_count(&[true, false, true, true]), 2);
441        assert_eq!(required_count(&[true, true]), 0);
442    }
443
444    #[test]
445    fn of_reads_metadata_from_the_type() {
446        let arg = Arg::of::<Option<i64>>("maybe");
447        assert_eq!(arg.r#type, DataType::Long);
448        assert!(arg.allow_null);
449        assert!(!arg.as_ref);
450        let arg = Arg::of::<&mut Zval>("target");
451        assert_eq!(arg.r#type, DataType::Mixed);
452        assert!(!arg.allow_null);
453        assert!(arg.as_ref);
454    }
455
456    fn default_of(arg: &Arg<'_>, optional: bool) -> Option<String> {
457        let info = arg.as_arg_info(optional).unwrap();
458        unsafe { drop(CString::from_raw(info.name.cast_mut())) };
459        if info.default_value.is_null() {
460            return None;
461        }
462        let default = unsafe { CString::from_raw(info.default_value.cast_mut()) };
463        Some(default.to_str().unwrap().to_string())
464    }
465
466    #[test]
467    fn optional_nullable_arg_reports_a_null_default() {
468        assert_eq!(
469            default_of(&Arg::of::<Option<i64>>("a"), true).as_deref(),
470            Some("null")
471        );
472        assert_eq!(default_of(&Arg::of::<Option<i64>>("a"), false), None);
473        assert_eq!(default_of(&Arg::of::<i64>("a"), true), None);
474        assert_eq!(
475            default_of(&Arg::of::<Option<i64>>("a").is_variadic(), true),
476            None
477        );
478        assert_eq!(
479            default_of(&Arg::of::<Option<i64>>("a").default("5"), true).as_deref(),
480            Some("5")
481        );
482    }
483
484    #[test]
485    fn test_new() {
486        let arg = Arg::new("test", DataType::Long);
487        assert_eq!(arg.name, "test");
488        assert_eq!(arg.r#type, DataType::Long);
489        assert!(!arg.as_ref);
490        assert!(!arg.allow_null);
491        assert!(!arg.variadic);
492        assert!(arg.default_value.is_none());
493        assert!(arg.zval.is_none());
494        assert!(arg.variadic_zvals.is_empty());
495    }
496
497    #[test]
498    fn test_as_ref() {
499        let arg = Arg::new("test", DataType::Long).as_ref();
500        assert!(arg.as_ref);
501    }
502
503    #[test]
504    fn test_is_variadic() {
505        let arg = Arg::new("test", DataType::Long).is_variadic();
506        assert!(arg.variadic);
507    }
508
509    #[test]
510    fn test_allow_null() {
511        let arg = Arg::new("test", DataType::Long).allow_null();
512        assert!(arg.allow_null);
513    }
514
515    #[test]
516    fn test_default() {
517        let arg = Arg::new("test", DataType::Long).default("default");
518        assert_eq!(arg.default_value, Some("default".to_string()));
519
520        // TODO: Validate type
521    }
522
523    #[test]
524    fn test_consume_no_value() {
525        let arg = Arg::new("test", DataType::Long);
526        let result: Result<i32, _> = arg.consume();
527        assert!(result.is_err());
528        assert_eq!(result.unwrap_err().name, "test");
529    }
530
531    #[test]
532    #[cfg(feature = "embed")]
533    fn test_consume() {
534        let mut arg = Arg::new("test", DataType::Long);
535        let mut zval = Zval::from(42);
536        arg.zval = Some(&mut zval);
537
538        let result: Result<i32, _> = arg.consume();
539        assert_eq!(result.unwrap(), 42);
540    }
541
542    #[test]
543    fn test_val_no_value() {
544        let mut arg = Arg::new("test", DataType::Long);
545        let result: Option<i32> = arg.val();
546        assert!(result.is_none());
547    }
548
549    #[test]
550    #[cfg(feature = "embed")]
551    fn test_val() {
552        let mut arg = Arg::new("test", DataType::Long);
553        let mut zval = Zval::from(42);
554        arg.zval = Some(&mut zval);
555
556        let result: Option<i32> = arg.val();
557        assert_eq!(result.unwrap(), 42);
558    }
559
560    #[test]
561    #[cfg(feature = "embed")]
562    fn test_variadic_vals() {
563        let mut arg = Arg::new("test", DataType::Long).is_variadic();
564        let mut zval1 = Zval::from(42);
565        let mut zval2 = Zval::from(43);
566        arg.variadic_zvals.push(Some(&mut zval1));
567        arg.variadic_zvals.push(Some(&mut zval2));
568
569        let result: Vec<i32> = arg.variadic_vals();
570        assert_eq!(result, vec![42, 43]);
571    }
572
573    #[test]
574    #[cfg(feature = "embed")]
575    fn try_variadic_vals_fails_when_a_value_does_not_convert() {
576        let mut arg = Arg::new("test", DataType::Long).is_variadic();
577        let mut long = Zval::from(42);
578        let mut double = Zval::from(1.5);
579        arg.variadic_zvals.push(Some(&mut long));
580        arg.variadic_zvals.push(Some(&mut double));
581
582        assert!(matches!(
583            arg.try_variadic_vals::<i64>(),
584            Err(Error::ZvalConversion(DataType::Double))
585        ));
586    }
587
588    #[test]
589    fn test_zval_no_value() {
590        let mut arg = Arg::new("test", DataType::Long);
591        let result = arg.zval();
592        assert!(result.is_none());
593    }
594
595    #[test]
596    #[cfg(feature = "embed")]
597    fn test_zval() {
598        let mut arg = Arg::new("test", DataType::Long);
599        let mut zval = Zval::from(42);
600        arg.zval = Some(&mut zval);
601
602        let result = arg.zval();
603        assert!(result.is_some());
604        assert_eq!(result.unwrap().dereference_mut().long(), Some(42));
605    }
606
607    #[cfg(feature = "embed")]
608    #[test]
609    fn test_try_call_no_value() {
610        let arg = Arg::new("test", DataType::Long);
611        let result = arg.try_call(vec![]);
612        assert!(result.is_err());
613    }
614
615    #[test]
616    #[cfg(feature = "embed")]
617    fn test_try_call_not_callable() {
618        Embed::run(|| {
619            let mut arg = Arg::new("test", DataType::Long);
620            let mut zval = Zval::from(42);
621            arg.zval = Some(&mut zval);
622
623            let result = arg.try_call(vec![]);
624            assert!(result.is_err());
625        });
626    }
627
628    // TODO: Test the callable case
629
630    #[test]
631    fn untyped_arg_has_no_type_bits() {
632        let info = Arg::untyped("value").as_arg_info(false).unwrap();
633        assert_eq!(info.type_.type_mask, 0);
634        assert!(info.type_.ptr.is_null());
635        unsafe { drop(CString::from_raw(info.name.cast_mut())) };
636    }
637
638    #[test]
639    fn union_arg_ors_the_type_bits() {
640        use crate::ffi::{_ZEND_TYPE_NULLABLE_BIT, IS_DOUBLE, IS_LONG};
641
642        let info = Arg::new("value", DataType::Long)
643            .or(DataType::Double)
644            .as_arg_info(false)
645            .unwrap();
646        assert_eq!(info.type_.type_mask, (1 << IS_LONG) | (1 << IS_DOUBLE));
647        unsafe { drop(CString::from_raw(info.name.cast_mut())) };
648
649        let info = Arg::new("value", DataType::Long)
650            .or(DataType::Null)
651            .as_arg_info(false)
652            .unwrap();
653        assert_eq!(
654            info.type_.type_mask,
655            (1 << IS_LONG) | _ZEND_TYPE_NULLABLE_BIT
656        );
657        unsafe { drop(CString::from_raw(info.name.cast_mut())) };
658    }
659
660    #[test]
661    fn union_with_a_class_type_is_refused() {
662        let arg = Arg::new("value", DataType::Long).or(DataType::Object("Foo".into()));
663        assert!(matches!(
664            arg.as_arg_info(false),
665            Err(Error::InvalidUnionType(_))
666        ));
667    }
668
669    #[test]
670    fn union_members_cover_every_data_type() {
671        use crate::ffi::{
672            _ZEND_TYPE_NULLABLE_BIT, IS_ARRAY, IS_DOUBLE, IS_LONG, IS_OBJECT, IS_STRING,
673            MAY_BE_BOOL,
674        };
675
676        // Only the scalar types and `null` can join a union: `resource` and
677        // `undef` gave masks that crash `ReflectionType::__toString`,
678        // `reference` and `ptr` stray bits, `void` and `mixed` types PHP forbids
679        // in a union, and `iterable` a bit only arginfo of its own can carry.
680        let int = 1 << IS_LONG;
681        let cases = [
682            (DataType::Undef, None),
683            (DataType::Null, Some(int | _ZEND_TYPE_NULLABLE_BIT)),
684            (DataType::False, None),
685            (DataType::True, None),
686            (DataType::Long, Some(int)),
687            (DataType::Double, Some(int | (1 << IS_DOUBLE))),
688            (DataType::String, Some(int | (1 << IS_STRING))),
689            (DataType::Array, Some(int | (1 << IS_ARRAY))),
690            (DataType::Iterable, None),
691            (DataType::Object("".into()), Some(int | (1 << IS_OBJECT))),
692            (DataType::Object("Foo".into()), None),
693            (DataType::Resource, None),
694            (DataType::Reference, None),
695            (DataType::Callable, None),
696            (DataType::ConstantExpression, None),
697            (DataType::Indirect, None),
698            (DataType::Void, None),
699            (DataType::Mixed, None),
700            (DataType::Bool, Some(int | MAY_BE_BOOL)),
701            (DataType::Ptr, None),
702        ];
703        for (member, mask) in cases {
704            let info = Arg::new("value", DataType::Long)
705                .or(member)
706                .as_arg_info(false);
707            match (info, mask) {
708                (Ok(info), Some(mask)) => {
709                    assert_eq!(info.type_.type_mask, mask, "{member:?}");
710                    unsafe { drop(CString::from_raw(info.name.cast_mut())) };
711                }
712                (Err(Error::InvalidUnionType(_)), None) => {}
713                (info, mask) => panic!(
714                    "{member:?}: {:?} for {mask:?}",
715                    info.map(|i| i.type_.type_mask)
716                ),
717            }
718        }
719        // The first type is checked too.
720        let arg = Arg::new("value", DataType::Resource).or(DataType::Long);
721        assert!(matches!(
722            arg.as_arg_info(false),
723            Err(Error::InvalidUnionType(_))
724        ));
725    }
726
727    #[test]
728    fn untyped_arg_with_a_union_is_refused() {
729        let arg = Arg::untyped("value").or(DataType::Long);
730        assert!(matches!(
731            arg.as_arg_info(false),
732            Err(Error::InvalidUnionType(message)) if message.contains("$value")
733        ));
734    }
735
736    #[test]
737    #[cfg(feature = "embed")]
738    fn test_as_arg_info() {
739        let arg = Arg::new("test", DataType::Long);
740        let arg_info = arg.as_arg_info(false);
741        assert!(arg_info.is_ok());
742
743        let arg_info = arg_info.unwrap();
744        assert!(arg_info.default_value.is_null());
745
746        let r#type = arg_info.type_;
747        assert_eq!(r#type.type_mask, 16);
748
749        unsafe { drop(CString::from_raw(arg_info.name.cast_mut())) };
750    }
751
752    #[test]
753    #[cfg(feature = "embed")]
754    fn test_as_arg_info_with_default() {
755        let arg = Arg::new("test", DataType::Long).default("default");
756        let arg_info = arg.as_arg_info(false);
757        assert!(arg_info.is_ok());
758
759        let arg_info = arg_info.unwrap();
760        assert!(!arg_info.default_value.is_null());
761
762        let r#type = arg_info.type_;
763        assert_eq!(r#type.type_mask, 16);
764
765        unsafe {
766            drop(CString::from_raw(arg_info.name.cast_mut()));
767            drop(CString::from_raw(arg_info.default_value.cast_mut()));
768        }
769    }
770
771    #[test]
772    fn test_param_from_arg() {
773        let arg = Arg::new("test", DataType::Long)
774            .default("default")
775            .allow_null();
776        let param: Parameter = arg.into();
777        assert_eq!(param.name, "test".into());
778        assert_eq!(param.ty, abi::Option::Some(DataType::Long));
779        assert!(param.nullable);
780        assert_eq!(param.default, abi::Option::Some("default".into()));
781    }
782
783    #[test]
784    fn test_arg_parser_new() {
785        let arg_zvals = vec![None, None];
786        let parser = ArgParser::new(arg_zvals);
787        assert_eq!(parser.arg_zvals.len(), 2);
788        assert!(parser.args.is_empty());
789        assert!(parser.min_num_args.is_none());
790    }
791
792    #[test]
793    fn test_arg_parser_arg() {
794        let arg_zvals = vec![None, None];
795        let mut parser = ArgParser::new(arg_zvals);
796        let mut arg = Arg::new("test", DataType::Long);
797        parser = parser.arg(&mut arg);
798        assert_eq!(parser.args.len(), 1);
799        assert_eq!(parser.args[0].name, "test");
800        assert_eq!(parser.args[0].r#type, DataType::Long);
801    }
802
803    // TODO: test parse
804}