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

davidcole1340 / ext-php-rs / 16274060216

14 Jul 2025 05:51PM UTC coverage: 22.552%. Remained the same
16274060216

Pull #514

github

web-flow
Merge 7ee17f41f into 31c9d9968
Pull Request #514: feat(stubs)!: add stubs for `RustClosure`

13 of 15 new or added lines in 3 files covered. (86.67%)

58 existing lines in 3 files now uncovered.

882 of 3911 relevant lines covered (22.55%)

3.69 hits per line

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

0.0
/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};
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::{PhpRename, RenameRule, Visibility};
11
use crate::prelude::*;
12
use crate::syn_ext::DropLifetimes;
13

14
pub fn wrap(input: &syn::Path) -> Result<TokenStream> {
×
15
    let Some(func_name) = input.get_ident() else {
×
16
        bail!(input => "Pass a PHP function name into `wrap_function!()`.");
×
17
    };
18
    let builder_func = format_ident!("_internal_{func_name}");
×
19

20
    Ok(quote! {{
×
21
        (<#builder_func as ::ext_php_rs::internal::function::PhpFunction>::FUNCTION_ENTRY)()
×
22
    }})
23
}
24

25
#[derive(FromAttributes, Default, Debug)]
26
#[darling(default, attributes(php), forward_attrs(doc))]
27
struct PhpFunctionAttribute {
28
    #[darling(flatten)]
29
    rename: PhpRename,
30
    defaults: HashMap<Ident, Expr>,
31
    optional: Option<Ident>,
32
    vis: Option<Visibility>,
33
    attrs: Vec<syn::Attribute>,
34
}
35

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

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

45
    let docs = get_docs(&php_attr.attrs)?;
×
46

47
    let func = Function::new(
48
        &input.sig,
×
49
        php_attr
×
50
            .rename
×
51
            .rename(input.sig.ident.to_string(), RenameRule::Snake),
×
52
        args,
×
53
        php_attr.optional,
×
54
        docs,
×
55
    );
56
    let function_impl = func.php_function_impl();
×
57

58
    Ok(quote! {
×
59
        #input
×
60
        #function_impl
×
61
    })
62
}
63

64
#[derive(Debug)]
65
pub struct Function<'a> {
66
    /// Identifier of the Rust function associated with the function.
67
    pub ident: &'a Ident,
68
    /// Name of the function in PHP.
69
    pub name: String,
70
    /// Function arguments.
71
    pub args: Args<'a>,
72
    /// Function outputs.
73
    pub output: Option<&'a Type>,
74
    /// The first optional argument of the function.
75
    pub optional: Option<Ident>,
76
    /// Doc comments for the function.
77
    pub docs: Vec<String>,
78
}
79

80
#[derive(Debug)]
81
pub enum CallType<'a> {
82
    Function,
83
    Method {
84
        class: &'a syn::Path,
85
        receiver: MethodReceiver,
86
    },
87
}
88

89
/// Type of receiver on the method.
90
#[derive(Debug)]
91
pub enum MethodReceiver {
92
    /// Static method - has no receiver.
93
    Static,
94
    /// Class method, takes `&self` or `&mut self`.
95
    Class,
96
    /// Class method, takes `&mut ZendClassObject<Self>`.
97
    ZendClassObject,
98
}
99

100
impl<'a> Function<'a> {
101
    /// Parse a function.
102
    ///
103
    /// # Parameters
104
    ///
105
    /// * `sig` - Function signature.
106
    /// * `name` - Function name in PHP land.
107
    /// * `args` - Function arguments.
108
    /// * `optional` - The ident of the first optional argument.
109
    pub fn new(
×
110
        sig: &'a syn::Signature,
111
        name: String,
112
        args: Args<'a>,
113
        optional: Option<Ident>,
114
        docs: Vec<String>,
115
    ) -> Self {
116
        Self {
117
            ident: &sig.ident,
×
118
            name,
119
            args,
120
            output: match &sig.output {
×
121
                syn::ReturnType::Default => None,
122
                syn::ReturnType::Type(_, ty) => Some(&**ty),
123
            },
124
            optional,
125
            docs,
126
        }
127
    }
128

129
    /// Generates an internal identifier for the function.
130
    pub fn internal_ident(&self) -> Ident {
×
131
        format_ident!("_internal_{}", &self.ident)
×
132
    }
133

134
    /// Generates the function builder for the function.
135
    pub fn function_builder(&self, call_type: CallType) -> TokenStream {
×
136
        let name = &self.name;
×
137
        let (required, not_required) = self.args.split_args(self.optional.as_ref());
×
138

139
        // `handler` impl
140
        let arg_declarations = self
×
141
            .args
×
142
            .typed
×
143
            .iter()
144
            .map(TypedArg::arg_declaration)
×
145
            .collect::<Vec<_>>();
146

147
        // `entry` impl
148
        let required_args = required
×
149
            .iter()
150
            .map(TypedArg::arg_builder)
×
151
            .collect::<Vec<_>>();
152
        let not_required_args = not_required
×
153
            .iter()
154
            .map(TypedArg::arg_builder)
×
155
            .collect::<Vec<_>>();
156

157
        let returns = self.build_returns();
×
158
        let result = self.build_result(call_type, required, not_required);
×
159
        let docs = if self.docs.is_empty() {
×
160
            quote! {}
×
161
        } else {
162
            let docs = &self.docs;
×
163
            quote! {
×
164
                .docs(&[#(#docs),*])
×
165
            }
166
        };
167

168
        quote! {
×
169
            ::ext_php_rs::builders::FunctionBuilder::new(#name, {
×
170
                ::ext_php_rs::zend_fastcall! {
×
171
                    extern fn handler(
×
172
                        ex: &mut ::ext_php_rs::zend::ExecuteData,
×
173
                        retval: &mut ::ext_php_rs::types::Zval,
×
174
                    ) {
175
                        use ::ext_php_rs::convert::IntoZval;
×
176

177
                        #(#arg_declarations)*
×
178
                        let result = {
×
179
                            #result
×
180
                        };
181

182
                        if let Err(e) = result.set_zval(retval, false) {
×
183
                            let e: ::ext_php_rs::exception::PhpException = e.into();
×
184
                            e.throw().expect("Failed to throw PHP exception.");
×
185
                        }
186
                    }
187
                }
188
                handler
×
189
            })
190
            #(.arg(#required_args))*
×
191
            .not_required()
×
192
            #(.arg(#not_required_args))*
×
193
            #returns
×
194
            #docs
×
195
        }
196
    }
197

198
    fn build_returns(&self) -> Option<TokenStream> {
×
199
        self.output.cloned().map(|mut output| {
×
200
            output.drop_lifetimes();
×
201
            quote! {
×
202
                .returns(
×
203
                    <#output as ::ext_php_rs::convert::IntoZval>::TYPE,
×
204
                    false,
×
205
                    <#output as ::ext_php_rs::convert::IntoZval>::NULLABLE,
×
206
                )
207
            }
208
        })
209
    }
210

211
    fn build_result(
×
212
        &self,
213
        call_type: CallType,
214
        required: &[TypedArg<'_>],
215
        not_required: &[TypedArg<'_>],
216
    ) -> TokenStream {
217
        let ident = self.ident;
×
218
        let required_arg_names: Vec<_> = required.iter().map(|arg| arg.name).collect();
×
219
        let not_required_arg_names: Vec<_> = not_required.iter().map(|arg| arg.name).collect();
×
220

221
        let arg_accessors = self.args.typed.iter().map(|arg| {
×
222
            arg.accessor(|e| {
×
223
                quote! {
×
224
                    #e.throw().expect("Failed to throw PHP exception.");
×
225
                    return;
×
226
                }
227
            })
228
        });
229

230
        match call_type {
×
231
            CallType::Function => quote! {
×
232
                let parse = ex.parser()
×
233
                    #(.arg(&mut #required_arg_names))*
×
234
                    .not_required()
×
235
                    #(.arg(&mut #not_required_arg_names))*
×
236
                    .parse();
×
237
                if parse.is_err() {
×
238
                    return;
×
239
                }
240

241
                #ident(#({#arg_accessors}),*)
×
242
            },
243
            CallType::Method { class, receiver } => {
×
244
                let this = match receiver {
×
245
                    MethodReceiver::Static => quote! {
×
246
                        let parse = ex.parser();
×
247
                    },
248
                    MethodReceiver::ZendClassObject | MethodReceiver::Class => quote! {
×
249
                        let (parse, this) = ex.parser_method::<#class>();
×
250
                        let this = match this {
×
251
                            Some(this) => this,
×
252
                            None => {
×
253
                                ::ext_php_rs::exception::PhpException::default("Failed to retrieve reference to `$this`".into())
×
254
                                    .throw()
×
255
                                    .unwrap();
×
256
                                return;
×
257
                            }
258
                        };
259
                    },
260
                };
261
                let call = match receiver {
×
262
                    MethodReceiver::Static => {
×
263
                        quote! { #class::#ident(#({#arg_accessors}),*) }
×
264
                    }
265
                    MethodReceiver::Class => quote! { this.#ident(#({#arg_accessors}),*) },
×
266
                    MethodReceiver::ZendClassObject => {
×
267
                        quote! { #class::#ident(this, #({#arg_accessors}),*) }
×
268
                    }
269
                };
270
                quote! {
×
271
                    #this
×
272
                    let parse_result = parse
×
273
                        #(.arg(&mut #required_arg_names))*
×
274
                        .not_required()
×
275
                        #(.arg(&mut #not_required_arg_names))*
×
276
                        .parse();
×
277
                    if parse_result.is_err() {
×
278
                        return;
×
279
                    }
280

281
                    #call
×
282
                }
283
            }
284
        }
285
    }
286

287
    /// Generates a struct and impl for the `PhpFunction` trait.
288
    pub fn php_function_impl(&self) -> TokenStream {
×
289
        let internal_ident = self.internal_ident();
×
290
        let builder = self.function_builder(CallType::Function);
×
291

292
        quote! {
×
293
            #[doc(hidden)]
×
294
            #[allow(non_camel_case_types)]
×
295
            struct #internal_ident;
×
296

297
            impl ::ext_php_rs::internal::function::PhpFunction for #internal_ident {
×
298
                const FUNCTION_ENTRY: fn() -> ::ext_php_rs::builders::FunctionBuilder<'static> = {
×
299
                    fn entry() -> ::ext_php_rs::builders::FunctionBuilder<'static>
×
300
                    {
301
                        #builder
×
302
                    }
303
                    entry
×
304
                };
305
            }
306
        }
307
    }
308

309
    /// Returns a constructor metadata object for this function. This doesn't
310
    /// check if the function is a constructor, however.
311
    pub fn constructor_meta(&self, class: &syn::Path) -> TokenStream {
×
312
        let ident = self.ident;
×
313
        let (required, not_required) = self.args.split_args(self.optional.as_ref());
×
314
        let required_args = required
×
315
            .iter()
316
            .map(TypedArg::arg_builder)
×
317
            .collect::<Vec<_>>();
318
        let not_required_args = not_required
×
319
            .iter()
320
            .map(TypedArg::arg_builder)
×
321
            .collect::<Vec<_>>();
322

323
        let required_arg_names: Vec<_> = required.iter().map(|arg| arg.name).collect();
×
324
        let not_required_arg_names: Vec<_> = not_required.iter().map(|arg| arg.name).collect();
×
325
        let arg_declarations = self
×
326
            .args
×
327
            .typed
×
328
            .iter()
329
            .map(TypedArg::arg_declaration)
×
330
            .collect::<Vec<_>>();
331
        let arg_accessors = self.args.typed.iter().map(|arg| {
×
332
            arg.accessor(
×
333
                |e| quote! { return ::ext_php_rs::class::ConstructorResult::Exception(#e); },
×
334
            )
335
        });
336
        let variadic = self.args.typed.iter().any(|arg| arg.variadic).then(|| {
×
337
            quote! {
×
338
                .variadic()
×
339
            }
340
        });
341
        let docs = &self.docs;
×
342

343
        quote! {
×
344
            ::ext_php_rs::class::ConstructorMeta {
×
345
                constructor: {
×
346
                    fn inner(ex: &mut ::ext_php_rs::zend::ExecuteData) -> ::ext_php_rs::class::ConstructorResult<#class> {
×
347
                        #(#arg_declarations)*
×
348
                        let parse = ex.parser()
×
349
                            #(.arg(&mut #required_arg_names))*
×
350
                            .not_required()
×
351
                            #(.arg(&mut #not_required_arg_names))*
×
352
                            #variadic
×
353
                            .parse();
×
354
                        if parse.is_err() {
×
355
                            return ::ext_php_rs::class::ConstructorResult::ArgError;
×
356
                        }
357
                        #class::#ident(#({#arg_accessors}),*).into()
×
358
                    }
359
                    inner
×
360
                },
361
                build_fn: {
×
362
                    fn inner(func: ::ext_php_rs::builders::FunctionBuilder) -> ::ext_php_rs::builders::FunctionBuilder {
×
363
                        func
×
364
                            .docs(&[#(#docs),*])
×
365
                            #(.arg(#required_args))*
×
366
                            .not_required()
×
367
                            #(.arg(#not_required_args))*
×
368
                            #variadic
×
369
                    }
370
                    inner
×
371
                }
372
            }
373
        }
374
    }
375
}
376

377
#[derive(Debug)]
378
pub struct ReceiverArg {
379
    pub _mutable: bool,
380
    pub span: Span,
381
}
382

383
#[derive(Debug)]
384
pub struct TypedArg<'a> {
385
    pub name: &'a Ident,
386
    pub ty: Type,
387
    pub nullable: bool,
388
    pub default: Option<Expr>,
389
    pub as_ref: bool,
390
    pub variadic: bool,
391
}
392

393
#[derive(Debug)]
394
pub struct Args<'a> {
395
    pub receiver: Option<ReceiverArg>,
396
    pub typed: Vec<TypedArg<'a>>,
397
}
398

399
impl<'a> Args<'a> {
400
    pub fn parse_from_fnargs(
×
401
        args: impl Iterator<Item = &'a FnArg>,
402
        mut defaults: HashMap<Ident, Expr>,
403
    ) -> Result<Self> {
404
        let mut result = Self {
405
            receiver: None,
406
            typed: vec![],
×
407
        };
408
        for arg in args {
×
409
            match arg {
×
410
                FnArg::Receiver(receiver) => {
×
411
                    if receiver.reference.is_none() {
×
412
                        bail!(receiver => "PHP objects are heap-allocated and cannot be passed by value. Try using `&self` or `&mut self`.");
×
413
                    } else if result.receiver.is_some() {
×
414
                        bail!(receiver => "Too many receivers specified.")
×
415
                    }
416
                    result.receiver.replace(ReceiverArg {
×
417
                        _mutable: receiver.mutability.is_some(),
×
418
                        span: receiver.span(),
×
419
                    });
420
                }
421
                FnArg::Typed(PatType { pat, ty, .. }) => {
×
422
                    let syn::Pat::Ident(syn::PatIdent { ident, .. }) = &**pat else {
×
423
                        bail!(pat => "Unsupported argument.");
×
424
                    };
425

426
                    // If the variable is `&[&Zval]` treat it as the variadic argument.
427
                    let default = defaults.remove(ident);
×
428
                    let nullable = type_is_nullable(ty.as_ref(), default.is_some())?;
×
429
                    let (variadic, as_ref, ty) = Self::parse_typed(ty);
×
430
                    result.typed.push(TypedArg {
×
431
                        name: ident,
×
432
                        ty,
×
433
                        nullable,
×
434
                        default,
×
435
                        as_ref,
×
436
                        variadic,
×
437
                    });
438
                }
439
            }
440
        }
441
        Ok(result)
×
442
    }
443

444
    fn parse_typed(ty: &Type) -> (bool, bool, Type) {
×
445
        match ty {
×
446
            Type::Reference(ref_) => {
×
447
                let as_ref = ref_.mutability.is_some();
×
448
                match ref_.elem.as_ref() {
×
449
                    Type::Slice(slice) => (
×
450
                        // TODO: Allow specifying the variadic type.
451
                        slice.elem.to_token_stream().to_string() == "& Zval",
×
452
                        as_ref,
×
453
                        ty.clone(),
×
454
                    ),
455
                    _ => (false, as_ref, ty.clone()),
×
456
                }
457
            }
458
            Type::Path(TypePath { path, .. }) => {
×
459
                let mut as_ref = false;
×
460

461
                // For for types that are `Option<&mut T>` to turn them into
462
                // `Option<&T>`, marking the Arg as as "passed by reference".
463
                let ty = path
×
464
                    .segments
×
465
                    .last()
466
                    .filter(|seg| seg.ident == "Option")
×
467
                    .and_then(|seg| {
×
468
                        if let PathArguments::AngleBracketed(args) = &seg.arguments {
×
469
                            args.args
×
470
                                .iter()
×
471
                                .find(|arg| matches!(arg, GenericArgument::Type(_)))
×
472
                                .and_then(|ga| match ga {
×
473
                                    GenericArgument::Type(ty) => Some(match ty {
×
474
                                        Type::Reference(r) => {
×
475
                                            let mut new_ref = r.clone();
×
476
                                            new_ref.mutability = None;
×
477
                                            as_ref = true;
×
478
                                            Type::Reference(new_ref)
×
479
                                        }
480
                                        _ => ty.clone(),
×
481
                                    }),
482
                                    _ => None,
×
483
                                })
484
                        } else {
485
                            None
×
486
                        }
487
                    })
488
                    .unwrap_or_else(|| ty.clone());
×
489
                (false, as_ref, ty.clone())
×
490
            }
491
            _ => (false, false, ty.clone()),
×
492
        }
493
    }
494

495
    /// Splits the typed arguments into two slices:
496
    ///
497
    /// 1. Required arguments.
498
    /// 2. Non-required arguments.
499
    ///
500
    /// # Parameters
501
    ///
502
    /// * `optional` - The first optional argument. If [`None`], the optional
503
    ///   arguments will be from the first nullable argument after the last
504
    ///   non-nullable argument to the end of the arguments.
505
    pub fn split_args(&self, optional: Option<&Ident>) -> (&[TypedArg<'a>], &[TypedArg<'a>]) {
×
506
        let mut mid = None;
×
507
        for (i, arg) in self.typed.iter().enumerate() {
×
508
            if let Some(optional) = optional {
×
509
                if optional == arg.name {
×
510
                    mid.replace(i);
×
511
                }
512
            } else if mid.is_none() && arg.nullable {
×
513
                mid.replace(i);
×
514
            } else if !arg.nullable {
×
515
                mid.take();
×
516
            }
517
        }
518
        match mid {
×
519
            Some(mid) => (&self.typed[..mid], &self.typed[mid..]),
×
520
            None => (&self.typed[..], &self.typed[0..0]),
×
521
        }
522
    }
523
}
524

525
impl TypedArg<'_> {
526
    /// Returns a 'clean type' with the lifetimes removed. This allows the type
527
    /// to be used outside of the original function context.
528
    fn clean_ty(&self) -> Type {
×
529
        let mut ty = self.ty.clone();
×
530
        ty.drop_lifetimes();
×
531

532
        // Variadic arguments are passed as slices, so we need to extract the
533
        // inner type.
534
        if self.variadic {
×
535
            let Type::Reference(reference) = &ty else {
×
536
                return ty;
×
537
            };
538

539
            if let Type::Slice(inner) = &*reference.elem {
×
540
                return *inner.elem.clone();
×
541
            }
542
        }
543

544
        ty
×
545
    }
546

547
    /// Returns a token stream containing an argument declaration, where the
548
    /// name of the variable holding the arg is the name of the argument.
549
    fn arg_declaration(&self) -> TokenStream {
×
550
        let name = self.name;
×
551
        let val = self.arg_builder();
×
552
        quote! {
×
553
            let mut #name = #val;
554
        }
555
    }
556

557
    /// Returns a token stream containing the `Arg` definition to be passed to
558
    /// `ext-php-rs`.
559
    fn arg_builder(&self) -> TokenStream {
×
560
        let name = self.name.to_string();
×
561
        let ty = self.clean_ty();
×
562
        let null = if self.nullable {
×
563
            Some(quote! { .allow_null() })
×
564
        } else {
565
            None
×
566
        };
567
        let default = self.default.as_ref().map(|val| {
×
568
            let val = val.to_token_stream().to_string();
×
569
            quote! {
×
570
                .default(#val)
571
            }
572
        });
573
        let as_ref = if self.as_ref {
×
574
            Some(quote! { .as_ref() })
×
575
        } else {
576
            None
×
577
        };
578
        let variadic = self.variadic.then(|| quote! { .is_variadic() });
×
579
        quote! {
×
580
            ::ext_php_rs::args::Arg::new(#name, <#ty as ::ext_php_rs::convert::FromZvalMut>::TYPE)
581
                #null
582
                #default
583
                #as_ref
584
                #variadic
585
        }
586
    }
587

588
    /// Get the accessor used to access the value of the argument.
589
    fn accessor(&self, bail_fn: impl Fn(TokenStream) -> TokenStream) -> TokenStream {
×
590
        let name = self.name;
×
591
        if let Some(default) = &self.default {
×
592
            quote! {
×
593
                #name.val().unwrap_or(#default.into())
×
594
            }
595
        } else if self.variadic {
×
596
            quote! {
×
597
                &#name.variadic_vals()
×
598
            }
599
        } else if self.nullable {
×
600
            // Originally I thought we could just use the below case for `null` options, as
601
            // `val()` will return `Option<Option<T>>`, however, this isn't the case when
602
            // the argument isn't given, as the underlying zval is null.
603
            quote! {
×
604
                #name.val()
×
605
            }
606
        } else {
607
            let bail = bail_fn(quote! {
×
608
                ::ext_php_rs::exception::PhpException::default(
×
609
                    concat!("Invalid value given for argument `", stringify!(#name), "`.").into()
×
610
                )
611
            });
612
            quote! {
×
613
                match #name.val() {
×
614
                    Some(val) => val,
×
615
                    None => {
×
616
                        #bail;
×
617
                    }
618
                }
619
            }
620
        }
621
    }
622
}
623

624
/// Returns true of the given type is nullable in PHP.
625
// TODO(david): Eventually move to compile-time constants for this (similar to
626
// FromZval::NULLABLE).
627
pub fn type_is_nullable(ty: &Type, has_default: bool) -> Result<bool> {
×
628
    Ok(match ty {
×
629
        syn::Type::Path(path) => {
×
630
            has_default
×
631
                || path
×
632
                    .path
×
633
                    .segments
×
634
                    .iter()
×
635
                    .next_back()
×
636
                    .is_some_and(|seg| seg.ident == "Option")
×
637
        }
638
        syn::Type::Reference(_) => false, /* Reference cannot be nullable unless */
×
639
        // wrapped in `Option` (in that case it'd be a Path).
640
        _ => bail!(ty => "Unsupported argument type."),
×
641
    })
642
}
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

© 2025 Coveralls, Inc