• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

extphprs / ext-php-rs / 21440531827

28 Jan 2026 01:41PM UTC coverage: 34.836% (-0.5%) from 35.363%
21440531827

Pull #621

github

web-flow
Merge e96b63a0b into 90b596ade
Pull Request #621: feat(interface): php_impl_interface macro

16 of 126 new or added lines in 8 files covered. (12.7%)

1 existing line in 1 file now uncovered.

1916 of 5500 relevant lines covered (34.84%)

13.91 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

19.84
/crates/macros/src/function.rs
1
use std::collections::HashMap;
2

3
use darling::{FromAttributes, ToTokens};
4
use proc_macro2::{Ident, Span, TokenStream};
5
use quote::{format_ident, quote, quote_spanned};
6
use syn::spanned::Spanned as _;
7
use syn::{Expr, FnArg, GenericArgument, ItemFn, PatType, PathArguments, Type, TypePath};
8

9
use crate::helpers::get_docs;
10
use crate::parsing::{
11
    PhpNameContext, PhpRename, RenameRule, Visibility, ident_to_php_name, validate_php_name,
12
};
13
use crate::prelude::*;
14
use crate::syn_ext::DropLifetimes;
15

16
/// Checks if the return type is a reference to Self (`&Self` or `&mut Self`).
17
/// This is used to detect methods that return `$this` in PHP.
18
fn returns_self_ref(output: Option<&Type>) -> bool {
3✔
19
    let Some(ty) = output else {
6✔
20
        return false;
×
21
    };
22
    if let Type::Reference(ref_) = ty
3✔
23
        && let Type::Path(path) = &*ref_.elem
×
24
        && path.path.segments.len() == 1
×
25
        && let Some(segment) = path.path.segments.last()
×
26
    {
27
        return segment.ident == "Self";
×
28
    }
29
    false
3✔
30
}
31

32
/// Checks if the return type is `Self` (not a reference).
33
/// This is used to detect methods that return a new instance of the same class.
34
fn returns_self(output: Option<&Type>) -> bool {
3✔
35
    let Some(ty) = output else {
6✔
36
        return false;
×
37
    };
38
    if let Type::Path(path) = ty
6✔
39
        && path.path.segments.len() == 1
3✔
40
        && let Some(segment) = path.path.segments.last()
6✔
41
    {
42
        return segment.ident == "Self";
3✔
43
    }
44
    false
×
45
}
46

47
pub fn wrap(input: &syn::Path) -> Result<TokenStream> {
×
48
    let Some(func_name) = input.get_ident() else {
×
49
        bail!(input => "Pass a PHP function name into `wrap_function!()`.");
×
50
    };
51
    let builder_func = format_ident!("_internal_{func_name}");
×
52

53
    Ok(quote! {{
×
54
        (<#builder_func as ::ext_php_rs::internal::function::PhpFunction>::FUNCTION_ENTRY)()
×
55
    }})
56
}
57

58
#[derive(FromAttributes, Default, Debug)]
59
#[darling(default, attributes(php), forward_attrs(doc))]
60
struct PhpFunctionAttribute {
61
    #[darling(flatten)]
62
    rename: PhpRename,
63
    defaults: HashMap<Ident, Expr>,
64
    optional: Option<Ident>,
65
    vis: Option<Visibility>,
66
    attrs: Vec<syn::Attribute>,
67
}
68

69
pub fn parser(mut input: ItemFn) -> Result<TokenStream> {
×
70
    let php_attr = PhpFunctionAttribute::from_attributes(&input.attrs)?;
×
71
    input.attrs.retain(|attr| !attr.path().is_ident("php"));
×
72

73
    let args = Args::parse_from_fnargs(input.sig.inputs.iter(), php_attr.defaults)?;
×
74
    if let Some(ReceiverArg { span, .. }) = args.receiver {
×
75
        bail!(span => "Receiver arguments are invalid on PHP functions. See `#[php_impl]`.");
×
76
    }
77

78
    let docs = get_docs(&php_attr.attrs)?;
×
79

80
    let func_name = php_attr
×
81
        .rename
×
82
        .rename(ident_to_php_name(&input.sig.ident), RenameRule::Snake);
×
83
    validate_php_name(&func_name, PhpNameContext::Function, input.sig.ident.span())?;
×
84
    let func = Function::new(&input.sig, func_name, args, php_attr.optional, docs);
×
85
    let function_impl = func.php_function_impl();
×
86

87
    Ok(quote! {
×
88
        #input
×
89
        #function_impl
×
90
    })
91
}
92

93
#[derive(Debug)]
94
pub struct Function<'a> {
95
    /// Identifier of the Rust function associated with the function.
96
    pub ident: &'a Ident,
97
    /// Name of the function in PHP.
98
    pub name: String,
99
    /// Function arguments.
100
    pub args: Args<'a>,
101
    /// Function outputs.
102
    pub output: Option<&'a Type>,
103
    /// The first optional argument of the function.
104
    pub optional: Option<Ident>,
105
    /// Doc comments for the function.
106
    pub docs: Vec<String>,
107
}
108

109
#[derive(Debug)]
110
pub enum CallType<'a> {
111
    Function,
112
    Method {
113
        class: &'a syn::Path,
114
        receiver: MethodReceiver,
115
    },
116
}
117

118
/// Type of receiver on the method.
119
#[derive(Debug)]
120
pub enum MethodReceiver {
121
    /// Static method - has no receiver.
122
    Static,
123
    /// Class method, takes `&self` or `&mut self`.
124
    Class,
125
    /// Class method, takes `&mut ZendClassObject<Self>`.
126
    ZendClassObject,
127
}
128

129
impl<'a> Function<'a> {
130
    /// Parse a function.
131
    ///
132
    /// # Parameters
133
    ///
134
    /// * `sig` - Function signature.
135
    /// * `name` - Function name in PHP land.
136
    /// * `args` - Function arguments.
137
    /// * `optional` - The ident of the first optional argument.
138
    pub fn new(
3✔
139
        sig: &'a syn::Signature,
140
        name: String,
141
        args: Args<'a>,
142
        optional: Option<Ident>,
143
        docs: Vec<String>,
144
    ) -> Self {
145
        Self {
146
            ident: &sig.ident,
3✔
147
            name,
148
            args,
149
            output: match &sig.output {
3✔
150
                syn::ReturnType::Default => None,
151
                syn::ReturnType::Type(_, ty) => Some(&**ty),
152
            },
153
            optional,
154
            docs,
155
        }
156
    }
157

158
    /// Generates an internal identifier for the function.
159
    pub fn internal_ident(&self) -> Ident {
×
160
        format_ident!("_internal_{}", &self.ident)
×
161
    }
162

163
    pub fn abstract_function_builder(&self) -> TokenStream {
3✔
164
        let name = &self.name;
6✔
165
        let (required, not_required) = self.args.split_args(self.optional.as_ref());
15✔
166

167
        // `entry` impl
168
        let required_args = required
6✔
169
            .iter()
170
            .map(TypedArg::arg_builder)
3✔
171
            .collect::<Vec<_>>();
172
        let not_required_args = not_required
6✔
173
            .iter()
174
            .map(TypedArg::arg_builder)
3✔
175
            .collect::<Vec<_>>();
176

177
        let returns = self.build_returns(None);
12✔
178
        let docs = if self.docs.is_empty() {
9✔
179
            quote! {}
2✔
180
        } else {
181
            let docs = &self.docs;
2✔
182
            quote! {
1✔
183
                .docs(&[#(#docs),*])
×
184
            }
185
        };
186

187
        quote! {
3✔
188
            ::ext_php_rs::builders::FunctionBuilder::new_abstract(#name)
×
189
            #(.arg(#required_args))*
×
190
            .not_required()
×
191
            #(.arg(#not_required_args))*
×
192
            #returns
×
193
            #docs
×
194
        }
195
    }
196

197
    /// Generates the function builder for the function.
198
    pub fn function_builder(&self, call_type: &CallType) -> TokenStream {
×
199
        let name = &self.name;
×
200
        let (required, not_required) = self.args.split_args(self.optional.as_ref());
×
201

202
        // `handler` impl
203
        let arg_declarations = self
×
204
            .args
×
205
            .typed
×
206
            .iter()
207
            .map(TypedArg::arg_declaration)
×
208
            .collect::<Vec<_>>();
209

210
        // `entry` impl
211
        let required_args = required
×
212
            .iter()
213
            .map(TypedArg::arg_builder)
×
214
            .collect::<Vec<_>>();
215
        let not_required_args = not_required
×
216
            .iter()
217
            .map(TypedArg::arg_builder)
×
218
            .collect::<Vec<_>>();
219

220
        let returns = self.build_returns(Some(call_type));
×
221
        let result = self.build_result(call_type, required, not_required);
×
222
        let docs = if self.docs.is_empty() {
×
223
            quote! {}
×
224
        } else {
225
            let docs = &self.docs;
×
226
            quote! {
×
227
                .docs(&[#(#docs),*])
×
228
            }
229
        };
230

231
        // Static methods cannot return &Self or &mut Self
232
        if returns_self_ref(self.output)
×
233
            && let CallType::Method {
×
234
                receiver: MethodReceiver::Static,
×
235
                ..
×
236
            } = call_type
×
237
            && let Some(output) = self.output
×
238
        {
239
            return quote_spanned! { output.span() =>
×
240
                compile_error!(
×
241
                    "Static methods cannot return `&Self` or `&mut Self`. \
×
242
                     Only instance methods can use fluent interface pattern returning `$this`."
×
243
                )
244
            };
245
        }
246

247
        // Check if this method returns &Self or &mut Self
248
        // In that case, we need to return `this` (the ZendClassObject) directly
249
        let returns_this = returns_self_ref(self.output)
×
250
            && matches!(
×
251
                call_type,
×
252
                CallType::Method {
×
253
                    receiver: MethodReceiver::Class | MethodReceiver::ZendClassObject,
×
254
                    ..
×
255
                }
256
            );
257

258
        let handler_body = if returns_this {
×
259
            quote! {
×
260
                use ::ext_php_rs::convert::IntoZval;
×
261

262
                #(#arg_declarations)*
×
263
                #result
×
264

265
                // The method returns &Self or &mut Self, use `this` directly
266
                if let Err(e) = this.set_zval(retval, false) {
×
267
                    let e: ::ext_php_rs::exception::PhpException = e.into();
×
268
                    e.throw().expect("Failed to throw PHP exception.");
×
269
                }
270
            }
271
        } else {
272
            quote! {
×
273
                use ::ext_php_rs::convert::IntoZval;
×
274

275
                #(#arg_declarations)*
×
276
                let result = {
×
277
                    #result
×
278
                };
279

280
                if let Err(e) = result.set_zval(retval, false) {
×
281
                    let e: ::ext_php_rs::exception::PhpException = e.into();
×
282
                    e.throw().expect("Failed to throw PHP exception.");
×
283
                }
284
            }
285
        };
286

287
        quote! {
×
288
            ::ext_php_rs::builders::FunctionBuilder::new(#name, {
×
289
                ::ext_php_rs::zend_fastcall! {
×
290
                    extern fn handler(
×
291
                        ex: &mut ::ext_php_rs::zend::ExecuteData,
×
292
                        retval: &mut ::ext_php_rs::types::Zval,
×
293
                    ) {
294
                        use ::ext_php_rs::zend::try_catch;
×
295
                        use ::std::panic::AssertUnwindSafe;
×
296

297
                        // Wrap the handler body with try_catch to ensure Rust destructors
298
                        // are called if a bailout occurs (issue #537)
299
                        let catch_result = try_catch(AssertUnwindSafe(|| {
×
300
                            #handler_body
×
301
                        }));
302

303
                        // If there was a bailout, run BailoutGuard cleanups and re-trigger
304
                        if catch_result.is_err() {
×
305
                            ::ext_php_rs::zend::run_bailout_cleanups();
×
306
                            unsafe { ::ext_php_rs::zend::bailout(); }
×
307
                        }
308
                    }
309
                }
310
                handler
×
311
            })
312
            #(.arg(#required_args))*
×
313
            .not_required()
×
314
            #(.arg(#not_required_args))*
×
315
            #returns
×
316
            #docs
×
317
        }
318
    }
319

320
    fn build_returns(&self, call_type: Option<&CallType>) -> TokenStream {
3✔
321
        let Some(output) = self.output.cloned() else {
6✔
322
            // PHP magic methods __destruct and __clone cannot have return types
323
            // (only applies to class methods, not standalone functions)
NEW
324
            if matches!(call_type, Some(CallType::Method { .. }))
×
NEW
325
                && (self.name == "__destruct" || self.name == "__clone")
×
326
            {
NEW
327
                return quote! {};
×
328
            }
329
            // No return type means void in PHP
NEW
330
            return quote! {
×
NEW
331
                .returns(::ext_php_rs::flags::DataType::Void, false, false)
×
332
            };
333
        };
334

335
        let mut output = output;
6✔
336
        output.drop_lifetimes();
6✔
337

338
        // If returning &Self or &mut Self from a method, use the class type
339
        // for return type information since we return `this` (ZendClassObject)
340
        if returns_self_ref(self.output)
6✔
NEW
341
            && let Some(CallType::Method { class, .. }) = call_type
×
342
        {
NEW
343
            return quote! {
×
344
                .returns(
×
NEW
345
                    <&mut ::ext_php_rs::types::ZendClassObject<#class> as ::ext_php_rs::convert::IntoZval>::TYPE,
×
346
                    false,
×
NEW
347
                    <&mut ::ext_php_rs::types::ZendClassObject<#class> as ::ext_php_rs::convert::IntoZval>::NULLABLE,
×
348
                )
349
            };
350
        }
351

352
        // If returning Self (new instance) from a method, replace Self with
353
        // the actual class type since Self won't resolve in generated code
354
        if returns_self(self.output)
6✔
NEW
355
            && let Some(CallType::Method { class, .. }) = call_type
×
356
        {
NEW
357
            return quote! {
×
NEW
358
                .returns(
×
NEW
359
                    <#class as ::ext_php_rs::convert::IntoZval>::TYPE,
×
NEW
360
                    false,
×
NEW
361
                    <#class as ::ext_php_rs::convert::IntoZval>::NULLABLE,
×
362
                )
363
            };
364
        }
365

366
        quote! {
3✔
NEW
367
            .returns(
×
NEW
368
                <#output as ::ext_php_rs::convert::IntoZval>::TYPE,
×
NEW
369
                false,
×
NEW
370
                <#output as ::ext_php_rs::convert::IntoZval>::NULLABLE,
×
371
            )
372
        }
373
    }
374

375
    fn build_result(
×
376
        &self,
377
        call_type: &CallType,
378
        required: &[TypedArg<'_>],
379
        not_required: &[TypedArg<'_>],
380
    ) -> TokenStream {
381
        let ident = self.ident;
×
382
        let required_arg_names: Vec<_> = required.iter().map(|arg| arg.name).collect();
×
383
        let not_required_arg_names: Vec<_> = not_required.iter().map(|arg| arg.name).collect();
×
384

385
        let variadic_bindings = self.args.typed.iter().filter_map(|arg| {
×
386
            if arg.variadic {
×
387
                let name = arg.name;
×
388
                let variadic_name = format_ident!("__variadic_{}", name);
×
389
                let clean_ty = arg.clean_ty();
×
390
                Some(quote! {
×
391
                    let #variadic_name = #name.variadic_vals::<#clean_ty>();
×
392
                })
393
            } else {
394
                None
×
395
            }
396
        });
397

398
        let arg_accessors = self.args.typed.iter().map(|arg| {
×
399
            arg.accessor(|e| {
×
400
                quote! {
×
401
                    #e.throw().expect("Failed to throw PHP exception.");
×
402
                    return;
×
403
                }
404
            })
405
        });
406

407
        // Check if this method returns &Self or &mut Self
408
        let returns_this = returns_self_ref(self.output);
×
409

410
        match call_type {
×
411
            CallType::Function => quote! {
×
412
                let parse = ex.parser()
×
413
                    #(.arg(&mut #required_arg_names))*
×
414
                    .not_required()
×
415
                    #(.arg(&mut #not_required_arg_names))*
×
416
                    .parse();
×
417
                if parse.is_err() {
×
418
                    return;
×
419
                }
420
                #(#variadic_bindings)*
×
421

422
                #ident(#({#arg_accessors}),*)
×
423
            },
424
            CallType::Method { class, receiver } => {
×
425
                let this = match receiver {
×
426
                    MethodReceiver::Static => quote! {
×
427
                        let parse = ex.parser();
×
428
                    },
429
                    MethodReceiver::ZendClassObject | MethodReceiver::Class => quote! {
×
430
                        let (parse, this) = ex.parser_method::<#class>();
×
431
                        let this = match this {
×
432
                            Some(this) => this,
×
433
                            None => {
×
434
                                ::ext_php_rs::exception::PhpException::default("Failed to retrieve reference to `$this`".into())
×
435
                                    .throw()
×
436
                                    .unwrap();
×
437
                                return;
×
438
                            }
439
                        };
440
                    },
441
                };
442

443
                // When returning &Self or &mut Self, discard the return value
444
                // (we'll use `this` directly in the handler)
445
                let call = match (receiver, returns_this) {
×
446
                    (MethodReceiver::Static, _) => {
×
447
                        quote! { #class::#ident(#({#arg_accessors}),*) }
×
448
                    }
449
                    (MethodReceiver::Class, true) => {
×
450
                        quote! { let _ = this.#ident(#({#arg_accessors}),*); }
×
451
                    }
452
                    (MethodReceiver::Class, false) => {
×
453
                        quote! { this.#ident(#({#arg_accessors}),*) }
×
454
                    }
455
                    (MethodReceiver::ZendClassObject, true) => {
×
456
                        // Explicit scope helps with mutable borrow lifetime when
457
                        // the method returns `&mut Self`
458
                        quote! {
×
459
                            {
460
                                let _ = #class::#ident(this, #({#arg_accessors}),*);
×
461
                            }
462
                        }
463
                    }
464
                    (MethodReceiver::ZendClassObject, false) => {
×
465
                        quote! { #class::#ident(this, #({#arg_accessors}),*) }
×
466
                    }
467
                };
468

469
                quote! {
×
470
                    #this
×
471
                    let parse_result = parse
×
472
                        #(.arg(&mut #required_arg_names))*
×
473
                        .not_required()
×
474
                        #(.arg(&mut #not_required_arg_names))*
×
475
                        .parse();
×
476
                    if parse_result.is_err() {
×
477
                        return;
×
478
                    }
479
                    #(#variadic_bindings)*
×
480

481
                    #call
×
482
                }
483
            }
484
        }
485
    }
486

487
    /// Generates a struct and impl for the `PhpFunction` trait.
488
    pub fn php_function_impl(&self) -> TokenStream {
×
489
        let internal_ident = self.internal_ident();
×
490
        let builder = self.function_builder(&CallType::Function);
×
491

492
        quote! {
×
493
            #[doc(hidden)]
×
494
            #[allow(non_camel_case_types)]
×
495
            struct #internal_ident;
×
496

497
            impl ::ext_php_rs::internal::function::PhpFunction for #internal_ident {
×
498
                const FUNCTION_ENTRY: fn() -> ::ext_php_rs::builders::FunctionBuilder<'static> = {
×
499
                    fn entry() -> ::ext_php_rs::builders::FunctionBuilder<'static>
×
500
                    {
501
                        #builder
×
502
                    }
503
                    entry
×
504
                };
505
            }
506
        }
507
    }
508

509
    /// Returns a constructor metadata object for this function. This doesn't
510
    /// check if the function is a constructor, however.
511
    pub fn constructor_meta(
×
512
        &self,
513
        class: &syn::Path,
514
        visibility: Option<&Visibility>,
515
    ) -> TokenStream {
516
        let ident = self.ident;
×
517
        let (required, not_required) = self.args.split_args(self.optional.as_ref());
×
518
        let required_args = required
×
519
            .iter()
520
            .map(TypedArg::arg_builder)
×
521
            .collect::<Vec<_>>();
522
        let not_required_args = not_required
×
523
            .iter()
524
            .map(TypedArg::arg_builder)
×
525
            .collect::<Vec<_>>();
526

527
        let required_arg_names: Vec<_> = required.iter().map(|arg| arg.name).collect();
×
528
        let not_required_arg_names: Vec<_> = not_required.iter().map(|arg| arg.name).collect();
×
529
        let arg_declarations = self
×
530
            .args
×
531
            .typed
×
532
            .iter()
533
            .map(TypedArg::arg_declaration)
×
534
            .collect::<Vec<_>>();
535
        let variadic_bindings = self.args.typed.iter().filter_map(|arg| {
×
536
            if arg.variadic {
×
537
                let name = arg.name;
×
538
                let variadic_name = format_ident!("__variadic_{}", name);
×
539
                let clean_ty = arg.clean_ty();
×
540
                Some(quote! {
×
541
                    let #variadic_name = #name.variadic_vals::<#clean_ty>();
×
542
                })
543
            } else {
544
                None
×
545
            }
546
        });
547
        let arg_accessors = self.args.typed.iter().map(|arg| {
×
548
            arg.accessor(
×
549
                |e| quote! { return ::ext_php_rs::class::ConstructorResult::Exception(#e); },
×
550
            )
551
        });
552
        let variadic = self.args.typed.iter().any(|arg| arg.variadic).then(|| {
×
553
            quote! {
×
554
                .variadic()
×
555
            }
556
        });
557
        let docs = &self.docs;
×
558
        let flags = visibility.option_tokens();
×
559

560
        quote! {
×
561
            ::ext_php_rs::class::ConstructorMeta {
×
562
                constructor: {
×
563
                    fn inner(ex: &mut ::ext_php_rs::zend::ExecuteData) -> ::ext_php_rs::class::ConstructorResult<#class> {
×
564
                        use ::ext_php_rs::zend::try_catch;
×
565
                        use ::std::panic::AssertUnwindSafe;
×
566

567
                        // Wrap the constructor body with try_catch to ensure Rust destructors
568
                        // are called if a bailout occurs (issue #537)
569
                        let catch_result = try_catch(AssertUnwindSafe(|| {
×
570
                            #(#arg_declarations)*
×
571
                            let parse = ex.parser()
×
572
                                #(.arg(&mut #required_arg_names))*
×
573
                                .not_required()
×
574
                                #(.arg(&mut #not_required_arg_names))*
×
575
                                #variadic
×
576
                                .parse();
×
577
                            if parse.is_err() {
×
578
                                return ::ext_php_rs::class::ConstructorResult::ArgError;
×
579
                            }
580
                            #(#variadic_bindings)*
×
581
                            #class::#ident(#({#arg_accessors}),*).into()
×
582
                        }));
583

584
                        // If there was a bailout, run BailoutGuard cleanups and re-trigger
585
                        match catch_result {
×
586
                            Ok(result) => result,
×
587
                            Err(_) => {
×
588
                                ::ext_php_rs::zend::run_bailout_cleanups();
×
589
                                unsafe { ::ext_php_rs::zend::bailout() }
×
590
                            }
591
                        }
592
                    }
593
                    inner
×
594
                },
595
                build_fn: {
×
596
                    fn inner(func: ::ext_php_rs::builders::FunctionBuilder) -> ::ext_php_rs::builders::FunctionBuilder {
×
597
                        func
×
598
                            .docs(&[#(#docs),*])
×
599
                            #(.arg(#required_args))*
×
600
                            .not_required()
×
601
                            #(.arg(#not_required_args))*
×
602
                            #variadic
×
603
                    }
604
                    inner
×
605
                },
606
                flags: #flags
×
607
            }
608
        }
609
    }
610
}
611

612
#[derive(Debug)]
613
pub struct ReceiverArg {
614
    pub _mutable: bool,
615
    pub span: Span,
616
}
617

618
#[derive(Debug)]
619
pub struct TypedArg<'a> {
620
    pub name: &'a Ident,
621
    pub ty: Type,
622
    pub nullable: bool,
623
    pub default: Option<Expr>,
624
    pub as_ref: bool,
625
    pub variadic: bool,
626
}
627

628
#[derive(Debug)]
629
pub struct Args<'a> {
630
    pub receiver: Option<ReceiverArg>,
631
    pub typed: Vec<TypedArg<'a>>,
632
}
633

634
impl<'a> Args<'a> {
635
    pub fn parse_from_fnargs(
3✔
636
        args: impl Iterator<Item = &'a FnArg>,
637
        mut defaults: HashMap<Ident, Expr>,
638
    ) -> Result<Self> {
639
        let mut result = Self {
640
            receiver: None,
641
            typed: vec![],
3✔
642
        };
643
        for arg in args {
8✔
644
            match arg {
5✔
645
                FnArg::Receiver(receiver) => {
3✔
646
                    if receiver.reference.is_none() {
6✔
647
                        bail!(receiver => "PHP objects are heap-allocated and cannot be passed by value. Try using `&self` or `&mut self`.");
×
648
                    } else if result.receiver.is_some() {
6✔
649
                        bail!(receiver => "Too many receivers specified.")
×
650
                    }
651
                    result.receiver.replace(ReceiverArg {
9✔
652
                        _mutable: receiver.mutability.is_some(),
9✔
653
                        span: receiver.span(),
3✔
654
                    });
655
                }
656
                FnArg::Typed(PatType { pat, ty, .. }) => {
4✔
657
                    let syn::Pat::Ident(syn::PatIdent { ident, .. }) = &**pat else {
4✔
658
                        bail!(pat => "Unsupported argument.");
×
659
                    };
660

661
                    // If the variable is `&[&Zval]` treat it as the variadic argument.
662
                    let default = defaults.remove(ident);
8✔
663
                    let nullable = type_is_nullable(ty.as_ref())?;
6✔
664
                    let (variadic, as_ref, ty) = Self::parse_typed(ty);
8✔
665
                    result.typed.push(TypedArg {
6✔
666
                        name: ident,
4✔
667
                        ty,
4✔
668
                        nullable,
4✔
669
                        default,
4✔
670
                        as_ref,
2✔
671
                        variadic,
2✔
672
                    });
673
                }
674
            }
675
        }
676
        Ok(result)
3✔
677
    }
678

679
    fn parse_typed(ty: &Type) -> (bool, bool, Type) {
2✔
680
        match ty {
2✔
681
            Type::Reference(ref_) => {
×
682
                let as_ref = ref_.mutability.is_some();
×
683
                match ref_.elem.as_ref() {
×
684
                    Type::Slice(slice) => (
×
685
                        // TODO: Allow specifying the variadic type.
686
                        slice.elem.to_token_stream().to_string() == "& Zval",
×
687
                        as_ref,
×
688
                        ty.clone(),
×
689
                    ),
690
                    _ => (false, as_ref, ty.clone()),
×
691
                }
692
            }
693
            Type::Path(TypePath { path, .. }) => {
2✔
694
                let mut as_ref = false;
4✔
695

696
                // For for types that are `Option<&mut T>` to turn them into
697
                // `Option<&T>`, marking the Arg as as "passed by reference".
698
                let ty = path
4✔
699
                    .segments
2✔
700
                    .last()
701
                    .filter(|seg| seg.ident == "Option")
6✔
702
                    .and_then(|seg| {
2✔
703
                        if let PathArguments::AngleBracketed(args) = &seg.arguments {
×
704
                            args.args
×
705
                                .iter()
×
706
                                .find(|arg| matches!(arg, GenericArgument::Type(_)))
×
707
                                .and_then(|ga| match ga {
×
708
                                    GenericArgument::Type(ty) => Some(match ty {
×
709
                                        Type::Reference(r) => {
×
710
                                            // Only mark as_ref for mutable references
711
                                            // (Option<&mut T>), not immutable ones (Option<&T>)
712
                                            as_ref = r.mutability.is_some();
×
713
                                            let mut new_ref = r.clone();
×
714
                                            new_ref.mutability = None;
×
715
                                            Type::Reference(new_ref)
×
716
                                        }
717
                                        _ => ty.clone(),
×
718
                                    }),
719
                                    _ => None,
×
720
                                })
721
                        } else {
722
                            None
×
723
                        }
724
                    })
725
                    .unwrap_or_else(|| ty.clone());
6✔
726
                (false, as_ref, ty.clone())
4✔
727
            }
728
            _ => (false, false, ty.clone()),
×
729
        }
730
    }
731

732
    /// Splits the typed arguments into two slices:
733
    ///
734
    /// 1. Required arguments.
735
    /// 2. Non-required arguments.
736
    ///
737
    /// # Parameters
738
    ///
739
    /// * `optional` - The first optional argument. If [`None`], the optional
740
    ///   arguments will be from the first optional argument (nullable or has
741
    ///   default) after the last required argument to the end of the arguments.
742
    pub fn split_args(&self, optional: Option<&Ident>) -> (&[TypedArg<'a>], &[TypedArg<'a>]) {
3✔
743
        let mut mid = None;
6✔
744
        for (i, arg) in self.typed.iter().enumerate() {
10✔
745
            // An argument is optional if it's nullable (Option<T>) or has a default value.
746
            let is_optional = arg.nullable || arg.default.is_some();
8✔
747
            if let Some(optional) = optional {
2✔
748
                if optional == arg.name {
×
749
                    mid.replace(i);
×
750
                }
751
            } else if mid.is_none() && is_optional {
6✔
752
                mid.replace(i);
×
753
            } else if !is_optional {
4✔
754
                mid.take();
2✔
755
            }
756
        }
757
        match mid {
3✔
758
            Some(mid) => (&self.typed[..mid], &self.typed[mid..]),
×
759
            None => (&self.typed[..], &self.typed[0..0]),
6✔
760
        }
761
    }
762
}
763

764
impl TypedArg<'_> {
765
    /// Returns a 'clean type' with the lifetimes removed. This allows the type
766
    /// to be used outside of the original function context.
767
    fn clean_ty(&self) -> Type {
2✔
768
        let mut ty = self.ty.clone();
6✔
769
        ty.drop_lifetimes();
4✔
770

771
        // Variadic arguments are passed as &[&Zval], so we need to extract the
772
        // inner type.
773
        if self.variadic {
2✔
774
            let Type::Reference(reference) = &ty else {
×
775
                return ty;
×
776
            };
777

778
            if let Type::Slice(inner) = &*reference.elem {
×
779
                return *inner.elem.clone();
×
780
            }
781
        }
782

783
        ty
2✔
784
    }
785

786
    /// Returns a token stream containing an argument declaration, where the
787
    /// name of the variable holding the arg is the name of the argument.
788
    fn arg_declaration(&self) -> TokenStream {
×
789
        let name = self.name;
×
790
        let val = self.arg_builder();
×
791
        quote! {
×
792
            let mut #name = #val;
793
        }
794
    }
795

796
    /// Returns a token stream containing the `Arg` definition to be passed to
797
    /// `ext-php-rs`.
798
    fn arg_builder(&self) -> TokenStream {
2✔
799
        let name = ident_to_php_name(self.name);
6✔
800
        let ty = self.clean_ty();
6✔
801
        let null = if self.nullable {
4✔
802
            Some(quote! { .allow_null() })
×
803
        } else {
804
            None
2✔
805
        };
806
        let default = self.default.as_ref().map(|val| {
8✔
807
            let val = expr_to_php_stub(val);
×
808
            quote! {
×
809
                .default(#val)
810
            }
811
        });
812
        let as_ref = if self.as_ref {
4✔
813
            Some(quote! { .as_ref() })
×
814
        } else {
815
            None
2✔
816
        };
817
        let variadic = self.variadic.then(|| quote! { .is_variadic() });
6✔
818
        quote! {
2✔
819
            ::ext_php_rs::args::Arg::new(#name, <#ty as ::ext_php_rs::convert::FromZvalMut>::TYPE)
820
                #null
821
                #default
822
                #as_ref
823
                #variadic
824
        }
825
    }
826

827
    /// Get the accessor used to access the value of the argument.
828
    fn accessor(&self, bail_fn: impl Fn(TokenStream) -> TokenStream) -> TokenStream {
×
829
        let name = self.name;
×
830
        if let Some(default) = &self.default {
×
831
            if self.nullable {
×
832
                // For nullable types with defaults, null is acceptable
833
                quote! {
×
834
                    #name.val().unwrap_or(#default.into())
×
835
                }
836
            } else {
837
                // For non-nullable types with defaults:
838
                // - If argument was omitted: use default
839
                // - If null was explicitly passed: throw TypeError
840
                // - If a value was passed: try to convert it
841
                let bail_null = bail_fn(quote! {
×
842
                    ::ext_php_rs::exception::PhpException::new(
×
843
                        concat!("Argument `$", stringify!(#name), "` must not be null").into(),
×
844
                        0,
×
845
                        ::ext_php_rs::zend::ce::type_error(),
×
846
                    )
847
                });
848
                let bail_invalid = bail_fn(quote! {
×
849
                    ::ext_php_rs::exception::PhpException::default(
×
850
                        concat!("Invalid value given for argument `", stringify!(#name), "`.").into()
×
851
                    )
852
                });
853
                quote! {
×
854
                    match #name.zval() {
×
855
                        Some(zval) if zval.is_null() => {
×
856
                            // Null was explicitly passed to a non-nullable parameter
857
                            #bail_null
×
858
                        }
859
                        Some(_) => {
×
860
                            // A value was passed, try to convert it
861
                            match #name.val() {
×
862
                                Some(val) => val,
×
863
                                None => {
×
864
                                    #bail_invalid
×
865
                                }
866
                            }
867
                        }
868
                        None => {
×
869
                            // Argument was omitted, use default
870
                            #default.into()
×
871
                        }
872
                    }
873
                }
874
            }
875
        } else if self.variadic {
×
876
            let variadic_name = format_ident!("__variadic_{}", name);
×
877
            quote! {
×
878
                #variadic_name.as_slice()
×
879
            }
880
        } else if self.nullable {
×
881
            // Originally I thought we could just use the below case for `null` options, as
882
            // `val()` will return `Option<Option<T>>`, however, this isn't the case when
883
            // the argument isn't given, as the underlying zval is null.
884
            quote! {
×
885
                #name.val()
×
886
            }
887
        } else {
888
            let bail = bail_fn(quote! {
×
889
                ::ext_php_rs::exception::PhpException::default(
×
890
                    concat!("Invalid value given for argument `", stringify!(#name), "`.").into()
×
891
                )
892
            });
893
            quote! {
×
894
                match #name.val() {
×
895
                    Some(val) => val,
×
896
                    None => {
×
897
                        #bail;
×
898
                    }
899
                }
900
            }
901
        }
902
    }
903
}
904

905
/// Converts a Rust expression to a PHP stub-compatible default value string.
906
///
907
/// This function handles common Rust patterns and converts them to valid PHP
908
/// syntax for use in generated stub files:
909
///
910
/// - `None` → `"null"`
911
/// - `Some(expr)` → converts the inner expression
912
/// - `42`, `3.14` → numeric literals as-is
913
/// - `true`/`false` → as-is
914
/// - `"string"` → `"string"`
915
/// - `"string".to_string()` or `String::from("string")` → `"string"`
916
fn expr_to_php_stub(expr: &Expr) -> String {
×
917
    match expr {
×
918
        // Handle None -> null
919
        Expr::Path(path) => {
×
920
            let path_str = path.path.to_token_stream().to_string();
×
921
            if path_str == "None" {
×
922
                "null".to_string()
×
923
            } else if path_str == "true" || path_str == "false" {
×
924
                path_str
×
925
            } else {
926
                // For other paths (constants, etc.), use the raw representation
927
                path_str
×
928
            }
929
        }
930

931
        // Handle Some(expr) -> convert inner expression
932
        Expr::Call(call) => {
×
933
            if let Expr::Path(func_path) = &*call.func {
×
934
                let func_name = func_path.path.to_token_stream().to_string();
×
935

936
                // Some(value) -> convert inner value
937
                if func_name == "Some"
×
938
                    && let Some(arg) = call.args.first()
×
939
                {
940
                    return expr_to_php_stub(arg);
×
941
                }
942

943
                // String::from("...") -> "..."
944
                if (func_name == "String :: from" || func_name == "String::from")
×
945
                    && let Some(arg) = call.args.first()
×
946
                {
947
                    return expr_to_php_stub(arg);
×
948
                }
949
            }
950

951
            // Default: use raw representation
952
            expr.to_token_stream().to_string()
×
953
        }
954

955
        // Handle method calls like "string".to_string()
956
        Expr::MethodCall(method_call) => {
×
957
            let method_name = method_call.method.to_string();
×
958

959
            // "...".to_string() or "...".to_owned() or "...".into() -> "..."
960
            if method_name == "to_string" || method_name == "to_owned" || method_name == "into" {
×
961
                return expr_to_php_stub(&method_call.receiver);
×
962
            }
963

964
            // Default: use raw representation
965
            expr.to_token_stream().to_string()
×
966
        }
967

968
        // String literals -> keep as-is (already valid PHP)
969
        Expr::Lit(lit) => match &lit.lit {
×
970
            syn::Lit::Str(s) => format!(
×
971
                "\"{}\"",
972
                s.value().replace('\\', "\\\\").replace('"', "\\\"")
×
973
            ),
974
            syn::Lit::Int(i) => i.to_string(),
×
975
            syn::Lit::Float(f) => f.to_string(),
×
976
            syn::Lit::Bool(b) => if b.value { "true" } else { "false" }.to_string(),
×
977
            syn::Lit::Char(c) => format!("\"{}\"", c.value()),
×
978
            _ => expr.to_token_stream().to_string(),
×
979
        },
980

981
        // Handle arrays: [] or vec![]
982
        Expr::Array(arr) => {
×
983
            if arr.elems.is_empty() {
×
984
                "[]".to_string()
×
985
            } else {
986
                let elems: Vec<String> = arr.elems.iter().map(expr_to_php_stub).collect();
×
987
                format!("[{}]", elems.join(", "))
×
988
            }
989
        }
990

991
        // Handle vec![] macro
992
        Expr::Macro(m) => {
×
993
            let macro_name = m.mac.path.to_token_stream().to_string();
×
994
            if macro_name == "vec" {
×
995
                let tokens = m.mac.tokens.to_string();
×
996
                if tokens.trim().is_empty() {
×
997
                    return "[]".to_string();
×
998
                }
999
            }
1000
            // Default: use raw representation
1001
            expr.to_token_stream().to_string()
×
1002
        }
1003

1004
        // Handle unary expressions like -42
1005
        Expr::Unary(unary) => {
×
1006
            let inner = expr_to_php_stub(&unary.expr);
×
1007
            format!("{}{}", unary.op.to_token_stream(), inner)
×
1008
        }
1009

1010
        // Default: use raw representation
1011
        _ => expr.to_token_stream().to_string(),
×
1012
    }
1013
}
1014

1015
/// Returns true if the given type is nullable in PHP (i.e., it's an
1016
/// `Option<T>`).
1017
///
1018
/// Note: Having a default value does NOT make a type nullable. A parameter with
1019
/// a default value is optional (can be omitted), but passing `null` explicitly
1020
/// should still be rejected unless the type is `Option<T>`.
1021
// TODO(david): Eventually move to compile-time constants for this (similar to
1022
// FromZval::NULLABLE).
1023
pub fn type_is_nullable(ty: &Type) -> Result<bool> {
2✔
1024
    Ok(match ty {
2✔
1025
        Type::Path(path) => path
4✔
1026
            .path
2✔
1027
            .segments
2✔
1028
            .iter()
2✔
1029
            .next_back()
2✔
1030
            .is_some_and(|seg| seg.ident == "Option"),
6✔
1031
        Type::Reference(_) => false, /* Reference cannot be nullable unless */
×
1032
        // wrapped in `Option` (in that case it'd be a Path).
1033
        _ => bail!(ty => "Unsupported argument type."),
×
1034
    })
1035
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc