ext-php-rs-derive 0.12.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
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
use darling::FromAttributes;
use darling::util::{Flag, SpannedValue};
use proc_macro2::TokenStream;
use quote::quote;
use std::collections::{BTreeSet, HashMap};
use syn::{Expr, Ident, ItemImpl};

use crate::constant::PhpConstAttribute;
use crate::function::{Args, CallType, Function, MethodReceiver};
use crate::helpers::get_docs;
use crate::parsing::{
    NameSet, PhpNameContext, PhpRename, RenameRule, Visibility, ident_to_php_name,
    reject_php_attrs, validate_php_name,
};
use crate::prelude::*;

/// Method types.
#[derive(Debug)]
enum MethodTy {
    /// Regular PHP method.
    Normal,
    /// Constructor method.
    Constructor,
    /// Property getter method.
    Getter,
    /// Property setter method.
    Setter,
    /// Abstract method.
    Abstract,
}

#[derive(FromAttributes, Debug, Default)]
#[darling(attributes(php), default)]
pub struct PhpImpl {
    /// Rename methods to match the given rule.
    change_method_case: Option<RenameRule>,
    /// Rename constants to match the given rule.
    change_constant_case: Option<RenameRule>,
}

pub fn parser(mut input: ItemImpl) -> Result<TokenStream> {
    let args = PhpImpl::from_attributes(&input.attrs)?;
    input.attrs.retain(|attr| !attr.path().is_ident("php"));
    let path = match &*input.self_ty {
        syn::Type::Path(ty) => &ty.path,
        _ => {
            bail!(input.self_ty => "The `#[php_impl]` attribute is only valid for struct implementations.")
        }
    };

    let mut parsed = ParsedImpl::new(
        path,
        args.change_method_case.unwrap_or(RenameRule::Camel),
        args.change_constant_case
            .unwrap_or(RenameRule::ScreamingSnake),
    );
    parsed.parse(input.items.iter_mut())?;

    let php_class_impl = parsed.generate_php_class_impl();
    Ok(quote::quote! {
        #input
        #php_class_impl
    })
}

/// Arguments applied to methods.
#[derive(Debug)]
struct MethodArgs {
    /// Method name. Only applies to PHP (not the Rust method name).
    name: String,
    /// The first optional argument of the function signature.
    optional: Option<Ident>,
    /// Default values for optional arguments.
    defaults: HashMap<Ident, Expr>,
    /// Visibility of the method (public, protected, private).
    vis: Visibility,
    /// Span of the explicit `vis` option, when given.
    vis_span: Option<proc_macro2::Span>,
    /// Method type.
    ty: MethodTy,
    /// Whether this is a final method.
    is_final: bool,
}

#[derive(FromAttributes, Default, Debug)]
#[darling(default, attributes(php), forward_attrs(doc))]
pub struct PhpFunctionImplAttribute {
    #[darling(flatten)]
    rename: PhpRename,
    defaults: HashMap<Ident, Expr>,
    optional: Option<Ident>,
    vis: Option<SpannedValue<Visibility>>,
    attrs: Vec<syn::Attribute>,
    getter: Flag,
    setter: Flag,
    constructor: Flag,
    #[darling(rename = "abstract")]
    abstract_method: Flag,
    #[darling(rename = "final")]
    final_method: Flag,
}

impl MethodArgs {
    #[allow(clippy::similar_names)]
    fn new(name: String, attr: PhpFunctionImplAttribute) -> Result<Self> {
        let is_constructor = name == "__construct" || attr.constructor.is_present();
        let is_getter = attr.getter.is_present();
        let is_setter = attr.setter.is_present();
        let is_abstract = attr.abstract_method.is_present();
        let is_final = attr.final_method.is_present();

        let abstract_span = attr.abstract_method.span();
        let final_span = attr.final_method.span();
        if is_getter && is_setter {
            bail!(attr.setter.span() => "A method cannot be both a getter and a setter.");
        }
        if is_constructor {
            if is_abstract {
                bail!(abstract_span => "Constructors cannot be abstract.");
            }
            if is_final {
                bail!(final_span => "Constructors cannot be final.");
            }
        }
        if is_getter {
            if is_abstract {
                bail!(abstract_span => "Getters cannot be abstract.");
            }
            if is_final {
                bail!(final_span => "Getters cannot be final.");
            }
        }
        if is_setter {
            if is_abstract {
                bail!(abstract_span => "Setters cannot be abstract.");
            }
            if is_final {
                bail!(final_span => "Setters cannot be final.");
            }
        }
        if is_abstract {
            if is_final {
                bail!(final_span => "Methods cannot be both abstract and final.");
            }
            if let Some(vis) = attr.vis.filter(|vis| **vis == Visibility::Private) {
                bail!(vis.span() => "Abstract methods cannot be private.");
            }
        }

        let ty = if is_constructor {
            MethodTy::Constructor
        } else if is_getter {
            MethodTy::Getter
        } else if is_setter {
            MethodTy::Setter
        } else if is_abstract {
            MethodTy::Abstract
        } else {
            MethodTy::Normal
        };
        if let Some(kind) = match ty {
            MethodTy::Getter => Some("Getters"),
            MethodTy::Setter => Some("Setters"),
            _ => None,
        } {
            let mut keys: Vec<&Ident> = attr.defaults.keys().collect();
            keys.sort();
            if let Some(key) = keys.first() {
                bail!(key => "{kind} cannot have `defaults`; they map to a PHP property.");
            }
            if let Some(optional) = &attr.optional {
                bail!(optional => "{kind} cannot have `optional`; they map to a PHP property.");
            }
        }

        Ok(Self {
            name,
            optional: attr.optional,
            defaults: attr.defaults,
            vis_span: attr.vis.as_ref().map(SpannedValue::span),
            vis: attr.vis.map_or(Visibility::Public, |vis| *vis),
            ty,
            is_final,
        })
    }
}

/// A PHP property backed by getter and/or setter methods, in declaration order.
#[derive(Debug)]
struct PropGroup<'a> {
    /// Property name in PHP (e.g., "name" for `get_name`/`set_name`).
    name: String,
    getter: Option<&'a syn::Ident>,
    setter: Option<&'a syn::Ident>,
    /// Visibility of the property.
    vis: Visibility,
    /// Documentation comments for the property.
    docs: Vec<String>,
    value_ty: Option<&'a syn::Type>,
}

#[derive(Debug)]
struct ParsedImpl<'a> {
    path: &'a syn::Path,
    change_method_case: RenameRule,
    change_constant_case: RenameRule,
    functions: Vec<FnBuilder>,
    constructor: Option<(Function<'a>, Option<Visibility>)>,
    constants: Vec<Constant<'a>>,
    has_abstract_methods: bool,
    /// Properties backed by getter/setter methods, in declaration order.
    properties: Vec<PropGroup<'a>>,
    method_names: NameSet,
    constant_names: NameSet,
}

#[derive(Debug, Eq, Ord, PartialEq, PartialOrd)]
pub enum MethodModifier {
    Abstract,
    Static,
    Final,
}

impl quote::ToTokens for MethodModifier {
    fn to_tokens(&self, tokens: &mut TokenStream) {
        match *self {
            Self::Abstract => quote! { ::ext_php_rs::flags::MethodFlags::Abstract },
            Self::Static => quote! { ::ext_php_rs::flags::MethodFlags::Static },
            Self::Final => quote! { ::ext_php_rs::flags::MethodFlags::Final },
        }
        .to_tokens(tokens);
    }
}

#[derive(Debug)]
pub struct FnBuilder {
    /// Tokens which represent the `FunctionBuilder` for this function.
    pub builder: TokenStream,
    /// The visibility of this method.
    pub vis: Visibility,
    /// Whether this method is abstract.
    pub modifiers: BTreeSet<MethodModifier>,
}

#[derive(Debug)]
pub struct Constant<'a> {
    /// Name of the constant in PHP land.
    pub name: String,
    /// Identifier of the constant in Rust land.
    pub ident: &'a syn::Ident,
    /// Documentation for the constant.
    pub docs: Vec<String>,
    /// PHP visibility of the constant.
    pub vis: Visibility,
}

impl<'a> ParsedImpl<'a> {
    /// Create a new, empty parsed impl block.
    ///
    /// # Parameters
    ///
    /// * `path` - Path of the type the `impl` block is for.
    /// * `rename_methods` - Rule to rename methods with.
    /// * `rename_constants` - Rule to rename constants with.
    fn new(path: &'a syn::Path, rename_methods: RenameRule, rename_constants: RenameRule) -> Self {
        Self {
            path,
            change_method_case: rename_methods,
            change_constant_case: rename_constants,
            functions: Vec::default(),
            constructor: Option::default(),
            constants: Vec::default(),
            has_abstract_methods: false,
            properties: Vec::default(),
            method_names: NameSet::case_insensitive(),
            constant_names: NameSet::case_sensitive(),
        }
    }

    fn parse_property_method(
        &mut self,
        method: &'a syn::ImplItemFn,
        opts: &MethodArgs,
        rename: &PhpRename,
        docs: Vec<String>,
    ) -> Result<()> {
        let is_getter = matches!(opts.ty, MethodTy::Getter);
        let method_name = ident_to_php_name(&method.sig.ident);
        let prefix = if is_getter { "get_" } else { "set_" };
        let prop_name = rename.rename(
            method_name.strip_prefix(prefix).unwrap_or(&method_name),
            RenameRule::Camel,
        );
        validate_php_name(
            &prop_name,
            PhpNameContext::Property,
            method.sig.ident.span(),
        )?;

        let value_ty = match (is_getter, &method.sig.output) {
            (true, syn::ReturnType::Type(_, ty)) => Some(ty.as_ref()),
            (false, _) => method.sig.inputs.iter().nth(1).and_then(|arg| match arg {
                syn::FnArg::Typed(pat) => Some(pat.ty.as_ref()),
                syn::FnArg::Receiver(_) => None,
            }),
            _ => None,
        };

        let idx = self
            .properties
            .iter()
            .position(|g| g.name == prop_name)
            .unwrap_or_else(|| {
                self.properties.push(PropGroup {
                    name: prop_name,
                    getter: None,
                    setter: None,
                    vis: opts.vis,
                    docs: Vec::new(),
                    value_ty: None,
                });
                self.properties.len() - 1
            });
        let group = &mut self.properties[idx];
        let kind = if is_getter { "getter" } else { "setter" };
        let slot = if is_getter {
            &mut group.getter
        } else {
            &mut group.setter
        };
        if slot.is_some() {
            bail!(method.sig.ident => "Property `{}` already has a {kind}.", group.name);
        }
        if group.vis != opts.vis {
            let span = opts.vis_span.unwrap_or_else(|| method.sig.ident.span());
            bail!(span => "The getter and setter of property `{}` must have the same visibility.", group.name);
        }
        *slot = Some(&method.sig.ident);
        if (is_getter && value_ty.is_some()) || group.value_ty.is_none() {
            group.value_ty = value_ty;
        }
        if (is_getter && !docs.is_empty()) || group.docs.is_empty() {
            group.docs = docs;
        }
        Ok(())
    }

    /// Parses an impl block from `items`, populating `self`.
    fn parse(&mut self, items: impl Iterator<Item = &'a mut syn::ImplItem>) -> Result<()> {
        for items in items {
            match items {
                syn::ImplItem::Const(c) => {
                    let attr = PhpConstAttribute::from_attributes(&c.attrs)?;
                    let name = attr
                        .rename
                        .rename(ident_to_php_name(&c.ident), self.change_constant_case);
                    validate_php_name(&name, PhpNameContext::Constant, c.ident.span())?;
                    if self.constant_names.insert(&name).is_err() {
                        bail!(c.ident => "PHP constant `{name}` is already declared in this block. Rename one of them with `#[php(name = \"...\")]`.");
                    }
                    let docs = get_docs(&attr.attrs)?;
                    c.attrs.retain(|attr| !attr.path().is_ident("php"));

                    self.constants.push(Constant {
                        name,
                        ident: &c.ident,
                        docs,
                        vis: attr.vis.map_or(Visibility::Public, |vis| *vis),
                    });
                }
                syn::ImplItem::Fn(method) => {
                    let mut attr = PhpFunctionImplAttribute::from_attributes(&method.attrs)?;
                    let name = attr.rename.rename_method(
                        ident_to_php_name(&method.sig.ident),
                        self.change_method_case,
                    );
                    validate_php_name(&name, PhpNameContext::Method, method.sig.ident.span())?;
                    let docs = get_docs(&attr.attrs)?;
                    method.attrs.retain(|attr| !attr.path().is_ident("php"));

                    let rename = std::mem::take(&mut attr.rename);
                    let opts = MethodArgs::new(name, attr)?;

                    // Handle getter/setter methods
                    if matches!(opts.ty, MethodTy::Getter | MethodTy::Setter) {
                        self.parse_property_method(method, &opts, &rename, docs)?;
                        continue;
                    }

                    let php_name = if matches!(opts.ty, MethodTy::Constructor) {
                        "__construct"
                    } else {
                        opts.name.as_str()
                    };
                    if let Err(earlier) = self.method_names.insert(php_name) {
                        bail!(method.sig.ident => "PHP method `{php_name}` is already declared as `{earlier}` in this block. PHP method names ignore case. Rename one of them with `#[php(name = \"...\")]`.");
                    }

                    let is_constructor = matches!(opts.ty, MethodTy::Constructor);
                    let mut args =
                        Args::parse_from_fnargs(method.sig.inputs.iter(), opts.defaults)?;
                    let receiver = if args.receiver.is_some() {
                        MethodReceiver::Class
                    } else if !is_constructor && args.take_self_object()? {
                        MethodReceiver::ZendClassObject
                    } else {
                        MethodReceiver::Static
                    };
                    let func = Function::new(&method.sig, opts.name, args, opts.optional, docs)?;

                    let mut modifiers: BTreeSet<MethodModifier> = BTreeSet::new();

                    if is_constructor {
                        if self.constructor.replace((func, opts.vis.into())).is_some() {
                            bail!(method => "Only one constructor can be provided per class.");
                        }
                    } else {
                        if matches!(receiver, MethodReceiver::Static) {
                            modifiers.insert(MethodModifier::Static);
                        }
                        let call_type = CallType::Method {
                            class: self.path,
                            receiver,
                        };
                        let is_abstract = matches!(opts.ty, MethodTy::Abstract);
                        if is_abstract {
                            modifiers.insert(MethodModifier::Abstract);
                            self.has_abstract_methods = true;
                        }
                        if opts.is_final {
                            modifiers.insert(MethodModifier::Final);
                        }

                        // Abstract methods use a different builder that doesn't
                        // generate a handler
                        let builder = if is_abstract {
                            func.abstract_function_builder()
                        } else {
                            func.function_builder(&call_type)
                        };

                        self.functions.push(FnBuilder {
                            builder,
                            vis: opts.vis,
                            modifiers,
                        });
                    }
                }
                syn::ImplItem::Type(t) => {
                    reject_php_attrs(&t.attrs, "associated types")?;
                }
                _ => {}
            }
        }
        Ok(())
    }

    /// Generates an `impl PhpClassImpl<Self> for PhpClassImplCollector<Self>`
    /// block.
    #[allow(clippy::too_many_lines)]
    fn generate_php_class_impl(&self) -> TokenStream {
        let path = &self.path;
        let functions = &self.functions;
        let constructor = self
            .constructor
            .as_ref()
            .map(|(func, vis)| func.constructor_meta(self.path, vis.as_ref()))
            .option_tokens();
        let constants = self.constants.iter().map(|c| {
            let name = &c.name;
            let ident = c.ident;
            let docs = &c.docs;
            let flags = c
                .vis
                .flag_tokens(&quote! { ::ext_php_rs::flags::ConstantFlags });
            quote! {
                (#name, &#path::#ident, &[#(#docs),*], #flags)
            }
        });

        // Compile-time check: abstract methods can only be in abstract classes
        let abstract_check = if self.has_abstract_methods {
            quote! {
                const _: () = assert!(
                    <#path as ::ext_php_rs::class::RegisteredClass>::FLAGS
                        .contains(::ext_php_rs::flags::ClassFlags::Abstract),
                    "Abstract methods can only be defined in abstract classes. \
                     Add `#[php(flags = ClassFlags::Abstract)]` to the class definition."
                );
            }
        } else {
            quote! {}
        };

        // Generate static PropertyDescriptor entries for method properties.
        // Each getter/setter pair gets wrapper fn pointers and a descriptor.
        let method_prop_data: Vec<(Vec<TokenStream>, TokenStream)> = self
            .properties
            .iter()
            .enumerate()
            .map(|(i, group)| {
                let prop_name = &group.name;
                let flags = match group.vis {
                    Visibility::Public => quote! { ::ext_php_rs::flags::PropertyFlags::Public },
                    Visibility::Protected => {
                        quote! { ::ext_php_rs::flags::PropertyFlags::Protected }
                    }
                    Visibility::Private => quote! { ::ext_php_rs::flags::PropertyFlags::Private },
                };
                let docs = &group.docs;
                let readonly = group.getter.is_some() && group.setter.is_none();
                let type_tokens = group.value_ty.map_or_else(
                    || {
                        quote! {
                            ty: ::ext_php_rs::flags::DataType::Mixed,
                            nullable: false,
                        }
                    },
                    |vty| {
                        quote! {
                            ty: <#vty as ::ext_php_rs::convert::IntoZval>::TYPE,
                            nullable: <#vty as ::ext_php_rs::convert::IntoZval>::NULLABLE,
                        }
                    },
                );

                let mut fn_defs = Vec::new();

                // Generate getter wrapper
                let getter_ref = if let Some(getter_ident) = group.getter {
                    let getter_fn_name =
                        syn::Ident::new(&format!("__method_get_{i}"), getter_ident.span());
                    fn_defs.push(quote! {
                        fn #getter_fn_name(
                            this: &#path,
                            __zv: &mut ::ext_php_rs::types::Zval,
                        ) -> ::ext_php_rs::exception::PhpResult {
                            use ::ext_php_rs::convert::IntoZval as _;
                            let value = #path::#getter_ident(this);
                            value.set_zval(__zv, false)
                                .map_err(|e| format!("Failed to return property value: {e:?}"))?;
                            Ok(())
                        }
                    });
                    quote! { ::std::option::Option::Some(#getter_fn_name) }
                } else {
                    quote! { ::std::option::Option::None }
                };

                // Generate setter wrapper
                let setter_ref = if let Some(setter_ident) = group.setter {
                    let setter_fn_name =
                        syn::Ident::new(&format!("__method_set_{i}"), setter_ident.span());
                    if let Some(vty) = group.value_ty {
                        fn_defs.push(quote! {
                            fn #setter_fn_name(
                                this: &mut #path,
                                __zv: &::ext_php_rs::types::Zval,
                            ) -> ::ext_php_rs::exception::PhpResult {
                                use ::ext_php_rs::convert::FromZval as _;
                                let val = <#vty as ::ext_php_rs::convert::FromZval>::from_zval(__zv)
                                    .ok_or("Unable to convert property value into required type.")?;
                                #path::#setter_ident(this, val);
                                Ok(())
                            }
                        });
                    } else {
                        fn_defs.push(quote! {
                            fn #setter_fn_name(
                                this: &mut #path,
                                __zv: &::ext_php_rs::types::Zval,
                            ) -> ::ext_php_rs::exception::PhpResult {
                                use ::ext_php_rs::convert::FromZval as _;
                                let val = ::ext_php_rs::convert::FromZval::from_zval(__zv)
                                    .ok_or("Unable to convert property value into required type.")?;
                                #path::#setter_ident(this, val);
                                Ok(())
                            }
                        });
                    }
                    quote! { ::std::option::Option::Some(#setter_fn_name) }
                } else {
                    quote! { ::std::option::Option::None }
                };

                let descriptor = quote! {
                    ::ext_php_rs::internal::property::PropertyDescriptor {
                        name: #prop_name,
                        get: #getter_ref,
                        set: #setter_ref,
                        flags: #flags,
                        docs: &[#(#docs),*],
                        #type_tokens
                        readonly: #readonly,
                    }
                };

                (fn_defs, descriptor)
            })
            .collect();

        let method_prop_fn_defs: Vec<&TokenStream> = method_prop_data
            .iter()
            .flat_map(|(fns, _)| fns.iter())
            .collect();
        let method_prop_descriptors: Vec<&TokenStream> =
            method_prop_data.iter().map(|(_, d)| d).collect();
        let method_prop_count = method_prop_descriptors.len();

        quote! {
            #abstract_check

            impl ::ext_php_rs::internal::class::PhpClassImpl<#path>
                for ::ext_php_rs::internal::class::PhpClassImplCollector<#path>
            {
                fn get_methods(self) -> ::std::vec::Vec<
                    (::ext_php_rs::builders::FunctionBuilder<'static>, ::ext_php_rs::flags::MethodFlags)
                > {
                    vec![#(#functions),*]
                }

                fn get_method_props(self) -> &'static [::ext_php_rs::internal::property::PropertyDescriptor<#path>] {
                    #(#method_prop_fn_defs)*

                    static METHOD_PROPS: [
                        ::ext_php_rs::internal::property::PropertyDescriptor<#path>; #method_prop_count
                    ] = [
                        #(#method_prop_descriptors,)*
                    ];
                    &METHOD_PROPS
                }

                fn get_constructor(self) -> ::std::option::Option<::ext_php_rs::class::ConstructorMeta<#path>> {
                    #constructor
                }

                fn get_constants(self) -> &'static [(&'static str, &'static dyn ::ext_php_rs::convert::IntoZvalDyn, &'static [&'static str], ::ext_php_rs::flags::ConstantFlags)] {
                    &[#(#constants),*]
                }
            }
        }
    }
}

impl quote::ToTokens for FnBuilder {
    fn to_tokens(&self, tokens: &mut TokenStream) {
        let builder = &self.builder;
        // TODO(cole_d): allow more flags via attributes
        let mut flags = vec![];
        let vis = &self.vis;
        flags.push(quote! { #vis });
        for flag in &self.modifiers {
            flags.push(quote! { #flag });
        }

        quote! {
            (#builder, #(#flags)|*)
        }
        .to_tokens(tokens);
    }
}

#[cfg(test)]
mod tests {
    use quote::{ToTokens, quote};

    use super::{BTreeSet, FnBuilder, MethodModifier};
    use crate::parsing::Visibility;

    #[test]
    fn modifiers_render_in_a_fixed_order() {
        let render = |inserted: [MethodModifier; 2]| {
            FnBuilder {
                builder: quote! { b },
                vis: Visibility::Public,
                modifiers: inserted.into_iter().collect::<BTreeSet<_>>(),
            }
            .to_token_stream()
            .to_string()
        };
        let expected = quote! {
            (b, ::ext_php_rs::flags::MethodFlags::Public
                | ::ext_php_rs::flags::MethodFlags::Abstract
                | ::ext_php_rs::flags::MethodFlags::Static)
        }
        .to_string();

        assert_eq!(
            render([MethodModifier::Static, MethodModifier::Abstract]),
            expected
        );
        assert_eq!(
            render([MethodModifier::Abstract, MethodModifier::Static]),
            expected
        );
    }
}