1use 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
15pub type ArgInfoTables = Box<[Box<[ArgInfo]>]>;
20
21#[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 untyped: bool,
34 #[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 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 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 pub fn untyped<T: Into<String>>(name: T) -> Self {
106 Self {
107 untyped: true,
108 ..Self::new(name, DataType::Mixed)
109 }
110 }
111
112 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 #[allow(clippy::wrong_self_convention)]
133 pub fn as_ref(mut self) -> Self {
134 self.as_ref = true;
135 self
136 }
137
138 pub fn is_variadic(mut self) -> Self {
140 self.variadic = true;
141 self
142 }
143
144 pub fn sensitive(mut self) -> Self {
148 self.sensitive = true;
149 self
150 }
151
152 pub fn allow_null(mut self) -> Self {
154 self.allow_null = true;
155 self
156 }
157
158 pub fn default<T: Into<String>>(mut self, default: T) -> Self {
160 self.default_value = Some(default.into());
161 self
162 }
163
164 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 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 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 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 #[allow(clippy::mut_mut)]
235 pub fn zval(&mut self) -> Option<&mut &'a mut Zval> {
236 self.zval.as_mut()
237 }
238
239 #[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 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
311pub type ArgInfo = zend_internal_arg_info;
313
314#[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#[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 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 pub fn arg(mut self, arg: &'b mut Arg<'a>) -> Self {
352 self.args.push(arg);
353 self
354 }
355
356 pub fn not_required(mut self) -> Self {
358 self.min_num_args = Some(self.args.len());
359 self
360 }
361
362 pub fn required_args(mut self, count: usize) -> Self {
364 self.min_num_args = Some(count);
365 self
366 }
367
368 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 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 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 }
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 #[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 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 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 }