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

davidcole1340 / ext-php-rs / 15650816286

14 Jun 2025 09:51AM CUT coverage: 21.105%. Remained the same
15650816286

Pull #450

github

web-flow
Merge cdc580976 into 1db8863be
Pull Request #450: test: improve test reliability and ease of use

829 of 3928 relevant lines covered (21.1%)

2.06 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, 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.rename.rename(input.sig.ident.to_string()),
×
50
        args,
×
51
        php_attr.optional,
×
52
        docs,
×
53
    );
54
    let function_impl = func.php_function_impl();
×
55

56
    Ok(quote! {
×
57
        #input
×
58
        #function_impl
×
59
    })
60
}
61

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

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

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

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

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

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

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

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

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

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

175
                        #(#arg_declarations)*
×
176
                        let result = {
×
177
                            #result
×
178
                        };
179

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

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

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

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

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

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

278
                    #call
×
279
                }
280
            }
281
        }
282
    }
283

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

289
        quote! {
×
290
            #[doc(hidden)]
×
291
            #[allow(non_camel_case_types)]
×
292
            struct #internal_ident;
×
293

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

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

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

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

372
#[derive(Debug)]
373
pub struct ReceiverArg {
374
    pub _mutable: bool,
375
    pub span: Span,
376
}
377

378
#[derive(Debug)]
379
pub struct TypedArg<'a> {
380
    pub name: &'a Ident,
381
    pub ty: Type,
382
    pub nullable: bool,
383
    pub default: Option<Expr>,
384
    pub as_ref: bool,
385
    pub variadic: bool,
386
}
387

388
#[derive(Debug)]
389
pub struct Args<'a> {
390
    pub receiver: Option<ReceiverArg>,
391
    pub typed: Vec<TypedArg<'a>>,
392
}
393

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

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

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

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

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

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

527
        // Variadic arguments are passed as slices, so we need to extract the
528
        // inner type.
529
        if self.variadic {
×
530
            let Type::Reference(reference) = &ty else {
×
531
                return ty;
×
532
            };
533

534
            if let Type::Slice(inner) = &*reference.elem {
×
535
                return *inner.elem.clone();
×
536
            }
537
        }
538

539
        ty
×
540
    }
541

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

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

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

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