ext-php-rs 0.17.0

Bindings for the Zend API to build PHP extensions natively in Rust.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
use std::{
    ffi::CString,
    mem::{ManuallyDrop, MaybeUninit},
    ptr,
    rc::Rc,
};

use crate::{
    args::ArgInfoTables,
    builders::{FunctionBuilder, function::free_registered_entries},
    class::{ClassEntryInfo, ConstructorMeta, ConstructorResult, RegisteredClass},
    convert::{IntoZval, IntoZvalDyn},
    describe::DocComments,
    error::{Error, Result},
    exception::PhpException,
    ffi::{
        _ZEND_TYPE_NAME_BIT, _ZEND_TYPE_NULLABLE_BIT, IS_DOUBLE, IS_LONG, IS_UNDEF, MAY_BE_ANY,
        ZEND_INTERNAL_FUNCTION, zend_declare_class_constant_ex, zend_declare_property,
        zend_declare_typed_property, zend_do_implement_interface, zend_hash_str_find_ptr_lc,
        zend_register_internal_class_ex, zend_register_internal_interface,
    },
    flags::{ClassFlags, ConstantFlags, DataType, MethodFlags, PropertyFlags},
    types::{ZendClassObject, ZendObject, ZendStr, Zval},
    zend::function::{SensitiveParameters, mark_sensitive},
    zend::{ClassEntry, CompilerGlobals, ExecuteData, ExecutorGlobals, FunctionEntry, ZendType},
    zend_fastcall,
};

/// A constant entry: (name, `value_closure`, docs, `stub_value`, flags)
type ConstantEntry = (
    String,
    Box<dyn FnOnce() -> Result<Zval>>,
    DocComments,
    String,
    ConstantFlags,
);
type PropertyDefault = Option<Box<dyn FnOnce() -> Result<Zval>>>;

/// Metadata for a class property to be registered with PHP.
pub struct ClassProperty {
    /// Name of the property.
    pub name: String,
    /// Visibility and modifier flags.
    pub flags: PropertyFlags,
    /// Optional default value closure.
    pub default: PropertyDefault,
    /// Documentation comments.
    pub docs: DocComments,
    /// PHP type for stub generation.
    pub ty: Option<DataType>,
    /// Whether the property accepts null.
    pub nullable: bool,
    /// Whether the property is read-only (getter without setter).
    pub readonly: bool,
    /// PHP stub representation of the default value (e.g. `"null"`, `"42"`).
    pub default_stub: Option<String>,
}

/// Returns the first name that repeats an earlier one. The engine keys
/// method, function and class tables by ASCII-lowercased name, and constant and
/// property tables by the exact name.
pub(crate) fn first_duplicate<'a>(
    names: impl IntoIterator<Item = &'a str>,
    fold_ascii_case: bool,
) -> Option<&'a str> {
    let names: Vec<&str> = names.into_iter().collect();
    names.iter().enumerate().find_map(|(i, name)| {
        names[..i]
            .iter()
            .any(|earlier| {
                if fold_ascii_case {
                    earlier.eq_ignore_ascii_case(name)
                } else {
                    earlier == name
                }
            })
            .then_some(*name)
    })
}

/// Returns an error when the engine already holds a class, interface or enum
/// named `name`, ignoring ASCII case. `do_register_internal_class` would
/// silently replace it.
///
/// `EG(class_table)` is only set at request startup, so this reads
/// `CG(class_table)`, which holds every class registered so far.
pub(crate) fn ensure_class_name_free(name: &str) -> Result<()> {
    let class_table = CompilerGlobals::get().class_table;
    if class_table.is_null() {
        return Ok(());
    }
    // SAFETY: `class_table` is the engine's live class table and `name` is
    // valid for `name.len()` bytes; the lookup copies it before lowercasing.
    let found = unsafe { zend_hash_str_find_ptr_lc(class_table, name.as_ptr().cast(), name.len()) };
    if found.is_null() {
        Ok(())
    } else {
        Err(Error::DuplicateClass {
            class: name.to_owned(),
        })
    }
}

/// Builder for registering a class in PHP.
#[must_use]
pub struct ClassBuilder {
    pub(crate) name: String,
    ce: ClassEntry,
    pub(crate) extends: Option<ClassEntryInfo>,
    pub(crate) interfaces: Vec<ClassEntryInfo>,
    pub(crate) methods: Vec<(FunctionBuilder<'static>, MethodFlags)>,
    object_override: Option<unsafe extern "C" fn(class_type: *mut ClassEntry) -> *mut ZendObject>,
    pub(crate) properties: Vec<ClassProperty>,
    /// Properties declared with their type, see
    /// [`ClassBuilder::typed_property`].
    pub(crate) typed_properties: Vec<ClassProperty>,
    /// The throwing constructor of a `#[php(no_constructor)]` class, added by
    /// [`ClassBuilder::register`] when the parent is a Rust class declaring a
    /// constructor: inherited, it would run on an object of another type.
    unless_parent_constructs: Option<FunctionBuilder<'static>>,
    pub(crate) constants: Vec<ConstantEntry>,
    register: Option<fn(&'static mut ClassEntry, ArgInfoTables)>,
    pub(crate) docs: DocComments,
}

impl ClassBuilder {
    /// Creates a new class builder, used to build classes
    /// to be exported to PHP.
    ///
    /// # Parameters
    ///
    /// * `name` - The name of the class.
    pub fn new<T: Into<String>>(name: T) -> Self {
        Self {
            name: name.into(),
            // SAFETY: A zeroed class entry is in an initialized state, as it is a raw C type
            // whose fields do not have a drop implementation.
            ce: unsafe { MaybeUninit::zeroed().assume_init() },
            extends: None,
            interfaces: vec![],
            methods: vec![],
            object_override: None,
            properties: vec![],
            typed_properties: vec![],
            unless_parent_constructs: None,
            constants: vec![],
            register: None,
            docs: &[],
        }
    }

    /// Return PHP class flags
    #[must_use]
    pub fn get_flags(&self) -> u32 {
        self.ce.ce_flags
    }

    /// Sets the class builder to extend another class.
    ///
    /// # Parameters
    ///
    /// * `parent` - The parent class to extend.
    pub fn extends(mut self, parent: ClassEntryInfo) -> Self {
        self.extends = Some(parent);
        self
    }

    /// Implements an interface on the class.
    ///
    /// # Parameters
    ///
    /// * `interface` - Interface to implement on the class.
    ///
    /// # Panics
    ///
    /// Panics when the given class entry `interface` is not an interface.
    pub fn implements(mut self, interface: ClassEntryInfo) -> Self {
        self.interfaces.push(interface);
        self
    }

    /// Adds a method to the class.
    ///
    /// # Parameters
    ///
    /// * `func` - The function builder to add to the class.
    /// * `flags` - Flags relating to the function. See [`MethodFlags`].
    pub fn method(mut self, func: FunctionBuilder<'static>, flags: MethodFlags) -> Self {
        self.methods.push((func, flags));
        self
    }

    /// Adds a property to the class.
    ///
    /// # Parameters
    ///
    /// * `prop` - The property metadata to add to the class.
    pub fn property(mut self, prop: ClassProperty) -> Self {
        self.properties.push(prop);
        self
    }

    /// Adds a typed property to the class, declared as PHP declares
    /// `protected int $count = 0;`: the engine enforces `prop.ty` (and
    /// `prop.nullable`) on every write, and reflection reports the type.
    ///
    /// `prop.ty` is a scalar type, `mixed`, or a class (`DataType::Object`
    /// with a class name). Without a default the property starts
    /// uninitialized, as an untyped default never does: reading it before a
    /// write throws PHP's `Error`, and `unset()` returns it to that state. A
    /// default must be a value of the type.
    ///
    /// `prop.readonly` must be `false`, and the class must not be a readonly
    /// class (PHP 8.2): the engine would declare the property writable, where
    /// PHP declares it `readonly`.
    ///
    /// [`ClassBuilder::property`] declares a property without a type; its
    /// `ty` only shapes the generated stubs.
    ///
    /// # Errors
    ///
    /// [`ClassBuilder::register`] fails with [`Error::InvalidPropertyType`]
    /// when `prop.ty` is `None` or names a type a property cannot have
    /// (`iterable`, `resource`, `callable`, ...), when the default is not a
    /// value of the type, or when the property would have to be readonly.
    pub fn typed_property(mut self, prop: ClassProperty) -> Self {
        self.typed_properties.push(prop);
        self
    }

    /// Adds a constant to the class. The type of the constant is defined by the
    /// type of the given default.
    ///
    /// Returns a result containing the class builder if the constant was
    /// successfully added.
    ///
    /// # Parameters
    ///
    /// * `name` - The name of the constant to add to the class.
    /// * `value` - The value of the constant.
    /// * `docs` - Documentation comments for the constant.
    /// * `flags` - Visibility of the constant.
    ///
    /// # Errors
    ///
    /// Returns an error if `value` cannot be converted into a [`Zval`].
    pub fn constant<T: Into<String>>(
        mut self,
        name: T,
        value: impl IntoZval + 'static,
        docs: DocComments,
        flags: ConstantFlags,
    ) -> Result<Self> {
        let zval = value.into_zval(true)?;
        let stub = crate::convert::zval_to_stub(&zval);
        self.constants
            .push((name.into(), Box::new(|| Ok(zval)), docs, stub, flags));
        Ok(self)
    }

    /// Adds a constant to the class from a `dyn` object. The type of the
    /// constant is defined by the type of the value.
    ///
    /// Returns a result containing the class builder if the constant was
    /// successfully added.
    ///
    /// # Parameters
    ///
    /// * `name` - The name of the constant to add to the class.
    /// * `value` - The value of the constant.
    /// * `docs` - Documentation comments for the constant.
    /// * `flags` - Visibility of the constant.
    ///
    /// # Errors
    ///
    /// Returns an error if `value` cannot be converted into a [`Zval`].
    pub fn dyn_constant<T: Into<String>>(
        mut self,
        name: T,
        value: &'static dyn IntoZvalDyn,
        docs: DocComments,
        flags: ConstantFlags,
    ) -> Result<Self> {
        let stub = value.stub_value();
        let value = Rc::new(value);
        self.constants.push((
            name.into(),
            Box::new(move || value.as_zval(true)),
            docs,
            stub,
            flags,
        ));
        Ok(self)
    }

    /// Sets the flags for the class.
    ///
    /// # Parameters
    ///
    /// * `flags` - Flags relating to the class. See [`ClassFlags`].
    pub fn flags(mut self, flags: ClassFlags) -> Self {
        self.ce.ce_flags = flags.bits();
        self
    }

    /// Overrides the creation of the Zend object which will represent an
    /// instance of this class.
    ///
    /// # Parameters
    ///
    /// * `T` - The type which will override the Zend object. Must implement
    ///   [`RegisteredClass`] which can be derived using the
    ///   [`php_class`](crate::php_class) attribute macro.
    ///
    /// # Panics
    ///
    /// Panics if the class name associated with `T` is not the same as the
    /// class name specified when creating the builder.
    pub fn object_override<T: RegisteredClass>(mut self) -> Self {
        extern "C" fn create_object<T: RegisteredClass>(ce: *mut ClassEntry) -> *mut ZendObject {
            // Try to initialize with a default instance if available.
            // This is critical for exception classes that extend \Exception, because
            // PHP's zend_throw_exception_ex creates objects via create_object without
            // calling the constructor, then immediately accesses properties.
            // Without default initialization, accessing properties on uninitialized
            // objects would panic.
            if let Some(instance) = T::default_init() {
                // `ce` is `T`'s class or a PHP subclass of it: the object is one
                // of the class `new` names.
                let obj = ZendClassObject::<T>::new_in(instance, unsafe { ce.as_ref() }).into_raw();
                // SAFETY: `into_raw` yields a valid, exclusively owned object that
                // the engine takes over.
                return unsafe { (*obj).get_mut_zend_obj() };
            }

            // SAFETY: After calling this function, PHP will always call the constructor
            // defined below, which assumes that the object is uninitialized.
            let obj = ZendClassObject::<T>::new_uninit(unsafe { ce.as_ref() }).into_raw();
            // SAFETY: same ownership transfer as above.
            unsafe { (*obj).get_mut_zend_obj() }
        }

        zend_fastcall! {
            extern fn constructor<T: RegisteredClass>(ex: &mut ExecuteData, _: &mut Zval) {
                crate::zend::run_handler(std::panic::AssertUnwindSafe(|| {
                    let Some(ConstructorMeta { constructor, .. }) = T::constructor() else {
                        PhpException::from_message("You cannot instantiate this class from PHP.".into())
                            .throw();
                        return;
                    };

                    let this = match constructor(ex) {
                        ConstructorResult::Ok(this) => this,
                        ConstructorResult::Exception(e) => {
                            e.throw();
                            return;
                        }
                        ConstructorResult::ArgError => return,
                    };

                    let Some(this_obj) = ex.get_object::<T>() else {
                        PhpException::from_message("Failed to retrieve reference to `this` object.".into())
                            .throw();
                        return;
                    };

                    if let Err(err) = this_obj.initialize(this) {
                        PhpException::from(err).throw();
                    }
                }));
            }
        }

        debug_assert_eq!(
            self.name.as_str(),
            T::CLASS_NAME,
            "Class name in builder does not match class name in `impl RegisteredClass`."
        );
        self.object_override = Some(create_object::<T>);
        let is_interface = T::FLAGS.contains(ClassFlags::Interface);

        // For interfaces: only add __construct if explicitly declared.
        // For classes: a declared constructor; else, with `NO_CONSTRUCTOR`, none
        // (objects are created initialized from `Default`, see `create_object`),
        // unless a Rust parent declares one (see `register`); else one that
        // throws, since the object could not be initialized.
        if let Some(ConstructorMeta {
            build_fn, flags, ..
        }) = T::constructor()
        {
            let func = if is_interface {
                FunctionBuilder::new_abstract("__construct")
            } else {
                FunctionBuilder::new("__construct", constructor::<T>)
            };
            let visibility = flags.unwrap_or(MethodFlags::Public);
            self.method(build_fn(func), visibility)
        } else if is_interface {
            self
        } else if T::NO_CONSTRUCTOR {
            self.unless_parent_constructs =
                Some(FunctionBuilder::new("__construct", constructor::<T>));
            self
        } else {
            // Add default constructor for classes
            let func = FunctionBuilder::new("__construct", constructor::<T>);
            self.method(func, MethodFlags::Public)
        }
    }

    /// Function to register the class with PHP, called once the class is built.
    ///
    /// It receives the registered class entry and the argument info tables of
    /// the class's methods. `zend_register_functions` borrows those tables for
    /// the life of the process, so the function must park them somewhere that
    /// lives that long — normally the class's own
    /// [`ClassMetadata`](crate::class::ClassMetadata) static:
    ///
    /// ```rust,ignore
    /// .registration(|ce, arg_info| {
    ///     META.set_ce(ce);
    ///     META.set_arg_info(arg_info);
    /// })
    /// ```
    ///
    /// # Parameters
    ///
    /// * `register` - The function to call to register the class.
    pub fn registration(mut self, register: fn(&'static mut ClassEntry, ArgInfoTables)) -> Self {
        self.register = Some(register);
        self
    }

    /// Sets the documentation for the class.
    ///
    /// # Parameters
    ///
    /// * `docs` - The documentation comments for the class.
    pub fn docs(mut self, docs: DocComments) -> Self {
        self.docs = docs;
        self
    }

    /// Checks that no two properties, methods or constants of the class share
    /// a PHP name. Methods are compared ignoring ASCII case, like the engine.
    fn validate(&self) -> Result<()> {
        if let Some(name) = first_duplicate(
            self.properties
                .iter()
                .chain(&self.typed_properties)
                .map(|p| p.name.as_str()),
            false,
        ) {
            return Err(Error::DuplicateProperty {
                property: format!("{}::${name}", self.name),
            });
        }
        if let Some(name) = first_duplicate(self.methods.iter().map(|(m, _)| m.name.as_str()), true)
        {
            return Err(Error::DuplicateMethod {
                method: format!("{}::{name}", self.name),
            });
        }
        if let Some(name) = first_duplicate(self.constants.iter().map(|c| c.0.as_str()), false) {
            return Err(Error::DuplicateConstant {
                constant: format!("{}::{name}", self.name),
            });
        }
        #[cfg(php82)]
        let readonly_class = self.ce.ce_flags & ClassFlags::ReadonlyClass.bits() != 0;
        #[cfg(not(php82))]
        let readonly_class = false;
        for prop in &self.typed_properties {
            let typed = prop
                .ty
                .and_then(|ty| property_type_mask(ty, prop.nullable))
                .is_some();
            if !typed || prop.readonly || readonly_class {
                return Err(Error::InvalidPropertyType {
                    property: format!("{}::${}", self.name, prop.name),
                });
            }
        }
        Ok(())
    }

    /// A `#[php(no_constructor)]` class under a Rust class that declares a
    /// constructor would inherit it, and the parent's constructor would run on
    /// an object of another Rust type: the class keeps the one that throws.
    fn keep_throwing_constructor(&mut self) {
        if let Some(constructor) = self.unless_parent_constructs.take()
            && self
                .extends
                .as_ref()
                .is_some_and(|(parent, _)| constructs_in_this_module(parent()))
        {
            self.methods.push((constructor, MethodFlags::Public));
        }
    }

    /// Builds and registers the class.
    ///
    /// # Errors
    ///
    /// * [`Error::DuplicateProperty`], [`Error::DuplicateMethod`] or
    ///   [`Error::DuplicateConstant`] - If two members share a PHP name.
    /// * [`Error::DuplicateClass`] - If a class with this name, ignoring ASCII
    ///   case, is already registered.
    /// * [`Error::InvalidPropertyType`] - If a typed property has no type a
    ///   property can have, or a default that is not a value of its type.
    /// * [`Error::InvalidPointer`] - If the class could not be registered.
    /// * [`Error::InvalidCString`] - If the class name is not a valid C string.
    /// * [`Error::IntegerOverflow`] - If the property flags are not valid.
    /// * If a method or property could not be built.
    ///
    /// # Panics
    ///
    /// * If called outside a module startup (MINIT) function.
    /// * If no registration function was provided.
    pub fn register(mut self) -> Result<()> {
        assert!(
            !ExecutorGlobals::get().current_module.is_null(),
            "Classes can only be registered from a module startup (MINIT) function: \
             `do_register_internal_class` dereferences `EG(current_module)`."
        );
        self.validate()?;
        ensure_class_name_free(&self.name)?;

        self.ce.name = ZendStr::new_interned(&self.name, true).into_raw();

        self.keep_throwing_constructor();

        let mut arg_info = Vec::with_capacity(self.methods.len());
        let mut methods = Vec::with_capacity(self.methods.len() + 1);
        let mut sensitive = SensitiveParameters::new();
        for (method, flags) in self.methods {
            sensitive.extend(method.sensitive());
            let (mut entry, args) = method.build()?;
            entry.add_flags(flags);
            methods.push(entry);
            arg_info.push(args);
        }

        // The engine keeps `zend_internal_function.arg_info` pointing into these
        // for the life of the process, so `register` parks them. Holding them in
        // a `ManuallyDrop` keeps them alive across registration, which reads
        // them, without a second owner. Every fallible step below runs after the
        // class entry is in `CG(class_table)`, so an error must leak the tables
        // rather than dangle the functions the engine already holds.
        let arg_info = ManuallyDrop::new(arg_info.into_boxed_slice());

        methods.push(FunctionEntry::end());
        let entries = Box::into_raw(methods.into_boxed_slice());
        self.ce.info.internal.builtin_functions = entries.cast::<FunctionEntry>().cast_const();

        let class = if self.ce.flags().contains(ClassFlags::Interface) {
            unsafe { zend_register_internal_interface(&raw mut self.ce) }
        } else {
            // Resolved here and not before the branch: the getter is usually
            // `T::get_metadata().ce()`, which panics when the parent has not been
            // registered, and `zend_register_internal_interface` takes no parent.
            let parent = match self.extends {
                Some((ptr, _)) => ptr::from_ref(ptr()).cast_mut(),
                None => std::ptr::null_mut(),
            };
            unsafe { zend_register_internal_class_ex(&raw mut self.ce, parent) }
        };

        // SAFETY: `do_register_internal_class` has interned every `fname` and read
        // `builtin_functions` for the last time, so the table is dead.
        unsafe { free_registered_entries(entries) };

        let class = unsafe { class.as_mut() }.ok_or(Error::InvalidPointer)?;
        class.info.internal.builtin_functions = ptr::null();
        mark_sensitive(&raw const class.function_table, &sensitive);

        // disable serialization if the class has an associated object
        if self.object_override.is_some() {
            cfg_if::cfg_if! {
                if #[cfg(php81)] {
                    class.ce_flags |= ClassFlags::NotSerializable.bits();
                } else {
                    class.serialize = Some(crate::ffi::zend_class_serialize_deny);
                    class.unserialize = Some(crate::ffi::zend_class_unserialize_deny);
                }
            }
        }

        for (iface, _) in self.interfaces {
            let interface = iface();
            assert!(
                interface.is_interface(),
                "Given class entry was not an interface."
            );

            unsafe { zend_do_implement_interface(class, ptr::from_ref(interface).cast_mut()) };
        }

        for prop in self.properties {
            let mut default_zval = match prop.default {
                Some(f) => f()?,
                None => Zval::new(),
            };
            unsafe {
                zend_declare_property(
                    class,
                    CString::new(prop.name.as_str())?.as_ptr(),
                    prop.name.len() as _,
                    &raw mut default_zval,
                    prop.flags.bits().try_into()?,
                );
            }
        }

        for prop in self.typed_properties {
            declare_typed_property(class, &self.name, prop)?;
        }

        for (name, value, _, _, flags) in self.constants {
            // The constants table keeps the interned key; releasing an interned
            // string is a no-op, so dropping the `ZBox` afterwards is sound.
            let name = ZendStr::new_interned(&name, true);
            // `zend_declare_class_constant_ex` takes the payload with
            // `ZVAL_COPY_VALUE` and no incref and, unlike
            // `zend_declare_typed_property`, does not reject refcounted values, so
            // the constants table owns it and the `Zval` must not run its destructor.
            let mut value = ManuallyDrop::new(value()?);
            unsafe {
                zend_declare_class_constant_ex(
                    class,
                    name.as_ptr().cast_mut(),
                    &raw mut *value,
                    flags.bits().try_into()?,
                    ptr::null_mut(),
                );
            };
        }

        if let Some(object_override) = self.object_override {
            class.__bindgen_anon_2.create_object = Some(object_override);
        }

        if let Some(register) = self.register {
            register(class, ManuallyDrop::into_inner(arg_info));
        } else {
            panic!("Class {} was not registered.", self.name);
        }

        Ok(())
    }
}

/// The type mask of a property declared with `ty`, or `None` when a property
/// cannot have that type.
///
/// An allowlist: the types of [`ZendType::scalar_type_mask`], `mixed`, and a
/// class (`DataType::Object` with a name, whose mask holds
/// `_ZEND_TYPE_NAME_BIT` and needs the name as the type's pointer).
/// `nullable` adds `null`, except to `mixed`, which holds it already.
/// `iterable` is refused: a property cannot use the `_ZEND_TYPE_ITERABLE_BIT`
/// arginfo carries, which only `zend_register_functions` expands into
/// `Traversable|array`.
pub(crate) fn property_type_mask(ty: DataType, nullable: bool) -> Option<u32> {
    let nullable = if nullable { _ZEND_TYPE_NULLABLE_BIT } else { 0 };
    let mask = match ty {
        DataType::Mixed => return Some(MAY_BE_ANY),
        DataType::Object(_) if ty.class_name().is_some() => _ZEND_TYPE_NAME_BIT,
        _ => ZendType::scalar_type_mask(ty)?,
    };
    Some(mask | nullable)
}

/// How a default value of type code `code` fits a property whose type is
/// `mask`, as `zend_is_valid_default_value` decides.
#[derive(Debug, PartialEq, Eq)]
pub(crate) enum DefaultFit {
    /// A value of the type, or no default (`IS_UNDEF`).
    Fits,
    /// An `int` where the type holds `float`: the default becomes a float.
    ToDouble,
    /// Refused.
    Refused,
}

pub(crate) fn default_fit(mask: u32, code: u32) -> DefaultFit {
    if code == IS_UNDEF || (code < 32 && mask & (1 << code) != 0) {
        DefaultFit::Fits
    } else if mask & (1 << IS_DOUBLE) != 0 && code == IS_LONG {
        DefaultFit::ToDouble
    } else {
        DefaultFit::Refused
    }
}

/// Declares `prop` on `class` (named `class_name`) with its type, see
/// [`ClassBuilder::typed_property`].
fn declare_typed_property(
    class: &mut ClassEntry,
    class_name: &str,
    prop: ClassProperty,
) -> Result<()> {
    let invalid = || Error::InvalidPropertyType {
        property: format!("{class_name}::${}", prop.name),
    };
    let ty = prop.ty.ok_or_else(invalid)?;
    let mask = property_type_mask(ty, prop.nullable).ok_or_else(invalid)?;
    // A property type names its class with an interned `zend_string`, where
    // argument info takes a C string.
    let type_ptr = match ty.class_name() {
        Some(name) => ManuallyDrop::new(ZendStr::new_interned(name, true))
            .as_ptr()
            .cast_mut()
            .cast(),
        None => ptr::null_mut(),
    };
    let mut default = if let Some(f) = prop.default {
        f()?
    } else {
        // `IS_UNDEF`: the property starts uninitialized.
        let mut undef = Zval::new();
        undef.u1.type_info = IS_UNDEF;
        undef
    };
    // SAFETY: the low byte of `type_info` is the zval's type code, whichever
    // member of the union was written.
    let code = unsafe { default.u1.type_info } & 0xff;
    match default_fit(mask, code) {
        DefaultFit::Fits => {}
        DefaultFit::ToDouble => {
            let long = default.long().ok_or_else(invalid)?;
            #[expect(
                clippy::cast_precision_loss,
                reason = "PHP converts an int default to float the same way"
            )]
            default.set_double(long as f64);
        }
        DefaultFit::Refused => return Err(invalid()),
    }
    let name = ZendStr::new_interned(&prop.name, true);
    // The engine takes the default with `ZVAL_COPY_VALUE`, as for
    // `zend_declare_property` above, and keeps the interned name and type.
    unsafe {
        zend_declare_typed_property(
            class,
            name.as_ptr().cast_mut(),
            &raw mut default,
            prop.flags.bits().try_into()?,
            ptr::null_mut(),
            ZendType {
                ptr: type_ptr,
                type_mask: mask,
            },
        );
    }
    std::mem::forget(default);
    Ok(())
}

/// Whether `class` declares a constructor registered by the module being
/// started: a Rust class of this extension, whose constructor initializes an
/// object of its own Rust type.
fn constructs_in_this_module(class: &ClassEntry) -> bool {
    // SAFETY: a registered class's constructor is a live function of the
    // engine's function table, and `type_` tells which member of the union
    // holds it.
    unsafe { class.constructor.as_ref() }.is_some_and(|constructor| unsafe {
        u32::from(constructor.type_) == ZEND_INTERNAL_FUNCTION
            && constructor.internal_function.module == ExecutorGlobals::get().current_module
    })
}

#[cfg(test)]
mod tests {
    use crate::ffi::{IS_ARRAY, IS_FALSE, IS_NULL, IS_OBJECT, IS_STRING, IS_TRUE, MAY_BE_BOOL};
    use crate::test::test_function;

    use super::*;

    fn typed(name: &str, ty: DataType, nullable: bool) -> ClassProperty {
        ClassProperty {
            name: name.into(),
            flags: PropertyFlags::Public,
            default: None,
            docs: &[],
            ty: Some(ty),
            nullable,
            readonly: false,
            default_stub: None,
        }
    }

    #[test]
    fn property_type_mask_covers_every_data_type() {
        let null = _ZEND_TYPE_NULLABLE_BIT;
        let cases = [
            (DataType::Undef, None),
            (DataType::Null, None),
            (DataType::False, None),
            (DataType::True, None),
            (DataType::Long, Some(1 << IS_LONG)),
            (DataType::Double, Some(1 << IS_DOUBLE)),
            (DataType::String, Some(1 << IS_STRING)),
            (DataType::Array, Some(1 << IS_ARRAY)),
            (DataType::Iterable, None),
            (DataType::Object("".into()), Some(1 << IS_OBJECT)),
            (DataType::Object("Foo".into()), Some(_ZEND_TYPE_NAME_BIT)),
            (DataType::Resource, None),
            (DataType::Reference, None),
            (DataType::Callable, None),
            (DataType::ConstantExpression, None),
            (DataType::Indirect, None),
            (DataType::Void, None),
            (DataType::Mixed, Some(MAY_BE_ANY)),
            (DataType::Bool, Some(MAY_BE_BOOL)),
            (DataType::Ptr, None),
        ];
        for (ty, mask) in cases {
            assert_eq!(property_type_mask(ty, false), mask, "{ty:?}");
            let nullable = match ty {
                DataType::Mixed => mask,
                _ => mask.map(|m| m | null),
            };
            assert_eq!(property_type_mask(ty, true), nullable, "?{ty:?}");
        }
    }

    #[test]
    fn validate_refuses_a_typed_property_without_a_property_type() {
        // `iterable` refused arrays and segfaulted on the TypeError, `resource`
        // and a constant expression segfaulted `ReflectionType::__toString`,
        // and `Indirect` became `callable`.
        for ty in [
            DataType::Iterable,
            DataType::Resource,
            DataType::ConstantExpression,
            DataType::Indirect,
            DataType::Callable,
            DataType::Void,
        ] {
            let class = ClassBuilder::new("Foo").typed_property(typed("a", ty, false));
            assert!(
                matches!(
                    class.validate(),
                    Err(Error::InvalidPropertyType { property }) if property == "Foo::$a"
                ),
                "{ty:?}"
            );
        }
        let mut missing = typed("a", DataType::Long, false);
        missing.ty = None;
        assert!(
            ClassBuilder::new("Foo")
                .typed_property(missing)
                .validate()
                .is_err()
        );
    }

    #[test]
    fn validate_accepts_property_types() {
        let class = ClassBuilder::new("Foo")
            .typed_property(typed("a", DataType::Long, false))
            .typed_property(typed("b", DataType::String, true))
            .typed_property(typed("c", DataType::Object("ArrayObject".into()), false))
            .typed_property(typed("d", DataType::Mixed, true))
            // An untyped property's `ty` only shapes stubs.
            .property(typed("e", DataType::Iterable, false));
        assert!(class.validate().is_ok());
    }

    #[test]
    fn default_fit_as_zend_is_valid_default_value() {
        let mask = |ty, nullable| property_type_mask(ty, nullable).expect("a property type");
        let float = mask(DataType::Double, false);
        assert_eq!(default_fit(float, IS_LONG), DefaultFit::ToDouble);
        assert_eq!(default_fit(float, IS_DOUBLE), DefaultFit::Fits);
        let string = mask(DataType::String, false);
        assert_eq!(default_fit(string, IS_LONG), DefaultFit::Refused);
        let int = mask(DataType::Long, false);
        assert_eq!(default_fit(int, IS_DOUBLE), DefaultFit::Refused);
        assert_eq!(default_fit(int, IS_NULL), DefaultFit::Refused);
        assert_eq!(default_fit(int, IS_UNDEF), DefaultFit::Fits);
        let nullable_int = mask(DataType::Long, true);
        assert_eq!(default_fit(nullable_int, IS_NULL), DefaultFit::Fits);
        let class = mask(DataType::Object("Foo".into()), false);
        assert_eq!(default_fit(class, IS_LONG), DefaultFit::Refused);
        assert_eq!(default_fit(class, IS_OBJECT), DefaultFit::Refused);
        let boolean = mask(DataType::Bool, false);
        assert_eq!(default_fit(boolean, IS_TRUE), DefaultFit::Fits);
        assert_eq!(default_fit(boolean, IS_FALSE), DefaultFit::Fits);
    }

    #[test]
    fn validate_refuses_readonly_typed_properties() {
        let mut readonly = typed("a", DataType::Long, false);
        readonly.readonly = true;
        assert!(matches!(
            ClassBuilder::new("Foo").typed_property(readonly).validate(),
            Err(Error::InvalidPropertyType { property }) if property == "Foo::$a"
        ));
    }

    #[test]
    #[cfg(php82)]
    fn validate_refuses_typed_properties_on_a_readonly_class() {
        // The engine does not make a readonly class's typed properties
        // readonly, as PHP's compiler does.
        let class = ClassBuilder::new("Foo")
            .flags(ClassFlags::ReadonlyClass)
            .typed_property(typed("a", DataType::Long, false));
        assert!(matches!(
            class.validate(),
            Err(Error::InvalidPropertyType { property }) if property == "Foo::$a"
        ));
    }

    #[test]
    fn validate_refuses_a_typed_property_repeating_an_untyped_one() {
        let class = ClassBuilder::new("Foo")
            .property(typed("a", DataType::Long, false))
            .typed_property(typed("a", DataType::Long, false));
        assert!(matches!(
            class.validate(),
            Err(Error::DuplicateProperty { property }) if property == "Foo::$a"
        ));
    }

    #[test]
    #[allow(unpredictable_function_pointer_comparisons)]
    fn test_new() {
        let class = ClassBuilder::new("Foo");
        assert_eq!(class.name, "Foo");
        assert_eq!(class.extends, None);
        assert_eq!(class.interfaces, vec![]);
        assert_eq!(class.methods.len(), 0);
        assert_eq!(class.object_override, None);
        assert!(class.properties.is_empty());
        assert_eq!(class.constants.len(), 0);
        assert_eq!(class.register, None);
        assert_eq!(class.docs, &[] as DocComments);
    }

    #[test]
    fn test_extends() {
        let extends: ClassEntryInfo = (|| todo!(), "Bar");
        let class = ClassBuilder::new("Foo").extends(extends);
        assert_eq!(class.extends, Some(extends));
    }

    #[test]
    fn test_implements() {
        let implements: ClassEntryInfo = (|| todo!(), "Bar");
        let class = ClassBuilder::new("Foo").implements(implements);
        assert_eq!(class.interfaces, vec![implements]);
    }

    #[test]
    fn test_method() {
        let method = FunctionBuilder::new("foo", test_function);
        let class = ClassBuilder::new("Foo").method(method, MethodFlags::Public);
        assert_eq!(class.methods.len(), 1);
    }

    #[test]
    fn test_property() {
        let class = ClassBuilder::new("Foo").property(ClassProperty {
            name: "bar".into(),
            flags: PropertyFlags::Public,
            default: None,
            docs: &["Doc 1"],
            ty: Some(DataType::String),
            nullable: false,
            readonly: false,
            default_stub: None,
        });
        assert_eq!(class.properties.len(), 1);
        assert_eq!(class.properties[0].name, "bar");
        assert_eq!(class.properties[0].flags, PropertyFlags::Public);
        assert!(class.properties[0].default.is_none());
        assert_eq!(class.properties[0].docs, &["Doc 1"] as DocComments);
        assert_eq!(class.properties[0].ty, Some(DataType::String));
    }

    fn named_property(name: &str) -> ClassProperty {
        ClassProperty {
            name: name.into(),
            flags: PropertyFlags::Public,
            default: None,
            docs: &[],
            ty: None,
            nullable: false,
            readonly: false,
            default_stub: None,
        }
    }

    fn with_constant(mut class: ClassBuilder, name: &str) -> ClassBuilder {
        class.constants.push((
            name.into(),
            Box::new(|| Err(Error::InvalidPointer)),
            &[],
            String::new(),
            ConstantFlags::Public,
        ));
        class
    }

    #[test]
    fn first_duplicate_folds_ascii_case_only_when_asked() {
        assert_eq!(first_duplicate(["a", "b", "a"], false), Some("a"));
        assert_eq!(first_duplicate(["a", "B", "b"], false), None);
        assert_eq!(first_duplicate(["a", "B", "b"], true), Some("b"));
        assert_eq!(first_duplicate(["ä", "Ä"], true), None);
        assert_eq!(first_duplicate([], true), None);
    }

    #[test]
    fn validate_rejects_a_repeated_property() {
        let mut class = ClassBuilder::new("Foo");
        class.properties = vec![named_property("a"), named_property("a")];
        assert!(matches!(
            class.validate(),
            Err(Error::DuplicateProperty { property }) if property == "Foo::$a"
        ));
    }

    #[test]
    fn validate_rejects_methods_that_differ_only_by_case() {
        let class = ClassBuilder::new("Foo")
            .method(
                FunctionBuilder::new("run", test_function),
                MethodFlags::Public,
            )
            .method(
                FunctionBuilder::new("RUN", test_function),
                MethodFlags::Static,
            );
        assert!(matches!(
            class.validate(),
            Err(Error::DuplicateMethod { method }) if method == "Foo::RUN"
        ));
    }

    #[test]
    fn validate_compares_constants_exactly() {
        let class = with_constant(with_constant(ClassBuilder::new("Foo"), "A"), "a");
        assert!(class.validate().is_ok());
        let class = with_constant(class, "A");
        assert!(matches!(
            class.validate(),
            Err(Error::DuplicateConstant { constant }) if constant == "Foo::A"
        ));
    }

    #[test]
    #[cfg(feature = "embed")]
    fn class_names_already_in_the_class_table_are_taken() {
        let ran = crate::embed::Embed::run(|| {
            assert!(matches!(
                ensure_class_name_free("STDCLASS"),
                Err(Error::DuplicateClass { class }) if class == "STDCLASS"
            ));
            assert!(ensure_class_name_free("ExtPhpRsNoSuchClass").is_ok());
            true
        });
        assert!(ran);
    }

    #[test]
    fn validate_accepts_distinct_members() {
        let mut class = ClassBuilder::new("Foo")
            .method(
                FunctionBuilder::new("run", test_function),
                MethodFlags::Public,
            )
            .method(
                FunctionBuilder::new("stop", test_function),
                MethodFlags::Public,
            );
        class.properties = vec![named_property("a"), named_property("b")];
        assert!(with_constant(class, "A").validate().is_ok());
    }

    #[test]
    #[cfg(feature = "embed")]
    fn test_constant() {
        let class = ClassBuilder::new("Foo")
            .constant("bar", 42, &["Doc 1"], ConstantFlags::Public)
            .expect("Failed to create constant");
        assert_eq!(class.constants.len(), 1);
        assert_eq!(class.constants[0].0, "bar");
        assert_eq!(class.constants[0].2, &["Doc 1"] as DocComments);
    }

    #[test]
    #[cfg(feature = "embed")]
    fn test_dyn_constant() {
        let class = ClassBuilder::new("Foo")
            .dyn_constant("bar", &42, &["Doc 1"], ConstantFlags::Public)
            .expect("Failed to create constant");
        assert_eq!(class.constants.len(), 1);
        assert_eq!(class.constants[0].0, "bar");
        assert_eq!(class.constants[0].2, &["Doc 1"] as DocComments);
    }

    #[test]
    fn test_flags() {
        let class = ClassBuilder::new("Foo").flags(ClassFlags::Abstract);
        assert_eq!(class.ce.ce_flags, ClassFlags::Abstract.bits());
    }

    #[test]
    fn test_registration() {
        let class = ClassBuilder::new("Foo").registration(|_, _| {});
        assert!(class.register.is_some());
    }

    #[test]
    fn test_registration_interface() {
        let class = ClassBuilder::new("Foo")
            .flags(ClassFlags::Interface)
            .registration(|_, _| {});
        assert!(class.register.is_some());
    }

    #[test]
    fn test_docs() {
        let class = ClassBuilder::new("Foo").docs(&["Doc 1"]);
        assert_eq!(class.docs, &["Doc 1"] as DocComments);
    }

    // TODO: Test the register function
}