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

davidcole1340 / ext-php-rs / 16824767628

08 Aug 2025 07:35AM UTC coverage: 27.748% (-0.03%) from 27.778%
16824767628

Pull #542

github

web-flow
Merge 44b890823 into 896cb945d
Pull Request #542: feat: Add constructor visability

5 of 21 new or added lines in 4 files covered. (23.81%)

1 existing line in 1 file now uncovered.

1156 of 4166 relevant lines covered (27.75%)

7.7 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.
NEW
311
    pub fn constructor_meta(
×
312
        &self,
313
        class: &syn::Path,
314
        visibility: Option<&Visibility>,
315
    ) -> TokenStream {
316
        let ident = self.ident;
×
317
        let (required, not_required) = self.args.split_args(self.optional.as_ref());
×
318
        let required_args = required
×
319
            .iter()
320
            .map(TypedArg::arg_builder)
×
321
            .collect::<Vec<_>>();
322
        let not_required_args = not_required
×
323
            .iter()
324
            .map(TypedArg::arg_builder)
×
325
            .collect::<Vec<_>>();
326

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

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

383
#[derive(Debug)]
384
pub struct ReceiverArg {
385
    pub _mutable: bool,
386
    pub span: Span,
387
}
388

389
#[derive(Debug)]
390
pub struct TypedArg<'a> {
391
    pub name: &'a Ident,
392
    pub ty: Type,
393
    pub nullable: bool,
394
    pub default: Option<Expr>,
395
    pub as_ref: bool,
396
    pub variadic: bool,
397
}
398

399
#[derive(Debug)]
400
pub struct Args<'a> {
401
    pub receiver: Option<ReceiverArg>,
402
    pub typed: Vec<TypedArg<'a>>,
403
}
404

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

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

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

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

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

531
impl TypedArg<'_> {
532
    /// Returns a 'clean type' with the lifetimes removed. This allows the type
533
    /// to be used outside of the original function context.
534
    fn clean_ty(&self) -> Type {
×
535
        let mut ty = self.ty.clone();
×
536
        ty.drop_lifetimes();
×
537

538
        // Variadic arguments are passed as slices, so we need to extract the
539
        // inner type.
540
        if self.variadic {
×
541
            let Type::Reference(reference) = &ty else {
×
542
                return ty;
×
543
            };
544

545
            if let Type::Slice(inner) = &*reference.elem {
×
546
                return *inner.elem.clone();
547
            }
548
        }
549

550
        ty
×
551
    }
552

553
    /// Returns a token stream containing an argument declaration, where the
554
    /// name of the variable holding the arg is the name of the argument.
555
    fn arg_declaration(&self) -> TokenStream {
×
556
        let name = self.name;
×
557
        let val = self.arg_builder();
×
558
        quote! {
×
559
            let mut #name = #val;
560
        }
561
    }
562

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

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

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