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

davidcole1340 / ext-php-rs / 15331766277

29 May 2025 07:22PM CUT coverage: 20.798% (-0.1%) from 20.927%
15331766277

Pull #436

github

Xenira
chore(macro)!: change rename defaults to match psr

BREAKING CHANGE: Methods and Properties are renamed to camelCase by default. Classes to PascalCase and constants to UPPER_CASE.

Refs: #189
Pull Request #436: chore(macro)!: change rename defaults to match psr

8 of 29 new or added lines in 5 files covered. (27.59%)

2 existing lines in 2 files now uncovered.

818 of 3933 relevant lines covered (20.8%)

2.05 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,
×
NEW
49
        php_attr
×
NEW
50
            .rename
×
NEW
51
            .rename(input.sig.ident.to_string(), RenameRule::Camel),
×
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.as_ref().map(|output| {
×
200
            quote! {
×
201
                .returns(
×
202
                    <#output as ::ext_php_rs::convert::IntoZval>::TYPE,
×
203
                    false,
×
204
                    <#output as ::ext_php_rs::convert::IntoZval>::NULLABLE,
×
205
                )
206
            }
207
        })
208
    }
209

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

541
        ty
×
542
    }
543

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

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

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

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