Skip to main content

ext_php_rs_derive/
lib.rs

1//! Macros for the `php-ext` crate.
2mod class;
3mod constant;
4mod enum_;
5mod extern_;
6mod fastcall;
7mod function;
8mod helpers;
9mod impl_;
10mod impl_interface;
11mod interface;
12mod module;
13mod parsing;
14mod syn_ext;
15mod zval;
16
17use darling::FromMeta;
18use proc_macro::TokenStream;
19use proc_macro2::TokenStream as TokenStream2;
20use syn::{
21    DeriveInput, ItemConst, ItemEnum, ItemFn, ItemForeignMod, ItemImpl, ItemStruct, ItemTrait,
22};
23
24extern crate proc_macro;
25
26// BEGIN DOCS FROM classes.md
27/// # `#[php_class]` Attribute
28///
29/// Structs can be exported to PHP as classes with the `#[php_class]` attribute
30/// macro. This attribute derives the `RegisteredClass` trait on your struct, as
31/// well as registering the class to be registered with the `#[php_module]`
32/// macro.
33///
34/// ## Options
35///
36/// There are additional macros that modify the class. These macros **must** be
37/// placed underneath the `#[php_class]` attribute.
38///
39/// - `name` - Changes the name of the class when exported to PHP. The Rust
40///   struct name is kept the same. If no name is given, the name of the struct
41///   is used. Useful for namespacing classes.
42/// - `change_case` - Changes the case of the class name when exported to PHP.
43/// - `readonly` - Marks the class as readonly (PHP 8.2+). All properties in a
44///   readonly class are implicitly readonly.
45/// - `flags` - Sets class flags using `ClassFlags`, e.g. `#[php(flags =
46///   ClassFlags::Final)]` for a final class.
47/// - `no_constructor` - A class without a constructor declares none, rather
48///   than one that throws: `new` creates an object initialized with
49///   `Default::default()`. The struct must implement `Default`. See
50///   [Constructors](./impl.md#constructors).
51/// - `#[php(extends(...))]` - Sets the parent class of the class. Can only be
52///   used once. Two forms are supported:
53///   - Simple type form: `#[php(extends(MyBaseClass))]` - For Rust-defined
54///     classes that implement `RegisteredClass`.
55///   - Explicit form: `#[php(extends(ce = ce_fn, stub = "ParentClass"))]` - For
56///     built-in PHP classes. `ce_fn` must be a function with the signature
57///     `fn() -> &'static ClassEntry`.
58/// - `#[php(implements(...))]` - Implements the given interface on the class.
59///   Can be used multiple times. Two forms are supported:
60///   - Simple type form: `#[php(implements(MyInterface))]` — For Rust-defined
61///     interfaces that implement `RegisteredClass`.
62///   - Explicit form: `#[php(implements(ce = ce_fn, stub = "InterfaceName"))]`
63///     — For built-in PHP interfaces. `ce_fn` must be a valid function with the
64///     signature `fn() -> &'static ClassEntry`.
65/// - Generated stubs write each parent class and interface name as a fully
66///   qualified name, with a leading `\`. A leading `\` in `stub = "..."` is
67///   optional.
68///
69/// You may also use the `#[php(prop)]` attribute on a struct field to use the
70/// field as a PHP property. By default, the property is public and its name is
71/// the field name converted to camelCase: the field `first_name` gives the
72/// property `firstName`. Property types must implement `IntoZval` and
73/// `FromZval`.
74///
75/// You can customize properties with these options:
76///
77/// - `name` - Allows you to rename the property, e.g. `#[php(prop, name =
78///   "new_name")]`
79/// - `change_case` - Allows you to rename the property using rename rules, e.g.
80///   `#[php(prop, change_case = "PascalCase")]`
81/// - `static` - Makes the property static (shared across all instances), e.g.
82///   `#[php(prop, static)]`
83/// - `flags` - Sets property visibility flags, e.g. `#[php(prop, flags =
84///   ext_php_rs::flags::PropertyFlags::Private)]`
85///
86/// ### How PHP code uses a Rust property
87///
88/// The value of a `#[php(prop)]` field is in the Rust struct. PHP reads the
89/// value with the getter and writes the value with the setter.
90///
91/// These operations use the getter and the setter:
92///
93/// - `$obj->prop += 1`, `$obj->prop .= 'x'`, `$obj->prop++` and `$obj->prop ??=
94///   1`.
95/// - `==` and `foreach`, which use the current Rust values. Thus `==` calls
96///   each getter of the two objects.
97///
98/// These operations change only a copy, and the Rust value does not change:
99///
100/// - `$obj->prop[] = 1`, `$obj->prop['key'] = 1` and `$r = &$obj->prop`. PHP
101///   gives the notice "Indirect modification of overloaded property", as for
102///   `__get`.
103/// - `foreach ($obj as &$value)`.
104///
105/// These operations throw an `Error`:
106///
107/// - `$obj->prop = &$value`.
108/// - `unset($obj->prop)`, because the Rust value cannot be removed.
109///
110/// If a PHP subclass declares the property again with hooks, PHP uses the Rust
111/// getter and setter, not the hooks.
112///
113/// ### Typed properties
114///
115/// A property PHP stores itself, rather than in the Rust struct, can be
116/// declared with a type, as `protected int $count = 0;` declares one in PHP.
117/// Add it with `ClassBuilder::typed_property` from the class's `modifier`
118/// function: the engine enforces the type on every write (coercing in weak
119/// mode), reflection reports it, and without a default the property starts
120/// uninitialized. PHP subclasses read and write it like any declared property.
121///
122/// ```rust,ignore
123/// use ext_php_rs::builders::{ClassBuilder, ClassProperty};
124/// use ext_php_rs::flags::{DataType, PropertyFlags};
125/// use ext_php_rs::prelude::*;
126/// use ext_php_rs::types::Zval;
127///
128/// #[php_class]
129/// #[php(modifier = counter_properties)]
130/// pub struct Counter;
131///
132/// fn counter_properties(builder: ClassBuilder) -> ClassBuilder {
133///     builder.typed_property(ClassProperty {
134///         name: "count".into(),
135///         flags: PropertyFlags::Protected,
136///         default: Some(Box::new(|| {
137///             let mut zero = Zval::new();
138///             zero.set_long(0);
139///             Ok(zero)
140///         })),
141///         docs: &[],
142///         ty: Some(DataType::Long),
143///         nullable: false,
144///         readonly: false,
145///         default_stub: Some("0".into()),
146///     })
147/// }
148/// ```
149///
150/// A property type is `bool`, `int`, `float`, `string`, `array`, `object`,
151/// `mixed` or a class, nullable or not; `iterable`, `resource`, `callable` and
152/// the other `DataType`s are refused. A default must be a value of the type (an
153/// `int` default of a `float` property becomes a float). Readonly typed
154/// properties, and typed properties of a readonly class, are not supported yet.
155/// Registration fails with `Error::InvalidPropertyType` otherwise.
156///
157/// `ClassBuilder::property` declares a property without a type; its `ty` only
158/// shapes the generated stubs.
159///
160/// ## Access to the Rust Value
161///
162/// The object keeps its Rust value in a borrow cell. Each method borrows the
163/// value until the method returns:
164///
165/// - A `&self` method borrows the value as shared. Other `&self` methods and
166///   property reads can use the value at the same time.
167/// - A `&mut self` method borrows the value as exclusive. No other method and
168///   no other property access can use the value at the same time.
169///
170/// A method can call PHP code, for example a callback. That PHP code can call a
171/// method on the same object. If the second call conflicts with the borrow, PHP
172/// throws an `Error`:
173///
174/// | Conflict | `Error` message |
175/// | --- | --- |
176/// | A `&self` method or a property read while a `&mut self` method runs | `Cannot use object of class Foo while one of its methods modifies it` |
177/// | A `&mut self` method or a property write while a different method runs | `Cannot modify object of class Foo while it is in use` |
178/// | The object has no Rust value, for example a subclass that does not call `parent::__construct()` | `Object of class Foo is not initialized` |
179///
180/// ### Class Arguments
181///
182/// A parameter of a `#[php_class]` type borrows the Rust value of the object:
183///
184/// - `&Foo` gives shared access to the value.
185/// - `&mut Foo` gives exclusive access to the value.
186/// - `Option<&Foo>` and `Option<&mut Foo>` also accept `null`.
187///
188/// The borrow starts before the function body and stops when the function
189/// returns. The rules of [Access to the Rust Value](#access-to-the-rust-value) apply during
190/// the call. If two parameters, or the object of the method and a parameter,
191/// get the same object and the borrows conflict, PHP throws an `Error`.
192///
193/// The borrow guards `ClassRef<Foo>` and `ClassRefMut<Foo>` are also parameter
194/// types. A variadic parameter must use them, for example `&[ClassRef<Foo>]`.
195/// The value parameter of a property setter accepts the same types.
196///
197/// Only a `#[php_class]` type can be a class parameter. The PHP objects of a
198/// `#[php_enum]` type hold no Rust value, so a `&Suit` parameter does not
199/// compile. Take the enum by value, for example `suit: Suit`.
200///
201/// A PHP fatal error during the call stops the function without the release of
202/// the borrow. The object stays borrowed until the end of the request.
203///
204/// ```rust,no_run,ignore
205/// # #![cfg_attr(windows, feature(abi_vectorcall))]
206/// # extern crate ext_php_rs;
207/// use ext_php_rs::prelude::*;
208///
209/// #[php_class]
210/// pub struct Counter {
211///     count: i64,
212/// }
213///
214/// #[php_function]
215/// pub fn add_to(target: &mut Counter, source: &Counter) -> i64 {
216///     target.count += source.count;
217///     target.count
218/// }
219///
220/// #[php_module]
221/// pub fn get_module(module: ModuleBuilder) -> ModuleBuilder {
222///     module.class::<Counter>().function(wrap_function!(add_to))
223/// }
224/// # fn main() {}
225/// ```
226///
227/// ### Class Objects in a `Zval`
228///
229/// `Zval::extract::<ClassRef<Foo>>()` gives `None` if the value is not a `Foo`.
230/// It also gives `None` if a method of the object borrows the Rust value. To
231/// know the cause, use `Zval::try_extract`:
232///
233/// - `Error::ZvalConversion` tells that the value is not a `Foo`.
234/// - `Error::Borrow` tells that the borrow conflicts with a method of the
235///   object.
236///
237/// ```rust,no_run,ignore
238/// # #![cfg_attr(windows, feature(abi_vectorcall))]
239/// # extern crate ext_php_rs;
240/// use ext_php_rs::{error::Error, prelude::*, types::Zval};
241///
242/// #[php_class]
243/// pub struct Counter {
244///     count: i64,
245/// }
246///
247/// #[php_function]
248/// pub fn count_of(value: &Zval) -> PhpResult<Option<i64>> {
249///     match value.try_extract::<ClassRef<Counter>>() {
250///         Ok(counter) => Ok(Some(counter.count)),
251///         Err(Error::ZvalConversion(_)) => Ok(None),
252///         Err(err) => Err(err.into()),
253///     }
254/// }
255///
256/// #[php_module]
257/// pub fn get_module(module: ModuleBuilder) -> ModuleBuilder {
258///     module.class::<Counter>().function(wrap_function!(count_of))
259/// }
260/// # fn main() {}
261/// ```
262///
263/// ### Call PHP Code from a Method
264///
265/// A `&mut self` method keeps the exclusive borrow until it returns. If a PHP
266/// callback of the method calls a method on the same object, the callback gets
267/// an `Error`. To let the callback use the object, use `self_:
268/// &ZendClassObject<Self>` in place of `&mut self`. Then borrow the value only
269/// when it is necessary:
270///
271/// ```rust,no_run,ignore
272/// # #![cfg_attr(windows, feature(abi_vectorcall))]
273/// # extern crate ext_php_rs;
274/// use ext_php_rs::{
275///     prelude::*,
276///     types::{ZendClassObject, Zval},
277/// };
278///
279/// #[php_class]
280/// pub struct EventEmitter {
281///     listeners: Vec<Zval>,
282/// }
283///
284/// #[php_impl]
285/// impl EventEmitter {
286///     pub fn __construct() -> Self {
287///         Self {
288///             listeners: Vec::new(),
289///         }
290///     }
291///
292///     pub fn on(&mut self, listener: &Zval) {
293///         self.listeners.push(listener.shallow_clone());
294///     }
295///
296///     pub fn emit(self_: &ZendClassObject<Self>) -> PhpResult<()> {
297///         let listeners: Vec<Zval> = self_
298///             .try_borrow()?
299///             .listeners
300///             .iter()
301///             .map(Zval::shallow_clone)
302///             .collect();
303///         for listener in &listeners {
304///             listener.try_call(vec![])?;
305///         }
306///         Ok(())
307///     }
308/// }
309///
310/// #[php_module]
311/// pub fn get_module(module: ModuleBuilder) -> ModuleBuilder {
312///     module.class::<EventEmitter>()
313/// }
314/// # fn main() {}
315/// ```
316///
317/// The guard of `try_borrow()` stops at the end of the `let` statement. Thus a
318/// listener can call `$emitter->on()` during `emit()`.
319///
320/// ## PHP Values in Rust Fields
321///
322/// A field can keep a PHP value, for example a callback. Two objects that refer
323/// to each other make a cycle. The PHP cycle collector finds and frees each
324/// cycle that no other value refers to. The collector must know the values that
325/// each object keeps.
326///
327/// `#[php_class]` gives the collector the value of each field that has one of
328/// these types:
329///
330/// - `Zval`.
331/// - `ZBox<ZendObject>` and `ZBox<ZendClassObject<T>>`.
332/// - `ZendCallable` when it owns its value.
333/// - `Option`, `Box`, `Vec` and arrays of these types, and the values of a
334///   `HashMap` or a `BTreeMap` of these types.
335///
336/// You do not write code for these fields. In this example, the collector frees
337/// the emitter and the closure after `unset($emitter)`:
338///
339/// ```rust,no_run,ignore
340/// # #![cfg_attr(windows, feature(abi_vectorcall))]
341/// # extern crate ext_php_rs;
342/// use ext_php_rs::{prelude::*, types::Zval};
343///
344/// #[php_class]
345/// pub struct EventEmitter {
346///     listeners: Vec<Zval>,
347/// }
348///
349/// #[php_impl]
350/// impl EventEmitter {
351///     pub fn __construct() -> Self {
352///         Self {
353///             listeners: Vec::new(),
354///         }
355///     }
356///
357///     pub fn on(&mut self, listener: &Zval) {
358///         self.listeners.push(listener.shallow_clone());
359///     }
360/// }
361///
362/// #[php_module]
363/// pub fn get_module(module: ModuleBuilder) -> ModuleBuilder {
364///     module.class::<EventEmitter>()
365/// }
366/// # fn main() {}
367/// ```
368///
369/// ```php
370/// $emitter = new EventEmitter();
371/// $emitter->on(fn() => $emitter);
372/// unset($emitter);
373/// gc_collect_cycles();
374/// ```
375///
376/// While a `&mut self` method runs, the collector does not read the Rust fields
377/// of the object. The collector then counts the values of these fields as used
378/// from outside the cycle. A later collection frees the cycle.
379///
380/// The collector does not see the values in other types, for example
381/// `ZBox<ZendHashTable>`, `Rc`, `Arc`, `RefCell` and Rust closures. A cycle
382/// through these fields stays in memory until the end of the request. To let
383/// the collector see a PHP array, keep the array in a `Zval`.
384///
385/// For a field of your own type, implement the unsafe trait `GcTrace` for the
386/// type. The implementation must give only the PHP values that the type owns,
387/// and each value one time. If it gives a value two times, the collector can
388/// free a value that is in use. Do not give the values in a `RefCell`, a `Cell`
389/// or a `Mutex`. A shared borrow does not stop a change of these values.
390///
391/// ```rust,no_run,ignore
392/// # extern crate ext_php_rs;
393/// use ext_php_rs::{
394///     gc::{GcRoots, GcTrace},
395///     types::Zval,
396/// };
397///
398/// pub struct Listener {
399///     name: String,
400///     callback: Zval,
401/// }
402///
403/// unsafe impl GcTrace for Listener {
404///     unsafe fn gc_trace(&self, roots: &mut GcRoots) {
405///         // SAFETY: `callback` is the only PHP value of `Listener`.
406///         unsafe { self.callback.gc_trace(roots) };
407///     }
408/// }
409/// # fn main() {}
410/// ```
411///
412/// ## Restrictions
413///
414/// ### No lifetime parameters
415///
416/// Rust lifetimes are used by the Rust compiler to reason about a program's
417/// memory safety. They are a compile-time only concept;
418/// there is no way to access Rust lifetimes at runtime from a dynamic language
419/// like PHP.
420///
421/// As soon as Rust data is exposed to PHP,
422/// there is no guarantee which the Rust compiler can make on how long the data
423/// will live. PHP is a reference-counted language and those references can be
424/// held for an arbitrarily long time, which is untraceable by the Rust
425/// compiler. The only possible way to express this correctly is to require that
426/// any `#[php_class]` does not borrow data for any lifetime shorter than the
427/// `'static` lifetime, i.e. the `#[php_class]` cannot have any lifetime
428/// parameters.
429///
430/// When you need to share ownership of data between PHP and Rust,
431/// instead of using borrowed references with lifetimes, consider using
432/// reference-counted smart pointers such as [Arc](https://doc.rust-lang.org/std/sync/struct.Arc.html).
433///
434/// ### No generic parameters
435///
436/// A Rust struct `Foo<T>` with a generic parameter `T` generates new compiled
437/// implementations each time it is used with a different concrete type for `T`.
438/// These new implementations are generated by the compiler at each usage site.
439/// This is incompatible with wrapping `Foo` in PHP,
440/// where there needs to be a single compiled implementation of `Foo` which is
441/// integrated with the PHP interpreter.
442///
443/// ## Example
444///
445/// This example creates a PHP class `Human`, adding a PHP property `address`.
446///
447/// ```rust,no_run,ignore
448/// # #![cfg_attr(windows, feature(abi_vectorcall))]
449/// # extern crate ext_php_rs;
450/// use ext_php_rs::prelude::*;
451///
452/// #[php_class]
453/// pub struct Human {
454///     name: String,
455///     age: i32,
456///     #[php(prop)]
457///     address: String,
458/// }
459///
460/// #[php_module]
461/// pub fn get_module(module: ModuleBuilder) -> ModuleBuilder {
462///     module.class::<Human>()
463/// }
464/// # fn main() {}
465/// ```
466///
467/// Create a custom exception `RedisException`, which extends `Exception`, and
468/// put it in the `Redis\Exception` namespace:
469///
470/// ```rust,no_run,ignore
471/// # #![cfg_attr(windows, feature(abi_vectorcall))]
472/// # extern crate ext_php_rs;
473/// use ext_php_rs::{
474///     prelude::*,
475///     exception::PhpException,
476///     zend::ce
477/// };
478///
479/// #[php_class]
480/// #[php(name = "Redis\\Exception\\RedisException")]
481/// #[php(extends(ce = ce::exception, stub = "\\Exception"))]
482/// #[derive(Default)]
483/// pub struct RedisException;
484///
485/// // Throw our newly created exception
486/// #[php_function]
487/// pub fn throw_exception() -> PhpResult<i32> {
488///     Err(PhpException::from_class::<RedisException>("Not good!".into()))
489/// }
490///
491/// #[php_module]
492/// pub fn get_module(module: ModuleBuilder) -> ModuleBuilder {
493///     module
494///         .class::<RedisException>()
495///         .function(wrap_function!(throw_exception))
496/// }
497/// # fn main() {}
498/// ```
499///
500/// ### Extending a Rust-defined Class
501///
502/// When extending another Rust-defined class, you can use the simpler type
503/// syntax:
504///
505/// ```rust,ignore
506/// # #![cfg_attr(windows, feature(abi_vectorcall))]
507/// # extern crate ext_php_rs;
508/// use ext_php_rs::prelude::*;
509///
510/// #[php_class]
511/// #[derive(Default)]
512/// pub struct Animal;
513///
514/// #[php_impl]
515/// impl Animal {
516///     pub fn speak(&self) -> &'static str {
517///         "..."
518///     }
519/// }
520///
521/// #[php_class]
522/// #[php(extends(Animal))]
523/// #[derive(Default)]
524/// pub struct Dog;
525///
526/// #[php_impl]
527/// impl Dog {
528///     pub fn speak(&self) -> &'static str {
529///         "Woof!"
530///     }
531/// }
532///
533/// #[php_module]
534/// pub fn get_module(module: ModuleBuilder) -> ModuleBuilder {
535///     module
536///         .class::<Animal>()
537///         .class::<Dog>()
538/// }
539/// # fn main() {}
540/// ```
541///
542/// #### Sharing Methods Between Parent and Child Classes
543///
544/// When both parent and child are Rust-defined classes, methods defined only in
545/// the parent won't automatically work when called on a child instance. This is
546/// because each Rust type has its own object handlers.
547///
548/// The recommended workaround is to use a Rust trait for shared behavior:
549///
550/// ```rust,ignore
551/// # #![cfg_attr(windows, feature(abi_vectorcall))]
552/// # extern crate ext_php_rs;
553/// use ext_php_rs::prelude::*;
554///
555/// /// Trait for shared behavior
556/// trait AnimalBehavior {
557///     fn speak(&self) -> &'static str {
558///         "..."
559///     }
560/// }
561///
562/// #[php_class]
563/// #[derive(Default)]
564/// pub struct Animal;
565///
566/// impl AnimalBehavior for Animal {}
567///
568/// #[php_impl]
569/// impl Animal {
570///     pub fn speak(&self) -> &'static str {
571///         AnimalBehavior::speak(self)
572///     }
573/// }
574///
575/// #[php_class]
576/// #[php(extends(Animal))]
577/// #[derive(Default)]
578/// pub struct Dog;
579///
580/// impl AnimalBehavior for Dog {
581///     fn speak(&self) -> &'static str {
582///         "Woof!"
583///     }
584/// }
585///
586/// #[php_impl]
587/// impl Dog {
588///     // Re-export the method so it works on Dog instances
589///     pub fn speak(&self) -> &'static str {
590///         AnimalBehavior::speak(self)
591///     }
592/// }
593///
594/// #[php_module]
595/// pub fn get_module(module: ModuleBuilder) -> ModuleBuilder {
596///     module
597///         .class::<Animal>()
598///         .class::<Dog>()
599/// }
600/// # fn main() {}
601/// ```
602///
603/// This pattern ensures that:
604/// - `$animal->speak()` returns `"..."`
605/// - `$dog->speak()` returns `"Woof!"`
606/// - `$dog instanceof Animal` is `true`
607///
608/// ## Implementing an Interface
609///
610/// To implement an interface, use `#[php(implements(...))]`. For built-in PHP
611/// interfaces, use the explicit form with `ce` and `stub`. For Rust-defined
612/// interfaces, you can use the simple type form. The following example implements [`ArrayAccess`](https://www.php.net/manual/en/class.arrayaccess.php):
613///
614/// ````rust,no_run,ignore
615/// # #![cfg_attr(windows, feature(abi_vectorcall))]
616/// # extern crate ext_php_rs;
617/// use ext_php_rs::{
618///     prelude::*,
619///     exception::PhpResult,
620///     types::Zval,
621///     zend::ce,
622/// };
623///
624/// #[php_class]
625/// #[php(implements(ce = ce::arrayaccess, stub = "\\ArrayAccess"))]
626/// #[derive(Default)]
627/// pub struct EvenNumbersArray;
628///
629/// /// Returns `true` if the array offset is an even number.
630/// /// Usage:
631/// /// ```php
632/// /// $arr = new EvenNumbersArray();
633/// /// var_dump($arr[0]); // true
634/// /// var_dump($arr[1]); // false
635/// /// var_dump($arr[2]); // true
636/// /// var_dump($arr[3]); // false
637/// /// var_dump($arr[4]); // true
638/// /// var_dump($arr[5] = true); // Fatal error:  Uncaught Exception: Setting values is not supported
639/// /// ```
640/// #[php_impl]
641/// impl EvenNumbersArray {
642///     pub fn __construct() -> EvenNumbersArray {
643///         EvenNumbersArray {}
644///     }
645///     // We need to use `Zval` because ArrayAccess needs $offset to be a `mixed`
646///     pub fn offset_exists(&self, offset: &'_ Zval) -> bool {
647///         offset.is_long()
648///     }
649///     pub fn offset_get(&self, offset: &'_ Zval) -> PhpResult<bool> {
650///         let integer_offset = offset.long().ok_or("Expected integer offset")?;
651///         Ok(integer_offset % 2 == 0)
652///     }
653///     pub fn offset_set(&mut self, _offset: &'_ Zval, _value: &'_ Zval) -> PhpResult {
654///         Err("Setting values is not supported".into())
655///     }
656///     pub fn offset_unset(&mut self, _offset: &'_ Zval) -> PhpResult {
657///         Err("Setting values is not supported".into())
658///     }
659/// }
660///
661/// #[php_module]
662/// pub fn get_module(module: ModuleBuilder) -> ModuleBuilder {
663///     module.class::<EvenNumbersArray>()
664/// }
665/// # fn main() {}
666/// ````
667///
668/// ## Static Properties
669///
670/// Static properties are shared across all instances of a class. Use
671/// `#[php(prop, static)]` to declare a static property. Unlike instance
672/// properties, static properties are managed entirely by PHP and do not use
673/// Rust property handlers.
674///
675/// You can specify a default value using the `default` attribute:
676///
677/// ```rust,no_run,ignore
678/// # #![cfg_attr(windows, feature(abi_vectorcall))]
679/// # extern crate ext_php_rs;
680/// use ext_php_rs::prelude::*;
681/// use ext_php_rs::class::RegisteredClass;
682///
683/// #[php_class]
684/// pub struct Counter {
685///     #[php(prop)]
686///     pub instance_value: i32,
687///     #[php(prop, static, default = 0)]
688///     pub count: i32,
689///     #[php(prop, static, flags = ext_php_rs::flags::PropertyFlags::Private)]
690///     pub internal_state: String,
691/// }
692///
693/// #[php_impl]
694/// impl Counter {
695///     pub fn __construct(value: i32) -> Self {
696///         Self {
697///             instance_value: value,
698///             count: 0,
699///             internal_state: String::new(),
700///         }
701///     }
702///
703///     /// Increment the static counter from Rust
704///     pub fn increment() {
705///         let ce = Self::get_metadata().ce();
706///         let current: i64 = ce.get_static_property("count").unwrap_or(0);
707///         ce.set_static_property("count", current + 1).unwrap();
708///     }
709///
710///     /// Get the current count
711///     pub fn get_count() -> i64 {
712///         let ce = Self::get_metadata().ce();
713///         ce.get_static_property("count").unwrap_or(0)
714///     }
715/// }
716///
717/// #[php_module]
718/// pub fn get_module(module: ModuleBuilder) -> ModuleBuilder {
719///     module.class::<Counter>()
720/// }
721/// # fn main() {}
722/// ```
723///
724/// From PHP, you can access static properties directly on the class:
725///
726/// ```php
727/// // No need to initialize - count already has default value of 0
728/// Counter::increment();
729/// Counter::increment();
730/// echo Counter::$count; // 2
731/// echo Counter::getCount(); // 2
732/// ```
733///
734/// ## Abstract Classes
735///
736/// Abstract classes cannot be instantiated directly and may contain abstract
737/// methods that must be implemented by subclasses. Use `#[php(flags =
738/// ClassFlags::Abstract)]` to declare an abstract class:
739///
740/// ```rust,ignore
741/// use ext_php_rs::prelude::*;
742/// use ext_php_rs::flags::ClassFlags;
743///
744/// #[php_class]
745/// #[php(flags = ClassFlags::Abstract)]
746/// pub struct AbstractAnimal;
747///
748/// #[php_impl]
749/// impl AbstractAnimal {
750///     // Protected constructor for subclasses
751///     #[php(vis = "protected")]
752///     pub fn __construct() -> Self {
753///         Self
754///     }
755///
756///     // Abstract method - must be implemented by subclasses.
757///     // Body is never called; use unimplemented!() as a placeholder.
758///     #[php(abstract)]
759///     pub fn speak(&self) -> String {
760///         unimplemented!()
761///     }
762///
763///     // Concrete method - inherited by subclasses
764///     pub fn breathe(&self) {
765///         println!("Breathing...");
766///     }
767/// }
768/// ```
769///
770/// From PHP, you can extend this abstract class:
771///
772/// ```php
773/// class Dog extends AbstractAnimal {
774///     public function __construct() {
775///         parent::__construct();
776///     }
777///
778///     public function speak(): string {
779///         return "Woof!";
780///     }
781/// }
782///
783/// $dog = new Dog();
784/// echo $dog->speak(); // "Woof!"
785/// $dog->breathe();    // "Breathing..."
786///
787/// // This would cause an error:
788/// // $animal = new AbstractAnimal(); // Cannot instantiate abstract class
789/// ```
790///
791/// See the [impl documentation](./impl.md#abstract-methods) for more details on
792/// abstract methods.
793///
794/// ## Final Classes
795///
796/// Final classes cannot be extended. Use `#[php(flags = ClassFlags::Final)]` to
797/// declare a final class:
798///
799/// ```rust,ignore
800/// use ext_php_rs::prelude::*;
801/// use ext_php_rs::flags::ClassFlags;
802///
803/// #[php_class]
804/// #[php(flags = ClassFlags::Final)]
805/// pub struct FinalClass;
806/// ```
807///
808/// ## Readonly Classes (PHP 8.2+)
809///
810/// PHP 8.2 introduced [readonly classes](https://www.php.net/manual/en/language.oop5.basic.php#language.oop5.basic.class.readonly),
811/// where all properties are implicitly readonly. You can create a readonly
812/// class using the `#[php(readonly)]` attribute:
813///
814/// ```rust,ignore
815/// # #![cfg_attr(windows, feature(abi_vectorcall))]
816/// # extern crate ext_php_rs;
817/// use ext_php_rs::prelude::*;
818///
819/// #[php_class]
820/// #[php(readonly)]
821/// pub struct ImmutablePoint {
822///     x: f64,
823///     y: f64,
824/// }
825///
826/// #[php_impl]
827/// impl ImmutablePoint {
828///     pub fn __construct(x: f64, y: f64) -> Self {
829///         Self { x, y }
830///     }
831///
832///     pub fn get_x(&self) -> f64 {
833///         self.x
834///     }
835///
836///     pub fn get_y(&self) -> f64 {
837///         self.y
838///     }
839///
840///     pub fn distance_from_origin(&self) -> f64 {
841///         (self.x * self.x + self.y * self.y).sqrt()
842///     }
843/// }
844///
845/// #[php_module]
846/// pub fn get_module(module: ModuleBuilder) -> ModuleBuilder {
847///     module.class::<ImmutablePoint>()
848/// }
849/// # fn main() {}
850/// ```
851///
852/// From PHP:
853///
854/// ```php
855/// $point = new ImmutablePoint(3.0, 4.0);
856/// echo $point->getX(); // 3.0
857/// echo $point->getY(); // 4.0
858/// echo $point->distanceFromOrigin(); // 5.0
859///
860/// // On PHP 8.2+, you can verify the class is readonly:
861/// $reflection = new ReflectionClass(ImmutablePoint::class);
862/// var_dump($reflection->isReadOnly()); // true
863/// ```
864///
865/// The `readonly` attribute is compatible with other class attributes:
866///
867/// ```rust,ignore
868/// # #![cfg_attr(windows, feature(abi_vectorcall))]
869/// # extern crate ext_php_rs;
870/// use ext_php_rs::prelude::*;
871/// use ext_php_rs::flags::ClassFlags;
872///
873/// // Readonly + Final class
874/// #[php_class]
875/// #[php(readonly)]
876/// #[php(flags = ClassFlags::Final)]
877/// pub struct FinalImmutableData {
878///     value: String,
879/// }
880/// # fn main() {}
881/// ```
882///
883/// **Note:** The `readonly` attribute requires PHP 8.2 or later. Using it when
884/// compiling against an earlier PHP version will result in a compile error.
885///
886/// ### Conditional Compilation for Multi-Version Support
887///
888/// If your extension needs to support both PHP 8.1 and PHP 8.2+, you can use
889/// conditional compilation to only enable readonly on supported versions.
890///
891/// First, add `ext-php-rs-build` as a build dependency in your `Cargo.toml`:
892///
893/// ```toml
894/// [build-dependencies]
895/// ext-php-rs-build = "0.1"
896/// anyhow = "1"
897/// ```
898///
899/// Then create a `build.rs` that detects the PHP version and emits cfg flags:
900///
901/// ```rust,ignore
902/// use ext_php_rs_build::{find_php, PHPInfo, ApiVersion, emit_php_cfg_flags, emit_check_cfg};
903///
904/// fn main() -> anyhow::Result<()> {
905///     let php = find_php()?;
906///     let info = PHPInfo::get(&php)?;
907///     let version: ApiVersion = info.zend_version()?.try_into()?;
908///
909///     emit_check_cfg();
910///     emit_php_cfg_flags(version);
911///     Ok(())
912/// }
913/// ```
914///
915/// Now you can use `#[cfg(php82)]` to conditionally apply the readonly
916/// attribute:
917///
918/// ```rust,ignore
919/// #[php_class]
920/// #[cfg_attr(php82, php(readonly))]
921/// pub struct MaybeReadonlyClass {
922///     value: String,
923/// }
924/// ```
925///
926/// The `ext-php-rs-build` crate provides several useful utilities:
927///
928/// - `find_php()` - Locates the PHP executable (respects the `PHP` env var)
929/// - `PHPInfo::get()` - Runs `php -i` and parses the output
930/// - `ApiVersion` - Enum for the PHP versions (Php80, Php81, Php82, etc.). It
931///   is `#[non_exhaustive]`, so a `match` on it must have a `_` arm.
932/// - `emit_php_cfg_flags()` - Emits `cargo:rustc-cfg=phpXX` for all supported
933///   versions
934/// - `emit_check_cfg()` - Emits check-cfg to avoid unknown cfg warnings
935///
936/// This is **optional** - if your extension only targets PHP 8.2+, you can use
937/// `#[php(readonly)]` directly without any build script setup.
938///
939/// ## Cloning
940///
941/// PHP's native `clone` operator is supported for `#[php_class]` structs that
942/// implement `Clone`. A derive or a hand-written `impl Clone` both work, and
943/// the spelling of the derive path does not matter. The cloned PHP object
944/// contains a copy of the Rust data:
945///
946/// ```rust,ignore
947/// use ext_php_rs::prelude::*;
948///
949/// #[php_class]
950/// #[derive(Clone)]
951/// pub struct Style {
952///     #[php(prop)]
953///     pub font_size: f64,
954///     #[php(prop)]
955///     pub color: String,
956/// }
957///
958/// #[php_impl]
959/// impl Style {
960///     pub fn __construct(font_size: f64, color: String) -> Self {
961///         Self { font_size, color }
962///     }
963/// }
964/// ```
965///
966/// ```php
967/// $style = new Style(12.0, 'red');
968/// $copy = clone $style;
969///
970/// $copy->fontSize = 16.0;
971/// echo $style->fontSize;  // 12.0 — original is unchanged
972/// ```
973///
974/// The clone of a PHP subclass has the class of the subclass. PHP copies the
975/// properties of the subclass and calls its `__clone` method.
976///
977/// A class whose struct does not implement `Clone` has no clone handler, like
978/// the uncloneable classes of PHP. `clone` throws an `Error` that names the
979/// class of the object, and `ReflectionClass::isCloneable()` returns `false`:
980///
981/// ```php
982/// // If MyClass does not implement Clone:
983/// $obj = new MyClass();
984/// $copy = clone $obj; // Error: Trying to clone an uncloneable object of class MyClass
985/// ```
986///
987/// A `clone` of an object that one of its methods modifies at that time throws
988/// an `Error`. A `clone` of an object that has no Rust value, for example a PHP
989/// subclass that did not call the parent constructor, also throws an `Error`.
990/// When a clone fails, PHP does not call `__destruct` on the failed copy.
991///
992/// A `__clone` method does not make a class cloneable. If the struct does not
993/// implement `Clone`, `clone` throws, but `ReflectionClass::isCloneable()`
994/// returns `true` because PHP sees the `__clone` method.
995///
996/// ## Implementing Iterator
997///
998/// To make a Rust class usable with PHP's `foreach` loop, implement the
999/// [`Iterator`](https://www.php.net/manual/en/class.iterator.php) interface.
1000/// This requires implementing five methods: `current()`, `key()`, `next()`,
1001/// `rewind()`, and `valid()`.
1002///
1003/// The following example creates a `RangeIterator` that iterates over a range
1004/// of integers:
1005///
1006/// ````rust,no_run,ignore
1007/// # #![cfg_attr(windows, feature(abi_vectorcall))]
1008/// # extern crate ext_php_rs;
1009/// use ext_php_rs::{prelude::*, zend::ce};
1010///
1011/// #[php_class]
1012/// #[php(implements(ce = ce::iterator, stub = "\\Iterator"))]
1013/// pub struct RangeIterator {
1014///     start: i64,
1015///     end: i64,
1016///     current: i64,
1017///     index: i64,
1018/// }
1019///
1020/// #[php_impl]
1021/// impl RangeIterator {
1022///     /// Create a new range iterator from start to end (inclusive).
1023///     pub fn __construct(start: i64, end: i64) -> Self {
1024///         Self {
1025///             start,
1026///             end,
1027///             current: start,
1028///             index: 0,
1029///         }
1030///     }
1031///
1032///     /// Return the current element.
1033///     pub fn current(&self) -> i64 {
1034///         self.current
1035///     }
1036///
1037///     /// Return the key of the current element.
1038///     pub fn key(&self) -> i64 {
1039///         self.index
1040///     }
1041///
1042///     /// Move forward to next element.
1043///     pub fn next(&mut self) {
1044///         self.current += 1;
1045///         self.index += 1;
1046///     }
1047///
1048///     /// Rewind the Iterator to the first element.
1049///     pub fn rewind(&mut self) {
1050///         self.current = self.start;
1051///         self.index = 0;
1052///     }
1053///
1054///     /// Checks if current position is valid.
1055///     pub fn valid(&self) -> bool {
1056///         self.current <= self.end
1057///     }
1058/// }
1059///
1060/// #[php_module]
1061/// pub fn get_module(module: ModuleBuilder) -> ModuleBuilder {
1062///     module.class::<RangeIterator>()
1063/// }
1064/// # fn main() {}
1065/// ````
1066///
1067/// Using the iterator in PHP:
1068///
1069/// ```php
1070/// <?php
1071///
1072/// $range = new RangeIterator(1, 5);
1073///
1074/// // Use with foreach
1075/// foreach ($range as $key => $value) {
1076///     echo "$key => $value\n";
1077/// }
1078/// // Output:
1079/// // 0 => 1
1080/// // 1 => 2
1081/// // 2 => 3
1082/// // 3 => 4
1083/// // 4 => 5
1084///
1085/// // Works with iterator functions
1086/// $arr = iterator_to_array(new RangeIterator(10, 12));
1087/// // [0 => 10, 1 => 11, 2 => 12]
1088///
1089/// $count = iterator_count(new RangeIterator(1, 100));
1090/// // 100
1091/// ```
1092///
1093/// ### Iterator with Mixed Types
1094///
1095/// You can return different types for keys and values. The following example
1096/// uses string keys:
1097///
1098/// ````rust,no_run,ignore
1099/// # #![cfg_attr(windows, feature(abi_vectorcall))]
1100/// # extern crate ext_php_rs;
1101/// use ext_php_rs::{prelude::*, zend::ce};
1102///
1103/// #[php_class]
1104/// #[php(implements(ce = ce::iterator, stub = "\\Iterator"))]
1105/// pub struct MapIterator {
1106///     keys: Vec<String>,
1107///     values: Vec<String>,
1108///     index: usize,
1109/// }
1110///
1111/// #[php_impl]
1112/// impl MapIterator {
1113///     pub fn __construct() -> Self {
1114///         Self {
1115///             keys: vec!["first".into(), "second".into(), "third".into()],
1116///             values: vec!["one".into(), "two".into(), "three".into()],
1117///             index: 0,
1118///         }
1119///     }
1120///
1121///     pub fn current(&self) -> Option<String> {
1122///         self.values.get(self.index).cloned()
1123///     }
1124///
1125///     pub fn key(&self) -> Option<String> {
1126///         self.keys.get(self.index).cloned()
1127///     }
1128///
1129///     pub fn next(&mut self) {
1130///         self.index += 1;
1131///     }
1132///
1133///     pub fn rewind(&mut self) {
1134///         self.index = 0;
1135///     }
1136///
1137///     pub fn valid(&self) -> bool {
1138///         self.index < self.keys.len()
1139///     }
1140/// }
1141///
1142/// #[php_module]
1143/// pub fn get_module(module: ModuleBuilder) -> ModuleBuilder {
1144///     module.class::<MapIterator>()
1145/// }
1146/// # fn main() {}
1147/// ````
1148///
1149/// ```php
1150/// <?php
1151///
1152/// $map = new MapIterator();
1153/// foreach ($map as $key => $value) {
1154///     echo "$key => $value\n";
1155/// }
1156/// // Output:
1157/// // first => one
1158/// // second => two
1159/// // third => three
1160/// ```
1161// END DOCS FROM classes.md
1162#[proc_macro_attribute]
1163pub fn php_class(args: TokenStream, input: TokenStream) -> TokenStream {
1164    php_class_internal(args.into(), input.into()).into()
1165}
1166
1167#[allow(clippy::needless_pass_by_value)]
1168fn php_class_internal(args: TokenStream2, input: TokenStream2) -> TokenStream2 {
1169    let input = parse_macro_input2!(input as ItemStruct);
1170    if let Err(e) = reject_args(&args, "php_class", PHP_ATTR_HINT) {
1171        return e.to_compile_error();
1172    }
1173
1174    class::parser(input).unwrap_or_else(|e| e.to_compile_error())
1175}
1176
1177// BEGIN DOCS FROM enum.md
1178/// # `#[php_enum]` Attribute
1179///
1180/// Enums can be exported to PHP as enums with the `#[php_enum]` attribute
1181/// macro. This attribute derives the `RegisteredClass` and `PhpEnum` traits on
1182/// your enum. To register the enum use the `enumeration::<EnumName>()` method
1183/// on the `ModuleBuilder` in the `#[php_module]` macro.
1184///
1185/// ## Options
1186///
1187/// The `#[php_enum]` attribute can be configured with the following options:
1188/// - `#[php(name = "EnumName")]` or `#[php(change_case = "snake_case")]`: Sets
1189///   the name of the enum in PHP. The default is the `PascalCase` name of the
1190///   enum.
1191/// - `#[php(allow_native_discriminants)]`: Allows the use of native Rust
1192///   discriminants (e.g., `Hearts = 1`).
1193/// - `#[php(change_cases_case = "snake_case")]`: Sets the rename rule for every
1194///   case that has no `name` or `change_case` of its own. The old name of this
1195///   option, `rename_cases`, is a compile error.
1196///
1197/// PHP enums are always public. `#[php(vis = "...")]` on an enum is a compile
1198/// error, and so is any argument passed to the macro itself, such as
1199/// `#[php_enum(name = "Suit")]`.
1200///
1201/// The cases of the enum can be configured with the following options:
1202/// - `#[php(name = "CaseName")]` or `#[php(change_case = "snake_case")]`: Sets
1203///   the name of the enum case in PHP. The default is the `PascalCase` name of
1204///   the case.
1205/// - `#[php(value = "value")]` or `#[php(value = 123)]`: Sets the discriminant
1206///   value for the enum case. This can be a string or an integer. If not set,
1207///   the case will be exported as a simple enum case without a discriminant.
1208///
1209/// ### Example
1210///
1211/// This example creates a PHP enum `Suit`.
1212///
1213/// ```rust,no_run,ignore
1214/// # #![cfg_attr(windows, feature(abi_vectorcall))]
1215/// # extern crate ext_php_rs;
1216/// use ext_php_rs::prelude::*;
1217///
1218/// #[php_enum]
1219/// pub enum Suit {
1220///     Hearts,
1221///     Diamonds,
1222///     Clubs,
1223///     Spades,
1224/// }
1225///
1226/// #[php_module]
1227/// pub fn get_module(module: ModuleBuilder) -> ModuleBuilder {
1228///     module.enumeration::<Suit>()
1229/// }
1230/// # fn main() {}
1231/// ```
1232///
1233/// ## Backed Enums
1234/// Enums can also be backed by either `i64` or `&'static str`. Those values can
1235/// be set using the `#[php(value = "value")]` or `#[php(value = 123)]`
1236/// attributes on the enum variants.
1237///
1238/// All variants must have a value of the same type, either all `i64` or all
1239/// `&'static str`.
1240///
1241/// A backed enum converts to and from its value. The macro implements
1242/// `From<Enum>` for the value type, and `TryFrom<i64>` or `TryFrom<&str>` for
1243/// the enum. `TryFrom` returns `Error::InvalidEnumCase` when no case has the
1244/// value.
1245///
1246/// ```rust,no_run,ignore
1247/// # #![cfg_attr(windows, feature(abi_vectorcall))]
1248/// # extern crate ext_php_rs;
1249/// use ext_php_rs::prelude::*;
1250///
1251/// #[php_enum]
1252/// pub enum Suit {
1253///     #[php(value = "hearts")]
1254///     Hearts,
1255///     #[php(value = "diamonds")]
1256///     Diamonds,
1257///     #[php(value = "clubs")]
1258///     Clubs,
1259///     #[php(value = "spades")]
1260///     Spades,
1261/// }
1262/// #[php_module]
1263/// pub fn get_module(module: ModuleBuilder) -> ModuleBuilder {
1264///     module.enumeration::<Suit>()
1265/// }
1266/// # fn main() {}
1267/// ```
1268///
1269/// ### 'Native' Discriminators
1270/// Native rust discriminants are currently not supported and will not be
1271/// exported to PHP.
1272///
1273/// To avoid confusion a compiler error will be raised if you try to use a
1274/// native discriminant. You can ignore this error by adding the
1275/// `#[php(allow_native_discriminants)]` attribute to your enum.
1276///
1277/// ```rust,no_run,ignore
1278/// # #![cfg_attr(windows, feature(abi_vectorcall))]
1279/// # extern crate ext_php_rs;
1280/// use ext_php_rs::prelude::*;
1281///
1282/// #[php_enum]
1283/// #[php(allow_native_discriminants)]
1284/// pub enum Suit {
1285///     Hearts = 1,
1286///     Diamonds = 2,
1287///     Clubs = 3,
1288///     Spades = 4,
1289/// }
1290///
1291/// #[php_module]
1292/// pub fn get_module(module: ModuleBuilder) -> ModuleBuilder {
1293///     module.enumeration::<Suit>()
1294/// }
1295/// # fn main() {}
1296/// ```
1297///
1298///
1299/// TODO: Add backed enums example
1300// END DOCS FROM enum.md
1301#[proc_macro_attribute]
1302pub fn php_enum(args: TokenStream, input: TokenStream) -> TokenStream {
1303    php_enum_internal(args.into(), input.into()).into()
1304}
1305
1306#[allow(clippy::needless_pass_by_value)]
1307fn php_enum_internal(args: TokenStream2, input: TokenStream2) -> TokenStream2 {
1308    let input = parse_macro_input2!(input as ItemEnum);
1309    if let Err(e) = reject_args(&args, "php_enum", PHP_ATTR_HINT) {
1310        return e.to_compile_error();
1311    }
1312
1313    enum_::parser(input).unwrap_or_else(|e| e.to_compile_error())
1314}
1315
1316// BEGIN DOCS FROM interface.md
1317/// # `#[php_interface]` Attribute
1318///
1319/// You can export a `Trait` block to PHP. This exports all methods as well as
1320/// constants to PHP on the interface. Trait method SHOULD NOT contain default
1321/// implementations, as these are not supported in PHP interfaces.
1322///
1323/// ## Options
1324///
1325/// By default all constants are renamed to `UPPER_CASE` and all methods are
1326/// renamed to `camelCase`. This can be changed by passing the
1327/// `change_method_case` and `change_constant_case` as `#[php]` attributes on
1328/// the `impl` block. The options are:
1329///
1330/// - `#[php(change_method_case = "snake_case")]` - Renames the method to snake
1331///   case.
1332/// - `#[php(change_constant_case = "snake_case")]` - Renames the constant to
1333///   snake case.
1334///
1335/// See the [`name` and `change_case`](./php.md#name-and-change_case) section for a list of all
1336/// available cases.
1337///
1338/// The macro itself takes no arguments: `#[php_interface(name = "Foo")]` is a
1339/// compile error. Put the options in `#[php(...)]` on the trait.
1340///
1341/// ## Methods
1342///
1343/// A trait method accepts the `name`, `change_case`, `defaults`, `optional`,
1344/// `sensitive` and `vis` options. Interfaces cannot declare property accessors
1345/// or constructors, so `getter`, `setter` and `constructor` are compile errors
1346/// here. See [`php_impl`](./impl.md#) for how each accepted option behaves.
1347///
1348/// ## Constants
1349///
1350/// A trait constant accepts the `name` and `change_case` options. Interface
1351/// constants are always public, so `vis` is a compile error here. See
1352/// [`php_impl`](./impl.md#constants) for the value types.
1353///
1354/// ## Example
1355///
1356/// Define an example trait with methods and constant:
1357///
1358/// ```rust,no_run,ignore
1359/// # #![cfg_attr(windows, feature(abi_vectorcall))]
1360/// # extern crate ext_php_rs;
1361/// use ext_php_rs::{prelude::*, types::ZendClassObject};
1362///
1363///
1364/// #[php_interface]
1365/// #[php(name = "Rust\\TestInterface")]
1366/// trait Test {
1367///     const TEST: &'static str = "TEST";
1368///
1369///     fn co();
1370///
1371///     #[php(defaults(value = 0))]
1372///     fn set_value(&mut self, value: i32);
1373/// }
1374///
1375/// #[php_module]
1376/// pub fn module(module: ModuleBuilder) -> ModuleBuilder {
1377///     module
1378///         .interface::<PhpInterfaceTest>()
1379/// }
1380///
1381/// # fn main() {}
1382/// ```
1383///
1384/// Using our newly created interface in PHP:
1385///
1386/// ```php
1387/// <?php
1388///
1389/// assert(interface_exists("Rust\TestInterface"));
1390///
1391/// class B implements Rust\TestInterface {
1392///
1393///     public static function co() {}
1394///
1395///     public function setValue(?int $value = 0) {
1396///
1397///     }
1398/// }
1399/// ```
1400///
1401/// ## Interface Inheritance
1402///
1403/// PHP interfaces can extend other interfaces. You can achieve this in two
1404/// ways:
1405///
1406/// ### Using `#[php(extends(...))]`
1407///
1408/// Use the `extends` attribute to extend a built-in PHP interface or another
1409/// Rust-defined interface. Generated stubs write each parent interface name as
1410/// a fully qualified name, with a leading `\`. A leading `\` in `stub = "..."`
1411/// is optional.
1412///
1413/// For built-in PHP interfaces, use the explicit form:
1414///
1415/// ```rust,no_run,ignore
1416/// # #![cfg_attr(windows, feature(abi_vectorcall))]
1417/// # extern crate ext_php_rs;
1418/// use ext_php_rs::prelude::*;
1419/// use ext_php_rs::zend::ce;
1420///
1421/// #[php_interface]
1422/// #[php(extends(ce = ce::throwable, stub = "\\Throwable"))]
1423/// #[php(name = "MyException")]
1424/// trait MyExceptionInterface {
1425///     fn get_error_code(&self) -> i32;
1426/// }
1427///
1428/// # fn main() {}
1429/// ```
1430///
1431/// For Rust-defined interfaces, you can use the simpler type syntax:
1432///
1433/// ```rust,ignore
1434/// # #![cfg_attr(windows, feature(abi_vectorcall))]
1435/// # extern crate ext_php_rs;
1436/// use ext_php_rs::prelude::*;
1437///
1438/// #[php_interface]
1439/// trait BaseInterface {
1440///     fn base_method(&self) -> i32;
1441/// }
1442///
1443/// #[php_interface]
1444/// #[php(extends(BaseInterface))]
1445/// trait ExtendedInterface {
1446///     fn extended_method(&self) -> String;
1447/// }
1448///
1449/// # fn main() {}
1450/// ```
1451///
1452/// ### Using Rust Trait Bounds
1453///
1454/// You can also use Rust's trait bound syntax. When a trait marked with
1455/// `#[php_interface]` has supertraits, the PHP interface will automatically
1456/// extend those parent interfaces:
1457///
1458/// ```rust,no_run,ignore
1459/// # #![cfg_attr(windows, feature(abi_vectorcall))]
1460/// # extern crate ext_php_rs;
1461/// use ext_php_rs::prelude::*;
1462///
1463/// #[php_interface]
1464/// #[php(name = "Rust\\ParentInterface")]
1465/// trait ParentInterface {
1466///     fn parent_method(&self) -> String;
1467/// }
1468///
1469/// // ChildInterface extends ParentInterface in PHP
1470/// #[php_interface]
1471/// #[php(name = "Rust\\ChildInterface")]
1472/// trait ChildInterface: ParentInterface {
1473///     fn child_method(&self) -> String;
1474/// }
1475///
1476/// #[php_module]
1477/// pub fn module(module: ModuleBuilder) -> ModuleBuilder {
1478///     module
1479///         .interface::<PhpInterfaceParentInterface>()
1480///         .interface::<PhpInterfaceChildInterface>()
1481/// }
1482///
1483/// # fn main() {}
1484/// ```
1485///
1486/// In PHP:
1487///
1488/// ```php
1489/// <?php
1490///
1491/// // ChildInterface extends ParentInterface
1492/// assert(is_a('Rust\ChildInterface', 'Rust\ParentInterface', true));
1493/// ```
1494///
1495/// # `#[php_impl_interface]` Attribute
1496///
1497/// The `#[php_impl_interface]` attribute allows a Rust class to implement a
1498/// custom PHP interface defined with `#[php_interface]`. This creates a
1499/// relationship where PHP's `instanceof` and `is_a()` recognize the
1500/// implementation.
1501///
1502/// **Key feature**: The macro automatically registers the trait methods as PHP
1503/// methods on the class. You don't need to duplicate them in a separate
1504/// `#[php_impl]` block.
1505///
1506/// ## Example
1507///
1508/// ```rust,no_run,ignore
1509/// # #![cfg_attr(windows, feature(abi_vectorcall))]
1510/// # extern crate ext_php_rs;
1511/// use ext_php_rs::prelude::*;
1512///
1513/// // Define a custom interface
1514/// #[php_interface]
1515/// #[php(name = "Rust\\Greetable")]
1516/// trait Greetable {
1517///     fn greet(&self) -> String;
1518/// }
1519///
1520/// // Define a class
1521/// #[php_class]
1522/// #[php(name = "Rust\\Greeter")]
1523/// pub struct Greeter {
1524///     name: String,
1525/// }
1526///
1527/// #[php_impl]
1528/// impl Greeter {
1529///     pub fn __construct(name: String) -> Self {
1530///         Self { name }
1531///     }
1532///
1533///     // Note: No need to add greet() here - it's automatically
1534///     // registered by #[php_impl_interface] below
1535/// }
1536///
1537/// // Implement the interface for the class
1538/// // This automatically registers greet() as a PHP method
1539/// #[php_impl_interface]
1540/// impl Greetable for Greeter {
1541///     fn greet(&self) -> String {
1542///         format!("Hello, {}!", self.name)
1543///     }
1544/// }
1545///
1546/// #[php_module]
1547/// pub fn module(module: ModuleBuilder) -> ModuleBuilder {
1548///     module
1549///         .interface::<PhpInterfaceGreetable>()
1550///         .class::<Greeter>()
1551/// }
1552///
1553/// # fn main() {}
1554/// ```
1555///
1556/// Using in PHP:
1557///
1558/// ```php
1559/// <?php
1560///
1561/// $greeter = new Rust\Greeter("World");
1562///
1563/// // instanceof works
1564/// assert($greeter instanceof Rust\Greetable);
1565///
1566/// // is_a() works
1567/// assert(is_a($greeter, 'Rust\Greetable'));
1568///
1569/// // The greet() method is available (registered by #[php_impl_interface])
1570/// echo $greeter->greet(); // Output: Hello, World!
1571///
1572/// // Can be used as type hint
1573/// function greet(Rust\Greetable $obj): void {
1574///     echo $obj->greet();
1575/// }
1576///
1577/// greet($greeter);
1578/// ```
1579///
1580/// ## When to Use
1581///
1582/// - Use `#[php_impl_interface]` for custom interfaces you define with
1583///   `#[php_interface]`
1584/// - Use `#[php(implements(ce = ...))]` on `#[php_class]` for built-in PHP
1585///   interfaces like `Iterator`, `ArrayAccess`, `Countable`, etc.
1586///
1587/// See the [Classes documentation](./classes.md#implementing-an-interface) for examples
1588/// of implementing built-in interfaces.
1589///
1590/// ## Cross-Crate Support
1591///
1592/// The `#[php_impl_interface]` macro supports cross-crate interface discovery
1593/// via the [`inventory`](https://crates.io/crates/inventory) crate. This means you can define
1594/// an interface in one crate and implement it in another crate, and the
1595/// implementation will be automatically discovered at link time.
1596///
1597/// ### Example: Defining an Interface in a Library Crate
1598///
1599/// First, create a library crate that defines the interface:
1600///
1601/// ```toml
1602/// # my-interfaces/Cargo.toml
1603/// [package]
1604/// name = "my-interfaces"
1605/// version = "0.1.0"
1606///
1607/// [dependencies]
1608/// ext-php-rs = "0.15"
1609/// ```
1610///
1611/// ```rust,no_run,ignore,ignore
1612/// // my-interfaces/src/lib.rs
1613/// use ext_php_rs::prelude::*;
1614///
1615/// /// A serializable interface that can convert objects to JSON.
1616/// #[php_interface]
1617/// #[php(name = "MyInterfaces\\Serializable")]
1618/// pub trait Serializable {
1619///     fn to_json(&self) -> String;
1620/// }
1621///
1622/// // Re-export the generated PHP interface struct for consumers
1623/// pub use PhpInterfaceSerializable;
1624/// ```
1625///
1626/// ### Example: Implementing the Interface in Another Crate
1627///
1628/// Now create your extension crate that implements the interface:
1629///
1630/// ```toml
1631/// # my-extension/Cargo.toml
1632/// [package]
1633/// name = "my-extension"
1634/// version = "0.1.0"
1635///
1636/// [lib]
1637/// crate-type = ["cdylib"]
1638///
1639/// [dependencies]
1640/// ext-php-rs = "0.15"
1641/// my-interfaces = { path = "../my-interfaces" }
1642/// ```
1643///
1644/// ```rust,no_run,ignore,ignore
1645/// // my-extension/src/lib.rs
1646/// use ext_php_rs::prelude::*;
1647/// use my_interfaces::Serializable;
1648///
1649/// #[php_class]
1650/// #[php(name = "MyExtension\\User")]
1651/// pub struct User {
1652///     name: String,
1653///     email: String,
1654/// }
1655///
1656/// #[php_impl]
1657/// impl User {
1658///     pub fn __construct(name: String, email: String) -> Self {
1659///         Self { name, email }
1660///     }
1661///
1662///     // Note: No need to add to_json() here - it's automatically
1663///     // registered by #[php_impl_interface] below
1664/// }
1665///
1666/// // Register the interface implementation
1667/// // This automatically registers to_json() as a PHP method
1668/// #[php_impl_interface]
1669/// impl Serializable for User {
1670///     fn to_json(&self) -> String {
1671///         format!(r#"{{"name":"{}","email":"{}"}}"#, self.name, self.email)
1672///     }
1673/// }
1674///
1675/// #[php_module]
1676/// pub fn module(module: ModuleBuilder) -> ModuleBuilder {
1677///     module
1678///         // Register the interface from the library crate
1679///         .interface::<my_interfaces::PhpInterfaceSerializable>()
1680///         .class::<User>()
1681/// }
1682/// ```
1683///
1684/// ### Using in PHP
1685///
1686/// ```php
1687/// <?php
1688///
1689/// use MyExtension\User;
1690/// use MyInterfaces\Serializable;
1691///
1692/// $user = new User("John", "john@example.com");
1693///
1694/// // instanceof works across crates
1695/// assert($user instanceof Serializable);
1696///
1697/// // Type hints work
1698/// function serialize_object(Serializable $obj): string {
1699///     return $obj->toJson();
1700/// }
1701///
1702/// echo serialize_object($user);
1703/// // Output: {"name":"John","email":"john@example.com"}
1704/// ```
1705///
1706/// ### Important Notes
1707///
1708/// 1. **Automatic method registration**: The `#[php_impl_interface]` macro
1709///    automatically registers all trait methods as PHP methods on the class.
1710///    You don't need to duplicate them in a `#[php_impl]` block.
1711///
1712/// 2. **Interface registration**: The interface must be registered in the
1713///    `#[php_module]` function using `.interface::<PhpInterfaceName>()`.
1714///
1715/// 3. **Link-time discovery**: The `inventory` crate uses link-time
1716///    registration for interface discovery, so all implementations are
1717///    automatically discovered when the final binary is linked.
1718///
1719/// 4. **Method names**: Each method gets the PHP name that `#[php_interface]`
1720///    declared for it. The trait's `change_method_case` and the `name` or
1721///    `change_case` of a trait method apply to the class too.
1722///    `#[php_impl_interface]` takes no arguments.
1723///
1724/// 5. **Sensitive parameters**: `#[php(sensitive(...))]` on a trait method also
1725///    applies to the class method, so exception traces from the class hide the
1726///    same arguments. The macro marks the argument at the same position, thus
1727///    the parameter names in the `impl` can be different. A PHP class that
1728///    implements the interface does not get the attribute, because PHP does not
1729///    copy parameter attributes from an interface. Declare
1730///    `#[\SensitiveParameter]` on its method.
1731// END DOCS FROM interface.md
1732#[proc_macro_attribute]
1733pub fn php_interface(args: TokenStream, input: TokenStream) -> TokenStream {
1734    php_interface_internal(args.into(), input.into()).into()
1735}
1736
1737#[allow(clippy::needless_pass_by_value)]
1738fn php_interface_internal(args: TokenStream2, input: TokenStream2) -> TokenStream2 {
1739    let input = parse_macro_input2!(input as ItemTrait);
1740    if let Err(e) = reject_args(&args, "php_interface", PHP_ATTR_HINT) {
1741        return e.to_compile_error();
1742    }
1743
1744    interface::parser(input).unwrap_or_else(|e| e.to_compile_error())
1745}
1746
1747// BEGIN DOCS FROM function.md
1748/// # `#[php_function]` Attribute
1749///
1750/// Used to annotate functions which should be exported to PHP. Note that this
1751/// should not be used on class methods - see the `#[php_impl]` macro for that.
1752///
1753/// See the [list of types](../types/index.md) that are valid as parameter and
1754/// return types. If the caller passes a value that the parameter type does not
1755/// accept, the call throws a `TypeError`.
1756///
1757/// A function accepts the `name`, `change_case`, `defaults`, `optional` and
1758/// `sensitive` options. PHP functions have no visibility, so `#[php(vis =
1759/// "...")]` is a compile error on a function.
1760///
1761/// ## Optional parameters
1762///
1763/// An `Option<T>` parameter accepts `null` and can be omitted. The macro reads
1764/// this from the type through `FromZvalMut::NULLABLE`, so a type alias such as
1765/// `type MaybeAge = Option<i64>` or the qualified path
1766/// `std::option::Option<i64>` behaves like `Option<i64>`. The trailing run of
1767/// parameters that are nullable or have a default value is optional.
1768///
1769/// ```rust,no_run,ignore
1770/// # #![cfg_attr(windows, feature(abi_vectorcall))]
1771/// # extern crate ext_php_rs;
1772/// use ext_php_rs::prelude::*;
1773///
1774/// #[php_function]
1775/// pub fn greet(name: String, age: Option<i32>) -> String {
1776///     let mut greeting = format!("Hello, {}!", name);
1777///
1778///     if let Some(age) = age {
1779///         greeting += &format!(" You are {} years old.", age);
1780///     }
1781///
1782///     greeting
1783/// }
1784///
1785/// #[php_module]
1786/// pub fn get_module(module: ModuleBuilder) -> ModuleBuilder {
1787///     module.function(wrap_function!(greet))
1788/// }
1789/// # fn main() {}
1790/// ```
1791///
1792/// Default parameter values can also be set for optional parameters. This is
1793/// done through the `#[php(defaults)]` attribute option. When an optional
1794/// parameter has a default, it does not need to be a variant of `Option`. The
1795/// default expression is converted into the parameter type with `Into`, and the
1796/// type must implement `StubLiteral`, which every scalar, string, `Option`,
1797/// `Vec` and `HashMap` does. The module renders the value once at load time
1798/// into the stub file and into `ReflectionParameter::getDefaultValue()`. Each
1799/// key in `defaults` must name a parameter of the function. If a key names no
1800/// parameter, the build fails:
1801///
1802/// ```rust,no_run,ignore
1803/// # #![cfg_attr(windows, feature(abi_vectorcall))]
1804/// # extern crate ext_php_rs;
1805/// use ext_php_rs::prelude::*;
1806///
1807/// #[php_function]
1808/// #[php(defaults(offset = 0))]
1809/// pub fn rusty_strpos(haystack: &str, needle: &str, offset: i64) -> Option<usize> {
1810///     let haystack: String = haystack.chars().skip(offset as usize).collect();
1811///     haystack.find(needle)
1812/// }
1813///
1814/// #[php_module]
1815/// pub fn get_module(module: ModuleBuilder) -> ModuleBuilder {
1816///     module.function(wrap_function!(rusty_strpos))
1817/// }
1818/// # fn main() {}
1819/// ```
1820///
1821/// Note that if there is a non-optional argument after an argument that is a
1822/// variant of `Option<T>`, the `Option<T>` argument will be deemed a nullable
1823/// argument rather than an optional argument.
1824///
1825/// ```rust,no_run,ignore
1826/// # #![cfg_attr(windows, feature(abi_vectorcall))]
1827/// # extern crate ext_php_rs;
1828/// use ext_php_rs::prelude::*;
1829///
1830/// /// `age` will be deemed required and nullable rather than optional.
1831/// #[php_function]
1832/// pub fn greet(name: String, age: Option<i32>, description: String) -> String {
1833///     let mut greeting = format!("Hello, {}!", name);
1834///
1835///     if let Some(age) = age {
1836///         greeting += &format!(" You are {} years old.", age);
1837///     }
1838///
1839///     greeting += &format!(" {}.", description);
1840///     greeting
1841/// }
1842///
1843/// #[php_module]
1844/// pub fn get_module(module: ModuleBuilder) -> ModuleBuilder {
1845///     module.function(wrap_function!(greet))
1846/// }
1847/// # fn main() {}
1848/// ```
1849///
1850/// You can also specify the optional arguments if you want to have nullable
1851/// arguments before optional arguments. This is done through the `optional`
1852/// attribute option, which names the first optional parameter. PHP callers can
1853/// omit that parameter and every parameter after it. Each of these parameters
1854/// must be an `Option<T>`, have a default, or be the variadic `&[T]` tail.
1855/// Otherwise the build fails with an error on the type of that parameter. If
1856/// `optional` names no parameter, the build also fails:
1857///
1858/// ```rust,no_run,ignore
1859/// # #![cfg_attr(windows, feature(abi_vectorcall))]
1860/// # extern crate ext_php_rs;
1861/// use ext_php_rs::prelude::*;
1862///
1863/// /// `age` will be deemed required and nullable rather than optional,
1864/// /// while description will be optional.
1865/// #[php_function]
1866/// #[php(optional = "description")]
1867/// pub fn greet(name: String, age: Option<i32>, description: Option<String>) -> String {
1868///     let mut greeting = format!("Hello, {}!", name);
1869///
1870///     if let Some(age) = age {
1871///         greeting += &format!(" You are {} years old.", age);
1872///     }
1873///
1874///     if let Some(description) = description {
1875///         greeting += &format!(" {}.", description);
1876///     }
1877///
1878///     greeting
1879/// }
1880///
1881/// #[php_module]
1882/// pub fn get_module(module: ModuleBuilder) -> ModuleBuilder {
1883///     module.function(wrap_function!(greet))
1884/// }
1885/// # fn main() {}
1886/// ```
1887///
1888/// ## Sensitive parameters
1889///
1890/// `#[php(sensitive(...))]` names parameters that PHP declares
1891/// [`#[\SensitiveParameter]`](https://www.php.net/manual/en/class.sensitiveparameter.php),
1892/// as it does for `password_hash()`'s password. When an exception is thrown,
1893/// its trace holds a `SensitiveParameterValue` in place of the value, so a
1894/// password or connection string does not reach logs or error trackers. Each
1895/// name must be a parameter of the function. It has no effect before PHP 8.2,
1896/// which introduced the attribute.
1897///
1898/// ```rust,no_run,ignore
1899/// # #![cfg_attr(windows, feature(abi_vectorcall))]
1900/// # extern crate ext_php_rs;
1901/// use ext_php_rs::prelude::*;
1902///
1903/// #[php_function]
1904/// #[php(sensitive(password))]
1905/// pub fn login(user: String, password: String) -> PhpResult<bool> {
1906///     let _ = password;
1907///     Err(PhpException::from_message(format!("Unknown user {user}")))
1908/// }
1909///
1910/// #[php_module]
1911/// pub fn get_module(module: ModuleBuilder) -> ModuleBuilder {
1912///     module.function(wrap_function!(login))
1913/// }
1914/// # fn main() {}
1915/// ```
1916///
1917/// ## Variadic Functions
1918///
1919/// A slice parameter `&[T]` in last position is variadic, the equivalent of the
1920/// PHP `...$args` syntax. `T` is any argument type: `&[&Zval]` receives the raw
1921/// values, `&[i64]` receives converted integers. If one of the values cannot be
1922/// converted into `T`, the call throws a `TypeError`. If one of the values is a
1923/// class object whose Rust value is borrowed or not initialized, the call
1924/// throws an `Error`, see [Class Arguments](./classes.md#class-arguments). A variadic parameter that is
1925/// not the last parameter is a compile error. The slice must be spelled in the
1926/// signature; a type alias that hides the slice is not detected.
1927///
1928/// ```rust,no_run,ignore
1929/// # #![cfg_attr(windows, feature(abi_vectorcall))]
1930/// # extern crate ext_php_rs;
1931/// use ext_php_rs::{prelude::*, types::Zval};
1932///
1933/// /// This can be called from PHP as `add(1, 2, 3, 4, 5)`
1934/// #[php_function]
1935/// pub fn add(number: u32, numbers:&[&Zval]) -> u32 {
1936///     // numbers is a slice of 4 Zvals all of type long
1937///     number
1938/// }
1939///
1940/// #[php_module]
1941/// pub fn get_module(module: ModuleBuilder) -> ModuleBuilder {
1942///     module.function(wrap_function!(add))
1943/// }
1944/// # fn main() {}
1945/// ```
1946///
1947/// ## Performance
1948///
1949/// The `#[php_function]` macro generates a zero-allocation fast path that reads
1950/// arguments directly from the PHP call frame, matching how native C extensions
1951/// parse parameters. This applies automatically — no configuration needed.
1952///
1953/// The same fast path is used for class methods defined with `#[php_impl]`,
1954/// including instance methods (`&self`, `&mut self`), static methods and
1955/// constructors.
1956///
1957/// ```rust,no_run,ignore
1958/// # #![cfg_attr(windows, feature(abi_vectorcall))]
1959/// # extern crate ext_php_rs;
1960/// # use ext_php_rs::prelude::*;
1961/// // Fast path: standalone functions
1962/// #[php_function]
1963/// pub fn fast(name: String, age: Option<i32>) -> String { name }
1964///
1965/// // Fast path: parameters with defaults
1966/// #[php_function]
1967/// #[php(defaults(offset = 0))]
1968/// pub fn also_fast(haystack: &str, offset: i64) -> i64 { offset }
1969/// # fn main() {}
1970/// ```
1971///
1972/// ```rust,ignore
1973/// #[php_impl]
1974/// impl MyClass {
1975///     // Fast path: constructors
1976///     pub fn __construct(n: i32) -> Self { /* ... */ }
1977///
1978///     // Fast path: static methods
1979///     pub fn create(n: i32) -> Self { /* ... */ }
1980///
1981///     // Fast path: instance methods
1982///     pub fn get_value(&self, offset: i32) -> i32 { /* ... */ }
1983/// }
1984/// ```
1985///
1986/// The only case that falls back to the runtime argument parser is when using
1987/// variadic arguments (`&[T]`, the Rust equivalent of PHP's `...$args`):
1988///
1989/// ```rust,no_run,ignore
1990/// # #![cfg_attr(windows, feature(abi_vectorcall))]
1991/// # extern crate ext_php_rs;
1992/// # use ext_php_rs::{prelude::*, types::Zval};
1993/// // Slower path: variadic arguments require runtime parsing
1994/// #[php_function]
1995/// pub fn add(first: u32, rest: &[&Zval]) -> u32 { first }
1996/// # fn main() {}
1997/// ```
1998///
1999/// ## Returning `Result<T, E>`
2000///
2001/// You can also return a `Result` from the function. The error variant will be
2002/// translated into an exception and thrown. See the section on
2003/// [exceptions](../exceptions.md) for more details.
2004// END DOCS FROM function.md
2005#[proc_macro_attribute]
2006pub fn php_function(args: TokenStream, input: TokenStream) -> TokenStream {
2007    php_function_internal(args.into(), input.into()).into()
2008}
2009
2010#[allow(clippy::needless_pass_by_value)]
2011fn php_function_internal(args: TokenStream2, input: TokenStream2) -> TokenStream2 {
2012    let input = parse_macro_input2!(input as ItemFn);
2013    if let Err(e) = reject_args(&args, "php_function", PHP_ATTR_HINT) {
2014        return e.to_compile_error();
2015    }
2016
2017    function::parser(input).unwrap_or_else(|e| e.to_compile_error())
2018}
2019
2020// BEGIN DOCS FROM constant.md
2021/// # `#[php_const]` Attribute
2022///
2023/// Exports a Rust constant as a global PHP constant. The constant can be any
2024/// type that implements `IntoConst`.
2025///
2026/// The `wrap_constant!()` macro can be used to simplify the registration of
2027/// constants. It sets the name and doc comments for the constant.
2028///
2029/// You can rename the const with options:
2030///
2031/// - `name` - Allows you to rename the property, e.g. `#[php(name =
2032///   "new_name")]`
2033/// - `change_case` - Allows you to rename the property using rename rules, e.g.
2034///   `#[php(change_case = "PascalCase")]`
2035///
2036/// A global constant has no visibility. `#[php(vis = "...")]` on a
2037/// `#[php_const]` is a compile error. Use `vis` on constants inside a
2038/// `#[php_impl]` block.
2039///
2040/// ## Examples
2041///
2042/// ```rust,no_run,ignore
2043/// # #![cfg_attr(windows, feature(abi_vectorcall))]
2044/// # extern crate ext_php_rs;
2045/// use ext_php_rs::prelude::*;
2046///
2047/// #[php_const]
2048/// const TEST_CONSTANT: i32 = 100;
2049///
2050/// #[php_const]
2051/// #[php(name = "I_AM_RENAMED")]
2052/// const TEST_CONSTANT_THE_SECOND: i32 = 42;
2053///
2054/// #[php_const]
2055/// const ANOTHER_STRING_CONST: &'static str = "Hello world!";
2056///
2057/// #[php_module]
2058/// pub fn get_module(module: ModuleBuilder) -> ModuleBuilder {
2059///     module
2060///         .constant(wrap_constant!(TEST_CONSTANT))
2061///         .constant(wrap_constant!(TEST_CONSTANT_THE_SECOND))
2062///         .constant(("MANUAL_CONSTANT", ANOTHER_STRING_CONST, &[]))
2063/// }
2064/// # fn main() {}
2065/// ```
2066///
2067/// ## PHP usage
2068///
2069/// ```php
2070/// <?php
2071///
2072/// var_dump(TEST_CONSTANT); // int(100)
2073/// var_dump(I_AM_RENAMED); // int(42)
2074/// var_dump(MANUAL_CONSTANT); // string(12) "Hello world!"
2075/// ```
2076// END DOCS FROM constant.md
2077#[proc_macro_attribute]
2078pub fn php_const(args: TokenStream, input: TokenStream) -> TokenStream {
2079    php_const_internal(args.into(), input.into()).into()
2080}
2081
2082#[allow(clippy::needless_pass_by_value)]
2083fn php_const_internal(args: TokenStream2, input: TokenStream2) -> TokenStream2 {
2084    let input = parse_macro_input2!(input as ItemConst);
2085    if let Err(e) = reject_args(&args, "php_const", PHP_ATTR_HINT) {
2086        return e.to_compile_error();
2087    }
2088
2089    constant::parser(input).unwrap_or_else(|e| e.to_compile_error())
2090}
2091
2092// BEGIN DOCS FROM module.md
2093/// # `#[php_module]` Attribute
2094///
2095/// The module macro is used to annotate the `get_module` function, which is
2096/// used by the PHP interpreter to retrieve information about your extension,
2097/// including the name, version, functions and extra initialization functions.
2098/// Regardless if you use this macro, your extension requires a `extern "C" fn
2099/// get_module()` so that PHP can get this information.
2100///
2101/// The function is renamed to `get_module` if you have used another name. The
2102/// macro also exports a crate-prefixed `<crate_name>_get_module` alias, used
2103/// when [statically linking the extension into php-src](../advanced/static_linking.md).
2104/// Building with `EXT_PHP_RS_STATIC_EXT=1` removes the unmangled `get_module`
2105/// export (the function itself stays callable from Rust) so a statically linked
2106/// extension cannot collide with another extension exporting `get_module`.
2107/// Dynamic builds (`extension=` / `dl()`) must not set the variable.
2108///
2109/// The function is passed an instance of `ModuleBuilder` which allows you to
2110/// register the following (if required):
2111///
2112/// - Functions, classes, and constants
2113/// - Extension and request startup and shutdown functions.
2114///   - Read more about the PHP extension lifecycle [here](https://www.phpinternalsbook.com/php7/extensions_design/php_lifecycle.html).
2115/// - PHP extension information function
2116///   - Used by the `phpinfo()` function to get information about your
2117///     extension.
2118///
2119/// Classes and constants are not registered with PHP in the `get_module`
2120/// function. These are registered inside the extension startup function.
2121///
2122/// ## Startup failures
2123///
2124/// If a constant, an interface, a class or an enum cannot be registered, the
2125/// generated startup function logs the cause as an `E_CORE_WARNING` and returns
2126/// `FAILURE`. PHP then reports `Unable to start <extension> module`. At engine
2127/// startup PHP exits. From `dl()` the request fails. A panic during
2128/// registration gets the same treatment. The process does not abort in either
2129/// case.
2130///
2131/// `get_module` cannot report a failure, because PHP reads the returned entry
2132/// without a check. If the `ModuleBuilder` cannot become a module entry, for
2133/// example because a function name, an argument name or the module name
2134/// contains a NUL byte, the macro returns a placeholder entry with the name of
2135/// the crate. The startup function of that entry logs the build error and fails
2136/// as described above.
2137///
2138/// The `startup` function that you name in `#[php(startup = ...)]` is your own
2139/// `extern "C"` function. A panic inside it is not caught.
2140///
2141/// You can also give a startup function to `ModuleBuilder::startup_function`.
2142/// The generated startup function calls it after the `#[php(startup = ...)]`
2143/// function. The two functions run before the macro registers the constants,
2144/// interfaces, classes and enums.
2145///
2146/// ## Usage
2147///
2148/// ```rust,no_run,ignore
2149/// # #![cfg_attr(windows, feature(abi_vectorcall))]
2150/// # extern crate ext_php_rs;
2151/// use ext_php_rs::{
2152///     prelude::*,
2153///     zend::ModuleEntry,
2154///     info_table_start,
2155///     info_table_row,
2156///     info_table_end
2157/// };
2158///
2159/// #[php_const]
2160/// pub const MY_CUSTOM_CONST: &'static str = "Hello, world!";
2161///
2162/// #[php_class]
2163/// pub struct Test {
2164///     a: i32,
2165///     b: i32
2166/// }
2167/// #[php_function]
2168/// pub fn hello_world() -> &'static str {
2169///     "Hello, world!"
2170/// }
2171///
2172/// /// Used by the `phpinfo()` function and when you run `php -i`.
2173/// /// This will probably be simplified with another macro eventually!
2174/// pub extern "C" fn php_module_info(_module: *mut ModuleEntry) {
2175///     info_table_start!();
2176///     info_table_row!("my extension", "enabled");
2177///     info_table_end!();
2178/// }
2179///
2180/// #[php_module]
2181/// pub fn get_module(module: ModuleBuilder) -> ModuleBuilder {
2182///     module
2183///         .constant(wrap_constant!(MY_CUSTOM_CONST))
2184///         .class::<Test>()
2185///         .function(wrap_function!(hello_world))
2186///         .info_function(php_module_info)
2187/// }
2188/// # fn main() {}
2189/// ```
2190// END DOCS FROM module.md
2191#[proc_macro_attribute]
2192pub fn php_module(args: TokenStream, input: TokenStream) -> TokenStream {
2193    php_module_internal(args.into(), input.into()).into()
2194}
2195
2196#[allow(clippy::needless_pass_by_value)]
2197fn php_module_internal(args: TokenStream2, input: TokenStream2) -> TokenStream2 {
2198    let input = parse_macro_input2!(input as ItemFn);
2199    if let Err(e) = reject_args(&args, "php_module", PHP_ATTR_HINT) {
2200        return e.to_compile_error();
2201    }
2202
2203    module::parser(input).unwrap_or_else(|e| e.to_compile_error())
2204}
2205
2206// BEGIN DOCS FROM impl.md
2207/// # `#[php_impl]` Attribute
2208///
2209/// You can export an entire `impl` block to PHP. This exports all methods as
2210/// well as constants to PHP on the class that it is implemented on. This
2211/// requires the `#[php_class]` macro to already be used on the underlying
2212/// struct. Trait implementations cannot be exported to PHP. Only one `impl`
2213/// block can be exported per class.
2214///
2215/// If you do not want a function exported to PHP, you should place it in a
2216/// separate `impl` block.
2217///
2218/// If you want to use async Rust, use `#[php_async_impl]`, instead: see [here &raquo;](./async_impl.md) for more info.
2219///
2220/// ## Options
2221///
2222/// By default all constants are renamed to `UPPER_CASE` and all methods are
2223/// renamed to camelCase. This can be changed by passing the
2224/// `change_method_case` and `change_constant_case` as `#[php]` attributes on
2225/// the `impl` block. The options are:
2226///
2227/// - `#[php(change_method_case = "snake_case")]` - Renames the method to snake
2228///   case.
2229/// - `#[php(change_constant_case = "snake_case")]` - Renames the constant to
2230///   snake case.
2231///
2232/// See the [`name` and `change_case`](./php.md#name-and-change_case) section for a list of all
2233/// available cases.
2234///
2235/// ## Methods
2236///
2237/// Methods basically follow the same rules as functions, so read about the
2238/// [`php_function`] macro first. The primary difference between functions and
2239/// methods is they are bounded by their class object.
2240///
2241/// Instance methods, static methods and constructors benefit from the same
2242/// zero-allocation fast path as standalone functions. See the [Performance](./function.md#performance)
2243/// section for details.
2244///
2245/// Class methods can take a `&self` or `&mut self` parameter. They cannot take
2246/// a consuming `self` parameter. Static methods can omit this `self` parameter.
2247///
2248/// To access the Zend object, use `self_: &ZendClassObject<Self>` in place of
2249/// the self parameter. The parameter must have the name `self_`. Borrow the
2250/// Rust value with `self_.try_borrow()` or `self_.try_borrow_mut()`. You can
2251/// also return `self_` to return `$this`. A `&mut ZendClassObject<Self>`
2252/// parameter does not compile. Refer to [Access to the Rust Value](./classes.md#access-to-the-rust-value)
2253/// for the borrow rules.
2254///
2255/// The rest of the options are passed as separate attributes:
2256///
2257/// - `#[php(defaults(i = 5, b = "\"hello\""))]` - Sets the default value for
2258///   parameter(s). Each key must name a parameter.
2259/// - `#[php(optional = i)]` - Sets the first optional parameter. Note that this
2260///   also sets the remaining parameters as optional, so each of them must be an
2261///   `Option<T>` or have a default. Otherwise the build fails.
2262/// - `#[php(sensitive(password))]` - Declares the named parameter(s)
2263///   `#[\SensitiveParameter]`, so exception traces hide their values. See
2264///   [sensitive parameters](./function.md#sensitive-parameters).
2265/// - `#[php(vis = "public")]`, `#[php(vis = "protected")]` and `#[php(vis =
2266///   "private")]` - Sets the visibility of the method.
2267/// - `#[php(name = "method_name")]` - Renames the PHP method to a different
2268///   identifier, without renaming the Rust method name.
2269/// - `#[php(final)]` - Makes the method final (cannot be overridden in
2270///   subclasses).
2271/// - `#[php(abstract)]` - Makes the method abstract (must be implemented by
2272///   subclasses). Can only be used in abstract classes.
2273///
2274/// The `#[php(defaults)]` and `#[php(optional)]` attributes operate the same as
2275/// the equivalent function attribute parameters. A `self_` parameter is the PHP
2276/// object, not a PHP parameter, so `defaults` and `optional` cannot name it. A
2277/// `getter` or `setter` method accepts neither option.
2278///
2279/// ### Static Methods
2280///
2281/// Methods that do not take a `&self` or `&mut self` parameter are
2282/// automatically exported as static methods. These can be called on the class
2283/// itself without creating an instance.
2284///
2285/// ```rust,ignore
2286/// #[php_impl]
2287/// impl MyClass {
2288///     // Static method - no self parameter
2289///     pub fn create_default() -> Self {
2290///         Self { /* ... */ }
2291///     }
2292///
2293///     // Instance method - takes &self
2294///     pub fn get_value(&self) -> i32 {
2295///         self.value
2296///     }
2297/// }
2298/// ```
2299///
2300/// From PHP:
2301///
2302/// ```php
2303/// $obj = MyClass::createDefault(); // Static call
2304/// $val = $obj->getValue();         // Instance call
2305/// ```
2306///
2307/// ### Final Methods
2308///
2309/// Methods marked with `#[php(final)]` cannot be overridden in subclasses. This
2310/// is useful when you want to prevent modification of critical functionality.
2311///
2312/// ```rust,ignore
2313/// use ext_php_rs::prelude::*;
2314///
2315/// #[php_class]
2316/// pub struct SecureClass;
2317///
2318/// #[php_impl]
2319/// impl SecureClass {
2320///     #[php(final)]
2321///     pub fn secure_method(&self) -> &str {
2322///         "This cannot be overridden"
2323///     }
2324///
2325///     // Final static methods are also supported
2326///     #[php(final)]
2327///     pub fn secure_static() -> i32 {
2328///         42
2329///     }
2330/// }
2331/// ```
2332///
2333/// ### Abstract Methods
2334///
2335/// Methods marked with `#[php(abstract)]` must be implemented by subclasses.
2336/// Abstract methods can only be defined in abstract classes (classes with
2337/// `ClassFlags::Abstract`).
2338///
2339/// ```rust,ignore
2340/// use ext_php_rs::prelude::*;
2341/// use ext_php_rs::flags::ClassFlags;
2342///
2343/// #[php_class]
2344/// #[php(flags = ClassFlags::Abstract)]
2345/// pub struct AbstractShape;
2346///
2347/// #[php_impl]
2348/// impl AbstractShape {
2349///     // Protected constructor for subclasses
2350///     #[php(vis = "protected")]
2351///     pub fn __construct() -> Self {
2352///         Self
2353///     }
2354///
2355///     // Abstract method - subclasses must implement this.
2356///     // The body is never called; use unimplemented!() as a placeholder.
2357///     #[php(abstract)]
2358///     pub fn area(&self) -> f64 {
2359///         unimplemented!()
2360///     }
2361///
2362///     // Concrete method in abstract class
2363///     pub fn describe(&self) -> String {
2364///         format!("A shape with area {}", self.area())
2365///     }
2366/// }
2367/// ```
2368///
2369/// **Note:** Abstract method bodies are never called - they exist only because
2370/// Rust syntax requires a body for methods in `impl` blocks. Use
2371/// `unimplemented!()` as a clear placeholder.
2372///
2373/// **Note:** If you try to use `#[php(abstract)]` on a method in a non-abstract
2374/// class, you will get a compile-time error.
2375///
2376/// **Note:** PHP does not support abstract static methods. If you need static
2377/// behavior that can be customized by subclasses, use a regular instance method
2378/// or the [late static binding](https://www.php.net/manual/en/language.oop5.late-static-bindings.php)
2379/// pattern in PHP.
2380///
2381/// ### Constructors
2382///
2383/// By default, if a class does not have a constructor, it is not constructable
2384/// from PHP. It can only be returned from a Rust function to PHP.
2385///
2386/// With `#[php(no_constructor)]` on a struct that implements `Default`, the
2387/// class declares no constructor instead, as a PHP class without one: `new`, on
2388/// the class or on a PHP subclass, creates an object initialized with
2389/// `Default::default()`, and `ReflectionClass::getConstructor()` returns
2390/// `null`. An exception class extending `\Exception` inherits
2391/// `Exception::__construct`. Under a Rust class that declares a constructor,
2392/// the class keeps the one that throws, since the parent's would run on an
2393/// object of another type.
2394///
2395/// Constructors are Rust methods which can take any amount of parameters and
2396/// returns either `Self` or `Result<Self, E>`, where `E: Into<PhpException>`.
2397/// When the error variant of `Result` is encountered, it is thrown as an
2398/// exception and the class is not constructed.
2399///
2400/// Constructors are designated by either naming the method `__construct` or by
2401/// annotating a method with the `#[php(constructor)]` attribute. Note that when
2402/// using the attribute, the function is not exported to PHP like a regular
2403/// method.
2404///
2405/// Constructors cannot use the visibility or rename attributes listed above.
2406///
2407/// ## Constants
2408///
2409/// Constants are defined as regular Rust `impl` constants. Any type that
2410/// implements `IntoZval` can be used as a constant. A constant accepts the
2411/// `name`, `change_case` and `vis` options. The default visibility is `public`.
2412///
2413/// ```rust,no_run,ignore
2414/// # #![cfg_attr(windows, feature(abi_vectorcall))]
2415/// # extern crate ext_php_rs;
2416/// # use ext_php_rs::prelude::*;
2417/// #[php_class]
2418/// pub struct Limits;
2419///
2420/// #[php_impl]
2421/// impl Limits {
2422///     const MAX_USERS: i64 = 100;
2423///
2424///     #[php(vis = "protected")]
2425///     const MAX_RETRIES: i64 = 3;
2426///
2427///     #[php(vis = "private", name = "SEED")]
2428///     const RANDOM_SEED: i64 = 42;
2429/// }
2430/// # fn main() {}
2431/// ```
2432///
2433/// PHP sees `public const MAX_USERS`, `protected const MAX_RETRIES` and
2434/// `private const SEED`. Reflection reports the same visibility, and the
2435/// generated stubs print it.
2436///
2437/// ## Property getters and setters
2438///
2439/// A class can expose a property whose value comes from Rust methods. Mark the
2440/// method that reads the value with `#[php(getter)]` and the method that writes
2441/// it with `#[php(setter)]`. The property name is the method name without its
2442/// `get_` or `set_` prefix, converted to camelCase. This is the same rule as
2443/// for `#[php(prop)]` fields: `get_first_name` gives the property `firstName`.
2444/// Properties are declared in the order in which their first
2445/// getter or setter appears in the `impl` block, after the `#[php(prop)]` field
2446/// properties of the struct.
2447///
2448/// If you want a different property name, pass a `name` or `change_case` option
2449/// to the `#[php]` attribute: `#[php(getter, name = "first_name")]` or
2450/// `#[php(getter, change_case = "snake_case")]`.
2451///
2452/// A property does not need both methods. A property with only a getter is
2453/// read-only. A property with only a setter is write-only.
2454///
2455/// One method cannot be both a getter and a setter. A property cannot have two
2456/// getters or two setters. The getter and the setter of one property must have
2457/// the same visibility. Each of these cases is a compile error.
2458///
2459/// A method property cannot have the same name as a `#[php(prop)]` field of the
2460/// struct. The two macros are expanded separately, so this is not a compile
2461/// error. The extension fails to load with this error:
2462///
2463/// ```text
2464/// property `Book::$title` is declared twice
2465/// ```
2466///
2467/// The PHP type of the property comes from the return type of the getter. If
2468/// the property has no getter, the type comes from the argument of the setter.
2469/// The documentation of the property comes from the getter, or from the setter
2470/// when the getter has none. Like field properties, the type must implement
2471/// `IntoZval` and `FromZval`.
2472///
2473/// ## Example
2474///
2475/// Continuing on from our `Human` example in the structs section, we will
2476/// define a constructor, as well as getters for the properties. We will also
2477/// define a constant for the maximum age of a `Human`.
2478///
2479/// ```rust,no_run,ignore
2480/// # #![cfg_attr(windows, feature(abi_vectorcall))]
2481/// # extern crate ext_php_rs;
2482/// use ext_php_rs::{prelude::*, types::ZendClassObject};
2483///
2484/// #[php_class]
2485/// #[derive(Debug, Default)]
2486/// pub struct Human {
2487///     name: String,
2488///     age: i32,
2489///     #[php(prop)]
2490///     address: String,
2491/// }
2492///
2493/// #[php_impl]
2494/// impl Human {
2495///     const MAX_AGE: i32 = 100;
2496///
2497///     // No `#[constructor]` attribute required here - the name is `__construct`.
2498///     pub fn __construct(name: String, age: i32) -> Self {
2499///         Self {
2500///             name,
2501///             age,
2502///             address: String::new()
2503///         }
2504///     }
2505///
2506///     #[php(getter)]
2507///     pub fn get_name(&self) -> String {
2508///         self.name.to_string()
2509///     }
2510///
2511///     #[php(setter)]
2512///     pub fn set_name(&mut self, name: String) {
2513///         self.name = name;
2514///     }
2515///
2516///     #[php(getter)]
2517///     pub fn get_age(&self) -> i32 {
2518///         self.age
2519///     }
2520///
2521///     pub fn introduce(&self) {
2522///         println!("My name is {} and I am {} years old. I live at {}.", self.name, self.age, self.address);
2523///     }
2524///
2525///     pub fn get_raw_obj(self_: &ZendClassObject<Human>) -> &ZendClassObject<Human> {
2526///         dbg!(self_)
2527///     }
2528///
2529///     pub fn get_max_age() -> i32 {
2530///         Self::MAX_AGE
2531///     }
2532/// }
2533/// #[php_module]
2534/// pub fn get_module(module: ModuleBuilder) -> ModuleBuilder {
2535///     module.class::<Human>()
2536/// }
2537/// # fn main() {}
2538/// ```
2539///
2540/// Using our newly created class in PHP:
2541///
2542/// ```php
2543/// <?php
2544///
2545/// $me = new Human('David', 20);
2546///
2547/// $me->introduce(); // My name is David and I am 20 years old.
2548/// var_dump(Human::get_max_age()); // int(100)
2549/// var_dump(Human::MAX_AGE); // int(100)
2550/// ```
2551///
2552/// [`php_async_impl`]: ./async_impl.md
2553// END DOCS FROM impl.md
2554#[proc_macro_attribute]
2555pub fn php_impl(args: TokenStream, input: TokenStream) -> TokenStream {
2556    php_impl_internal(args.into(), input.into()).into()
2557}
2558
2559#[allow(clippy::needless_pass_by_value)]
2560fn php_impl_internal(args: TokenStream2, input: TokenStream2) -> TokenStream2 {
2561    let input = parse_macro_input2!(input as ItemImpl);
2562    if let Err(e) = reject_args(&args, "php_impl", PHP_ATTR_HINT) {
2563        return e.to_compile_error();
2564    }
2565
2566    impl_::parser(input).unwrap_or_else(|e| e.to_compile_error())
2567}
2568
2569/// # `#[php_impl_interface]` Attribute
2570///
2571/// Marks a trait implementation as implementing a PHP interface. This allows
2572/// Rust structs marked with `#[php_class]` to implement Rust traits marked
2573/// with `#[php_interface]`, and have PHP recognize the relationship.
2574///
2575/// **Key feature**: The macro automatically registers the trait methods as PHP
2576/// methods on the class. You don't need to duplicate them in a separate
2577/// `#[php_impl]` block.
2578///
2579/// ## Usage
2580///
2581/// ```rust,no_run,ignore
2582/// # #![cfg_attr(windows, feature(abi_vectorcall))]
2583/// # extern crate ext_php_rs;
2584/// use ext_php_rs::prelude::*;
2585///
2586/// #[php_interface]
2587/// trait MyInterface {
2588///     fn my_method(&self) -> String;
2589/// }
2590///
2591/// #[php_class]
2592/// struct MyClass;
2593///
2594/// // The trait method my_method() is automatically registered as a PHP method
2595/// #[php_impl_interface]
2596/// impl MyInterface for MyClass {
2597///     fn my_method(&self) -> String {
2598///         "Hello from MyClass!".to_string()
2599///     }
2600/// }
2601///
2602/// #[php_module]
2603/// pub fn get_module(module: ModuleBuilder) -> ModuleBuilder {
2604///     module
2605///         .interface::<PhpInterfaceMyInterface>()
2606///         .class::<MyClass>()
2607/// }
2608/// # fn main() {}
2609/// ```
2610///
2611/// After registration, PHP's `is_a($obj, 'MyInterface')` will return `true`
2612/// for instances of `MyClass`, and `$obj->myMethod()` will be callable.
2613///
2614/// ## Method names
2615///
2616/// Each method is registered under the name that `#[php_interface]` gave it.
2617/// The trait's `change_method_case` and the `name` or `change_case` of a trait
2618/// method apply to the class too. The macro takes no arguments:
2619/// `#[php_impl_interface(change_method_case = "...")]` is a compile error.
2620///
2621/// ## Requirements
2622///
2623/// - The trait must be marked with `#[php_interface]`
2624/// - The struct must be marked with `#[php_class]`
2625/// - The interface must be registered before the class in the module builder
2626#[proc_macro_attribute]
2627pub fn php_impl_interface(args: TokenStream, input: TokenStream) -> TokenStream {
2628    php_impl_interface_internal(args.into(), input.into()).into()
2629}
2630
2631#[allow(clippy::needless_pass_by_value)]
2632fn php_impl_interface_internal(args: TokenStream2, input: TokenStream2) -> TokenStream2 {
2633    let input = parse_macro_input2!(input as ItemImpl);
2634    let attr_args = match darling::ast::NestedMeta::parse_meta_list(args) {
2635        Ok(v) => v,
2636        Err(e) => return e.to_compile_error(),
2637    };
2638    let args = match impl_interface::PhpImplInterfaceArgs::from_list(&attr_args) {
2639        Ok(v) => v,
2640        Err(e) => return e.write_errors(),
2641    };
2642
2643    impl_interface::parser(&args, &input).unwrap_or_else(|e| e.to_compile_error())
2644}
2645
2646// BEGIN DOCS FROM extern.md
2647/// # `#[php_extern]` Attribute
2648///
2649/// Attribute used to annotate `extern` blocks which are deemed as PHP
2650/// functions.
2651///
2652/// This allows you to 'import' PHP functions into Rust so that they can be
2653/// called like regular Rust functions. Parameters can be any type that
2654/// implements [`IntoZval`], and the return type can be anything that implements
2655/// [`From<Zval>`] (notice how [`Zval`] is consumed rather than borrowed in this
2656/// case).
2657///
2658/// Unlike most other attributes, this does not need to be placed inside a
2659/// `#[php_module]` block.
2660///
2661/// # Panics
2662///
2663/// The function can panic when called under a few circumstances:
2664///
2665/// * The function could not be found or was not callable.
2666/// * One of the parameters could not be converted into a [`Zval`].
2667/// * The actual function call failed internally.
2668/// * The output [`Zval`] could not be parsed into the output type.
2669///
2670/// Inside a function that PHP calls, these panics become a PHP `Error`. The
2671/// process does not abort. See [Exceptions](../exceptions.md#panics).
2672///
2673/// The last point can be important when interacting with functions that return
2674/// unions, such as [`strpos`] which can return an integer or a boolean. In this
2675/// case, a [`Zval`] should be returned as parsing a boolean to an integer is
2676/// invalid, and vice versa.
2677///
2678/// # Example
2679///
2680/// This `extern` block imports the [`strpos`] function from PHP. Notice that
2681/// the string parameters can take either [`String`] or [`&str`], the optional
2682/// parameter `offset` is an [`Option<i64>`], and the return value is a [`Zval`]
2683/// as the return type is an integer-boolean union.
2684///
2685/// ```rust,no_run,ignore
2686/// # #![cfg_attr(windows, feature(abi_vectorcall))]
2687/// # extern crate ext_php_rs;
2688/// use ext_php_rs::{
2689///     prelude::*,
2690///     types::Zval,
2691/// };
2692///
2693/// #[php_extern]
2694/// extern "C" {
2695///     fn strpos(haystack: &str, needle: &str, offset: Option<i64>) -> Zval;
2696/// }
2697///
2698/// #[php_function]
2699/// pub fn my_strpos() {
2700///     assert_eq!(unsafe { strpos("Hello", "e", None) }.long(), Some(1));
2701/// }
2702///
2703/// #[php_module]
2704/// pub fn module(module: ModuleBuilder) -> ModuleBuilder {
2705///     module.function(wrap_function!(my_strpos))
2706/// }
2707/// # fn main() {}
2708/// ```
2709///
2710/// [`strpos`]: https://www.php.net/manual/en/function.strpos.php
2711/// [`IntoZval`]: crate::convert::IntoZval
2712/// [`Zval`]: crate::types::Zval
2713// END DOCS FROM extern.md
2714#[proc_macro_attribute]
2715pub fn php_extern(args: TokenStream, input: TokenStream) -> TokenStream {
2716    php_extern_internal(args.into(), input.into()).into()
2717}
2718
2719#[allow(clippy::needless_pass_by_value)]
2720fn php_extern_internal(args: TokenStream2, input: TokenStream2) -> TokenStream2 {
2721    let input = parse_macro_input2!(input as ItemForeignMod);
2722    if let Err(e) = reject_args(&args, "php_extern", NO_ARGS_HINT) {
2723        return e.to_compile_error();
2724    }
2725
2726    extern_::parser(input).unwrap_or_else(|e| e.to_compile_error())
2727}
2728
2729// BEGIN DOCS FROM zval_convert.md
2730/// # `ZvalConvert` Derive Macro
2731///
2732/// The `#[derive(ZvalConvert)]` macro derives the `FromZval` and `IntoZval`
2733/// traits on a struct or enum.
2734///
2735/// ## Structs
2736///
2737/// When used on a struct, the `FromZendObject` and `IntoZendObject` traits are
2738/// also implemented, mapping fields to properties in both directions. All
2739/// fields on the struct must implement `FromZval` as well. Generics are allowed
2740/// on structs that use the derive macro, however, the implementation will add a
2741/// `FromZval` bound to all generics types.
2742///
2743/// ### Examples
2744///
2745/// ```rust,no_run,ignore
2746/// # #![cfg_attr(windows, feature(abi_vectorcall))]
2747/// # extern crate ext_php_rs;
2748/// use ext_php_rs::prelude::*;
2749///
2750/// #[derive(ZvalConvert)]
2751/// pub struct ExampleClass<'a> {
2752///     a: i32,
2753///     b: String,
2754///     c: &'a str
2755/// }
2756///
2757/// #[php_function]
2758/// pub fn take_object(obj: ExampleClass) {
2759///     dbg!(obj.a, obj.b, obj.c);
2760/// }
2761///
2762/// #[php_function]
2763/// pub fn give_object() -> ExampleClass<'static> {
2764///     ExampleClass {
2765///         a: 5,
2766///         b: "String".to_string(),
2767///         c: "Borrowed",
2768///     }
2769/// }
2770///
2771/// #[php_module]
2772/// pub fn get_module(module: ModuleBuilder) -> ModuleBuilder {
2773///     module
2774///         .function(wrap_function!(take_object))
2775///         .function(wrap_function!(give_object))
2776/// }
2777/// # fn main() {}
2778/// ```
2779///
2780/// Calling from PHP:
2781///
2782/// ```php
2783/// <?php
2784///
2785/// $obj = new stdClass;
2786/// $obj->a = 5;
2787/// $obj->b = 'Hello, world!';
2788/// $obj->c = 'another string';
2789///
2790/// take_object($obj);
2791/// var_dump(give_object());
2792/// ```
2793///
2794/// Another example involving generics:
2795///
2796/// ```rust,no_run,ignore
2797/// # #![cfg_attr(windows, feature(abi_vectorcall))]
2798/// # extern crate ext_php_rs;
2799/// use ext_php_rs::prelude::*;
2800///
2801/// // T must implement both `PartialEq<i32>` and `FromZval`.
2802/// #[derive(Debug, ZvalConvert)]
2803/// pub struct CompareVals<T: PartialEq<i32>> {
2804///     a: T,
2805///     b: T
2806/// }
2807///
2808/// #[php_function]
2809/// pub fn take_object(obj: CompareVals<i32>) {
2810///     dbg!(obj);
2811/// }
2812///
2813/// #[php_module]
2814/// pub fn get_module(module: ModuleBuilder) -> ModuleBuilder {
2815///     module
2816///         .function(wrap_function!(take_object))
2817/// }
2818/// # fn main() {}
2819/// ```
2820///
2821/// ## Enums
2822///
2823/// When used on an enum, the `FromZval` implementation will treat the enum as a
2824/// tagged union with a mixed datatype. This allows you to accept multiple types
2825/// in a parameter, for example, a string and an integer.
2826///
2827/// The enum variants must not have named fields, and each variant must have
2828/// exactly one field (the type to extract from the zval). Optionally, the enum
2829/// may have one default variant with no data contained, which will be used when
2830/// the rest of the variants could not be extracted from the zval.
2831///
2832/// The ordering of the variants in the enum is important, as the `FromZval`
2833/// implementation will attempt to parse the zval data in order. For example, if
2834/// you put a `String` variant before an integer variant, the integer would be
2835/// converted to a string and passed as the string variant. Because an `f64` or
2836/// `f32` variant also accepts an integer, the integer variants must come before
2837/// it.
2838///
2839/// ### Examples
2840///
2841/// Basic example showing the importance of variant ordering and default field:
2842///
2843/// ```rust,no_run,ignore
2844/// # #![cfg_attr(windows, feature(abi_vectorcall))]
2845/// # extern crate ext_php_rs;
2846/// use ext_php_rs::prelude::*;
2847///
2848/// #[derive(Debug, ZvalConvert)]
2849/// pub enum UnionExample<'a> {
2850///     Long(u64), // Long
2851///     ProperStr(&'a str), // Actual string - not a converted value
2852///     ParsedStr(String), // Potentially parsed string, i.e. a double
2853///     None // Zval did not contain anything that could be parsed above
2854/// }
2855///
2856/// #[php_function]
2857/// pub fn test_union(val: UnionExample) {
2858///     dbg!(val);
2859/// }
2860///
2861/// #[php_function]
2862/// pub fn give_union() -> UnionExample<'static> {
2863///     UnionExample::Long(5)
2864/// }
2865///
2866/// #[php_module]
2867/// pub fn get_module(module: ModuleBuilder) -> ModuleBuilder {
2868///     module
2869///         .function(wrap_function!(test_union))
2870///         .function(wrap_function!(give_union))
2871/// }
2872/// # fn main() {}
2873/// ```
2874///
2875/// Use in PHP:
2876///
2877/// ```php
2878/// test_union(5); // UnionExample::Long(5)
2879/// test_union("Hello, world!"); // UnionExample::ProperStr("Hello, world!")
2880/// test_union(5.66666); // UnionExample::ParsedStr("5.6666")
2881/// test_union(null); // UnionExample::None
2882/// var_dump(give_union()); // int(5)
2883/// ```
2884// END DOCS FROM zval_convert.md
2885#[proc_macro_derive(ZvalConvert, attributes(php))]
2886pub fn zval_convert_derive(input: TokenStream) -> TokenStream {
2887    zval_convert_derive_internal(input.into()).into()
2888}
2889
2890fn zval_convert_derive_internal(input: TokenStream2) -> TokenStream2 {
2891    let input = parse_macro_input2!(input as DeriveInput);
2892
2893    zval::parser(input).unwrap_or_else(|e| e.to_compile_error())
2894}
2895
2896/// Defines an `extern` function with the Zend fastcall convention based on
2897/// operating system.
2898///
2899/// On Windows, Zend fastcall functions use the vector calling convention, while
2900/// on all other operating systems no fastcall convention is used (just the
2901/// regular C calling convention).
2902///
2903/// This macro wraps a function and applies the correct calling convention.
2904///
2905/// ## Examples
2906///
2907/// ```rust,ignore
2908/// # #![cfg_attr(windows, feature(abi_vectorcall))]
2909/// use ext_php_rs::zend_fastcall;
2910///
2911/// zend_fastcall! {
2912///     pub extern fn test_hello_world(a: i32, b: i32) -> i32 {
2913///         a + b
2914///     }
2915/// }
2916/// ```
2917///
2918/// On Windows, this function will have the signature `pub extern "vectorcall"
2919/// fn(i32, i32) -> i32`, while on macOS/Linux the function will have the
2920/// signature `pub extern "C" fn(i32, i32) -> i32`.
2921///
2922/// ## Support
2923///
2924/// The `vectorcall` ABI is currently only supported on Windows with nightly
2925/// Rust and the `abi_vectorcall` feature enabled.
2926#[proc_macro]
2927pub fn zend_fastcall(input: TokenStream) -> TokenStream {
2928    zend_fastcall_internal(input.into()).into()
2929}
2930
2931fn zend_fastcall_internal(input: TokenStream2) -> TokenStream2 {
2932    let input = parse_macro_input2!(input as ItemFn);
2933
2934    fastcall::parser(input)
2935}
2936
2937/// Wraps a function to be used in the [`Module::function`] method.
2938#[proc_macro]
2939pub fn wrap_function(input: TokenStream) -> TokenStream {
2940    wrap_function_internal(input.into()).into()
2941}
2942
2943fn wrap_function_internal(input: TokenStream2) -> TokenStream2 {
2944    let input = parse_macro_input2!(input as syn::Path);
2945
2946    match function::wrap(&input) {
2947        Ok(parsed) => parsed,
2948        Err(e) => e.to_compile_error(),
2949    }
2950}
2951
2952/// Wraps a constant to be used in the [`ModuleBuilder::constant`] method.
2953#[proc_macro]
2954pub fn wrap_constant(input: TokenStream) -> TokenStream {
2955    wrap_constant_internal(input.into()).into()
2956}
2957
2958fn wrap_constant_internal(input: TokenStream2) -> TokenStream2 {
2959    let input = parse_macro_input2!(input as syn::Path);
2960
2961    match constant::wrap(&input) {
2962        Ok(parsed) => parsed,
2963        Err(e) => e.to_compile_error(),
2964    }
2965}
2966
2967const PHP_ATTR_HINT: &str = "Use `#[php(<args>)]` on the item instead.";
2968const NO_ARGS_HINT: &str = "It takes no arguments.";
2969
2970fn reject_args(args: &TokenStream2, macro_name: &str, hint: &str) -> Result<(), syn::Error> {
2971    if args.is_empty() {
2972        return Ok(());
2973    }
2974    Err(err!(args => "`#[{macro_name}(<args>)]` args are not supported. {hint}"))
2975}
2976
2977macro_rules! parse_macro_input2 {
2978    ($tokenstream:ident as $ty:ty) => {
2979        match syn::parse2::<$ty>($tokenstream) {
2980            Ok(data) => data,
2981            Err(err) => {
2982                return proc_macro2::TokenStream::from(err.to_compile_error());
2983            }
2984        }
2985    };
2986    ($tokenstream:ident) => {
2987        $crate::parse_macro_input!($tokenstream as _)
2988    };
2989}
2990
2991pub(crate) use parse_macro_input2;
2992
2993macro_rules! err {
2994    ($span:expr => $($msg:tt)*) => {
2995        ::syn::Error::new(::syn::spanned::Spanned::span(&$span), format!($($msg)*))
2996    };
2997    ($($msg:tt)*) => {
2998        ::syn::Error::new(::proc_macro2::Span::call_site(), format!($($msg)*))
2999    };
3000}
3001
3002/// Bails out of a function with a syn error.
3003macro_rules! bail {
3004    ($span:expr => $($msg:tt)*) => {
3005        return Err($crate::err!($span => $($msg)*))
3006    };
3007    ($($msg:tt)*) => {
3008        return Err($crate::err!($($msg)*))
3009    };
3010}
3011
3012pub(crate) use bail;
3013pub(crate) use err;
3014
3015pub(crate) mod prelude {
3016    pub(crate) trait OptionTokens {
3017        fn option_tokens(&self) -> proc_macro2::TokenStream;
3018    }
3019
3020    impl<T: quote::ToTokens> OptionTokens for Option<T> {
3021        fn option_tokens(&self) -> proc_macro2::TokenStream {
3022            if let Some(token) = self {
3023                quote::quote! { ::std::option::Option::Some(#token) }
3024            } else {
3025                quote::quote! { ::std::option::Option::None }
3026            }
3027        }
3028    }
3029
3030    pub(crate) use crate::{bail, err};
3031    pub(crate) type Result<T> = std::result::Result<T, syn::Error>;
3032}
3033
3034#[cfg(test)]
3035mod tests {
3036    use super::*;
3037    use std::path::PathBuf;
3038
3039    type AttributeFn =
3040        fn(proc_macro2::TokenStream, proc_macro2::TokenStream) -> proc_macro2::TokenStream;
3041    type FunctionLikeFn = fn(proc_macro2::TokenStream) -> proc_macro2::TokenStream;
3042
3043    #[test]
3044    pub fn test_expand() {
3045        for entry in glob::glob("tests/expand/*.rs").expect("Failed to read expand tests glob") {
3046            let entry = entry.expect("Failed to read expand test file");
3047            runtime_expand_attr(&entry);
3048            runtime_expand_func(&entry);
3049            runtime_expand_derive(&entry);
3050        }
3051    }
3052
3053    fn runtime_expand_attr(path: &PathBuf) {
3054        let file = std::fs::File::open(path).expect("Failed to open expand test file");
3055        runtime_macros::emulate_attributelike_macro_expansion(
3056            file,
3057            &[
3058                ("php_class", php_class_internal as AttributeFn),
3059                ("php_const", php_const_internal as AttributeFn),
3060                ("php_enum", php_enum_internal as AttributeFn),
3061                ("php_interface", php_interface_internal as AttributeFn),
3062                ("php_extern", php_extern_internal as AttributeFn),
3063                ("php_function", php_function_internal as AttributeFn),
3064                ("php_impl", php_impl_internal as AttributeFn),
3065                (
3066                    "php_impl_interface",
3067                    php_impl_interface_internal as AttributeFn,
3068                ),
3069                ("php_module", php_module_internal as AttributeFn),
3070            ],
3071        )
3072        .expect("Failed to expand attribute macros in test file");
3073    }
3074
3075    fn runtime_expand_func(path: &PathBuf) {
3076        let file = std::fs::File::open(path).expect("Failed to open expand test file");
3077        runtime_macros::emulate_functionlike_macro_expansion(
3078            file,
3079            &[
3080                ("zend_fastcall", zend_fastcall_internal as FunctionLikeFn),
3081                ("wrap_function", wrap_function_internal as FunctionLikeFn),
3082                ("wrap_constant", wrap_constant_internal as FunctionLikeFn),
3083            ],
3084        )
3085        .expect("Failed to expand function-like macros in test file");
3086    }
3087
3088    fn runtime_expand_derive(path: &PathBuf) {
3089        let file = std::fs::File::open(path).expect("Failed to open expand test file");
3090        runtime_macros::emulate_derive_macro_expansion(
3091            file,
3092            &[("ZvalConvert", zval_convert_derive_internal)],
3093        )
3094        .expect("Failed to expand derive macros in test file");
3095    }
3096}