ext-php-rs-derive 0.13.0

Derive macros for ext-php-rs.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
//! Implementation for the `#[php_impl_interface]` macro.
//!
//! This macro allows classes to implement PHP interfaces by implementing Rust
//! traits that are marked with `#[php_interface]`.
//!
//! Uses the `inventory` crate for cross-crate interface discovery.
//! Method registration uses autoref specialization to avoid PHP symbol
//! resolution issues at binary load time.

use darling::FromMeta;
use darling::util::SpannedValue;
use proc_macro2::TokenStream;
use quote::{format_ident, quote};
use syn::spanned::Spanned as _;
use syn::{FnArg, ImplItem, ItemImpl, Pat, ReturnType};

use crate::function::{extract_call, invalid_argument, new_holder};
use crate::interface::{method_name_const, method_sensitive_const};
use crate::parsing::{RenameRule, ident_to_php_name, reject_php_attrs};
use crate::prelude::*;
use crate::syn_ext::DropLifetimes;

/// Attributes for the `#[php_impl_interface]` macro.
#[derive(FromMeta, Default, Debug)]
#[darling(default)]
pub struct PhpImplInterfaceArgs {
    /// Removed: method names come from the `#[php_interface]` trait.
    change_method_case: Option<SpannedValue<RenameRule>>,
}

const INTERNAL_INTERFACE_NAME_PREFIX: &str = "PhpInterface";

/// Parses a trait impl block and generates the interface implementation
/// registration.
///
/// # Arguments
///
/// * `args` - The macro arguments. None are accepted.
/// * `input` - The trait impl block (e.g., `impl SomeTrait for SomeStruct { ...
///   }`)
///
/// # Generated Code
///
/// The macro generates:
/// 1. The original trait impl block (passed through unchanged)
/// 2. An `inventory::submit!` call to register the interface implementation
/// 3. An `InterfaceMethodsProvider` trait implementation for method
///    registration
///
/// # Path Resolution
///
/// The macro preserves the full module path of the trait, so
/// `impl other::MyTrait for Foo` will correctly reference
/// `other::PhpInterfaceMyTrait`.
pub fn parser(args: &PhpImplInterfaceArgs, input: &ItemImpl) -> Result<TokenStream> {
    if let Some(change_method_case) = &args.change_method_case {
        bail!(change_method_case.span() => "`change_method_case` is not accepted here; method names come from the `#[php_interface]` trait.");
    }
    // Extract the trait being implemented
    let Some((trait_path, _)) = &input.trait_ else {
        bail!(input => "`#[php_impl_interface]` can only be used on trait implementations (e.g., `impl SomeTrait for SomeStruct`)");
    };

    // Clone the trait path and modify the last segment to add PhpInterface
    // prefix
    let mut interface_struct_path = trait_path.clone();
    match interface_struct_path.segments.last_mut() {
        Some(segment) => {
            segment.ident = format_ident!("{}{}", INTERNAL_INTERFACE_NAME_PREFIX, segment.ident);
        }
        None => {
            bail!(trait_path => "Invalid trait path");
        }
    }

    // Get the struct type being implemented
    let struct_ty = &input.self_ty;

    reject_php_attrs(
        &input.attrs,
        "`#[php_impl_interface]` blocks; pass them as macro arguments instead",
    )?;

    // Generate method builders for each trait method
    let mut method_builders = Vec::new();

    for item in &input.items {
        let attrs = match item {
            ImplItem::Fn(method) => &method.attrs,
            ImplItem::Const(c) => &c.attrs,
            ImplItem::Type(t) => &t.attrs,
            _ => continue,
        };
        reject_php_attrs(attrs, "`#[php_impl_interface]` items")?;
        let ImplItem::Fn(method) = item else {
            continue;
        };
        let method_ident = &method.sig.ident;
        let name_const = method_name_const(method_ident);
        let php_name = quote! { <#interface_struct_path>::#name_const };
        let sensitive_const = method_sensitive_const(method_ident);
        let sensitive = quote! { <#interface_struct_path>::#sensitive_const };

        // Check if this is a static method (no self receiver)
        let has_self = method
            .sig
            .inputs
            .iter()
            .any(|arg| matches!(arg, FnArg::Receiver(_)));
        let is_static = !has_self;

        // Generate the method builder
        let builder = generate_method_builder(
            &php_name,
            &sensitive,
            struct_ty,
            method_ident,
            &method.sig.inputs,
            &method.sig.output,
            is_static,
        );
        method_builders.push(builder);
    }

    Ok(quote! {
        // Pass through the original trait implementation
        #input

        // Register the interface implementation using inventory for cross-crate discovery
        ::ext_php_rs::inventory::submit! {
            ::ext_php_rs::internal::class::InterfaceRegistration {
                class_type_id: ::std::any::TypeId::of::<#struct_ty>(),
                interface_getter: || (
                    || <#interface_struct_path as ::ext_php_rs::class::RegisteredClass>::get_metadata().ce(),
                    <#interface_struct_path as ::ext_php_rs::class::RegisteredClass>::CLASS_NAME
                ),
            }
        }

        // Implement InterfaceMethodsProvider for the class (direct impl, not on reference)
        // This uses autoref specialization - the direct impl takes precedence over the
        // default reference impl.
        impl ::ext_php_rs::internal::class::InterfaceMethodsProvider<#struct_ty>
            for ::ext_php_rs::internal::class::PhpClassImplCollector<#struct_ty>
        {
            fn get_interface_methods(self) -> ::std::vec::Vec<(
                ::ext_php_rs::builders::FunctionBuilder<'static>,
                ::ext_php_rs::flags::MethodFlags,
            )> {
                vec![
                    #(#method_builders),*
                ]
            }
        }
    })
}

/// Generates a method builder expression (`FunctionBuilder`, `MethodFlags`).
/// The handler is defined inside the `FunctionBuilder::new()` call, so it's
/// only instantiated when `get_interface_methods()` is called at runtime.
#[allow(clippy::too_many_lines)]
fn generate_method_builder(
    php_name: &TokenStream,
    sensitive: &TokenStream,
    struct_ty: &syn::Type,
    method_ident: &syn::Ident,
    inputs: &syn::punctuated::Punctuated<FnArg, syn::token::Comma>,
    output: &ReturnType,
    is_static: bool,
) -> TokenStream {
    let receiver_mut = inputs
        .iter()
        .any(|arg| matches!(arg, FnArg::Receiver(receiver) if matches!(receiver.kind, syn::ReceiverKind::Reference(_, _, Some(_)))));
    let guard = crate::function::payload_guard(&quote! { this }, receiver_mut);

    // Collect non-self arguments in order
    let typed_args = inputs.iter().filter_map(|arg| match arg {
        FnArg::Typed(pat_type) => Some(pat_type),
        FnArg::Receiver(_) => None,
    });
    let positioned_args: Vec<_> = typed_args
        .enumerate()
        .filter_map(|(position, pat_type)| match &*pat_type.pat {
            Pat::Ident(pat_ident) => {
                let mut ty = (*pat_type.ty).clone();
                ty.drop_lifetimes();
                let span = pat_type.ty.span();
                let holder = new_holder(&ty, span);
                Some((position, (&pat_ident.ident, ty, holder, span)))
            }
            _ => None,
        })
        .collect();
    let args: Vec<_> = positioned_args.iter().map(|(_, arg)| arg).collect();

    // The required count follows each parameter's `FunctionArgument::NULLABLE`,
    // so an alias of `Option<T>` behaves like `Option<T>`. An `Option<T>`
    // before a required parameter stays required.
    let omittable = args
        .iter()
        .map(|(_, ty, _, _)| quote! { ::ext_php_rs::internal::argument::nullable::<#ty, _>() });
    let required = quote! {
        const __REQUIRED: usize = ::ext_php_rs::args::required_count(&[#(#omittable),*]);
    };

    let arg_declarations: Vec<_> = args
        .iter()
        .map(|(name, ty, new_holder, _)| {
            let php_name = ident_to_php_name(name);
            let holder = format_ident!("__holder_{}", name);
            quote! {
                let mut #name = ::ext_php_rs::internal::argument::arg::<#ty, _>(#php_name);
                #[allow(non_snake_case)]
            let mut #holder = #new_holder;
            }
        })
        .collect();

    let arg_names: Vec<_> = args.iter().map(|(name, _, _, _)| name).collect();

    // Value accessors that extract values from the Arg objects after parsing.
    // An omitted argument takes `FunctionArgument::missing()`.
    let arg_value_accessors: Vec<_> = args
        .iter()
        .map(|(name, ty, _, span)| {
            let invalid = invalid_argument(name);
            let holder = format_ident!("__holder_{}", name);
            let extract = extract_call(ty, *span, &quote! { zval.dereference_mut() }, &holder);
            let php_name = ident_to_php_name(name);
            quote! {
                let #name: #ty = match #name.zval() {
                    Some(zval) => match #extract {
                        Ok(value) => value,
                        Err(error) => {
                            ::ext_php_rs::internal::argument::argument_error(#php_name, &error).throw();
                            return;
                        }
                    },
                    None => match ::ext_php_rs::internal::argument::missing::<#ty, _>() {
                        Some(value) => value,
                        None => {
                            #invalid.throw();
                            return;
                        }
                    },
                };
            }
        })
        .collect();

    // Generate .arg() calls for PHP reflection metadata (for FunctionBuilder)
    let arg_builders: Vec<_> = positioned_args
        .iter()
        .map(|(position, (name, ty, _, _))| {
            let php_name = ident_to_php_name(name);
            quote! {
                .arg({
                    let arg = ::ext_php_rs::internal::argument::arg::<#ty, _>(#php_name);
                    if #sensitive.contains(&#position) {
                        arg.sensitive()
                    } else {
                        arg
                    }
                })
            }
        })
        .collect();

    let flags = if is_static {
        quote! { ::ext_php_rs::flags::MethodFlags::Public | ::ext_php_rs::flags::MethodFlags::Static }
    } else {
        quote! { ::ext_php_rs::flags::MethodFlags::Public }
    };

    // Generate the .returns() call - void for no return type, or the actual
    // type
    let returns_call = match output {
        ReturnType::Default => quote! {
            .returns(::ext_php_rs::flags::DataType::Void, false, false)
        },
        ReturnType::Type(_, ty) => {
            quote! {
                .returns(
                    <#ty as ::ext_php_rs::convert::IntoZval>::TYPE,
                    false,
                    <#ty as ::ext_php_rs::convert::IntoZval>::NULLABLE,
                )
            }
        }
    };

    // Check if return type is void
    let is_void = matches!(output, ReturnType::Default);

    // Generate the method call and result handling based on whether it's void
    let result_handling = if is_void {
        quote! {
            // Void method - just call it, don't try to set return value
        }
    } else {
        quote! {
            if let Err(e) = result.set_zval(retval, false) {
                let e: ::ext_php_rs::exception::PhpException = e.into();
                e.throw();
            }
        }
    };

    let handler_body = if is_static {
        if is_void {
            quote! {
                #(#arg_declarations)*
                let parse = ex.parser()
                    #(.arg(&mut #arg_names))*
                    .required_args(__REQUIRED)
                    .parse();
                if parse.is_err() {
                    return;
                }
                #(#arg_value_accessors)*
                <#struct_ty>::#method_ident(#(#arg_names),*);
            }
        } else {
            quote! {
                #(#arg_declarations)*
                let parse = ex.parser()
                    #(.arg(&mut #arg_names))*
                    .required_args(__REQUIRED)
                    .parse();
                if parse.is_err() {
                    return;
                }
                #(#arg_value_accessors)*
                let result = <#struct_ty>::#method_ident(#(#arg_names),*);
                #result_handling
            }
        }
    } else if is_void {
        quote! {
            let (parse, this) = ex.parser_method::<#struct_ty>();
            let this = match this {
                Some(this) => this,
                None => {
                    ::ext_php_rs::exception::PhpException::from_message("Failed to get $this".into())
                        .throw();
                    return;
                }
            };
            #guard
            #(#arg_declarations)*
            let parse_result = parse
                #(.arg(&mut #arg_names))*
                .required_args(__REQUIRED)
                .parse();
            if parse_result.is_err() {
                return;
            }
            #(#arg_value_accessors)*
            __payload.#method_ident(#(#arg_names),*);
        }
    } else {
        quote! {
            let (parse, this) = ex.parser_method::<#struct_ty>();
            let this = match this {
                Some(this) => this,
                None => {
                    ::ext_php_rs::exception::PhpException::from_message("Failed to get $this".into())
                        .throw();
                    return;
                }
            };
            #guard
            #(#arg_declarations)*
            let parse_result = parse
                #(.arg(&mut #arg_names))*
                .required_args(__REQUIRED)
                .parse();
            if parse_result.is_err() {
                return;
            }
            #(#arg_value_accessors)*
            let result = __payload.#method_ident(#(#arg_names),*);
            #result_handling
        }
    };

    quote! {
        ({
            #required
            ::ext_php_rs::builders::FunctionBuilder::new(#php_name, {
                ::ext_php_rs::zend_fastcall! {
                    extern fn handler(
                        ex: &mut ::ext_php_rs::zend::ExecuteData,
                        retval: &mut ::ext_php_rs::types::Zval,
                    ) {
                        use ::ext_php_rs::convert::IntoZval;

                        ::ext_php_rs::zend::run_handler(::std::panic::AssertUnwindSafe(|| {
                            #handler_body
                        }));
                    }
                }
                handler
            })
            #(#arg_builders)*
            .required_args(__REQUIRED)
            #returns_call
        },
            #flags
        )
    }
}