godot-core 0.5.1

Internal crate used by godot-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
/*
 * Copyright (c) godot-rust; Bromeon and contributors.
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at https://mozilla.org/MPL/2.0/.
 */

use std::collections::HashMap;
use std::{any, ptr};

use sys::{Global, GlobalGuard, GlobalLockError, interface_fn, out};

use crate::classes::ClassDb;
use crate::init::InitLevel;
use crate::meta::ClassId;
use crate::meta::error::FromGodotError;
use crate::obj::{DynGd, Gd, GodotClass, Singleton, cap};
use crate::private::{ClassPlugin, PluginItem};
use crate::registry::callbacks;
use crate::registry::plugin::{DynTraitImpl, ErasedRegisterFn, ITraitImpl, InherentImpl, Struct};
use crate::{godot_error, godot_warn, sys};

/// Returns a lock to a global map of loaded classes, by initialization level.
///
/// Needed for class unregistering. The `static` is populated during class registering. There is no actual concurrency here, because Godot
/// calls register/unregister in the main thread. Mutex is just casual way to ensure safety in this non-performance-critical path.
/// Note that we panic on concurrent access instead of blocking (fail-fast approach). If that happens, most likely something changed on Godot
/// side and analysis required to adopt these changes.
fn global_loaded_classes_by_init_level()
-> GlobalGuard<'static, HashMap<InitLevel, Vec<LoadedClass>>> {
    static LOADED_CLASSES_BY_INIT_LEVEL: Global<
        HashMap<InitLevel, Vec<LoadedClass>>, //.
    > = Global::default();

    lock_or_panic(&LOADED_CLASSES_BY_INIT_LEVEL, "loaded classes")
}

/// Returns a lock to a global map of loaded classes, by class name.
///
/// Complementary mechanism to the on-registration hooks like `__register_methods()`. This is used for runtime queries about a class, for
/// information which isn't stored in Godot. Example: list related `dyn Trait` implementations.
fn global_loaded_classes_by_name() -> GlobalGuard<'static, HashMap<ClassId, ClassMetadata>> {
    static LOADED_CLASSES_BY_NAME: Global<HashMap<ClassId, ClassMetadata>> = Global::default();

    lock_or_panic(&LOADED_CLASSES_BY_NAME, "loaded classes (by name)")
}

fn global_dyn_traits_by_typeid() -> GlobalGuard<'static, HashMap<any::TypeId, Vec<DynTraitImpl>>> {
    static DYN_TRAITS_BY_TYPEID: Global<HashMap<any::TypeId, Vec<DynTraitImpl>>> =
        Global::default();

    lock_or_panic(&DYN_TRAITS_BY_TYPEID, "dyn traits")
}

// ----------------------------------------------------------------------------------------------------------------------------------------------

/// Represents a class which is currently loaded and retained in memory.
///
/// Besides the name, this type holds information relevant for the deregistration of the class.
pub struct LoadedClass {
    name: ClassId,
    is_editor_plugin: bool,
    unregister_singleton_fn: Option<fn()>,
}

/// Represents a class which is currently loaded and retained in memory -- including metadata.
//
// Currently empty, but should already work for per-class queries.
pub struct ClassMetadata {}

// ----------------------------------------------------------------------------------------------------------------------------------------------

// This works as long as fields are called the same. May still need individual #[cfg]s for newer fields.
#[cfg(before_api = "4.3")] #[cfg_attr(published_docs, doc(cfg(before_api = "4.3")))]
type GodotCreationInfo = sys::GDExtensionClassCreationInfo2;
#[cfg(all(since_api = "4.3", before_api = "4.4"))] #[cfg_attr(published_docs, doc(cfg(all(since_api = "4.3", before_api = "4.4"))))]
type GodotCreationInfo = sys::GDExtensionClassCreationInfo3;
#[cfg(since_api = "4.4")] #[cfg_attr(published_docs, doc(cfg(since_api = "4.4")))]
type GodotCreationInfo = sys::GDExtensionClassCreationInfo4;

#[cfg(before_api = "4.4")] #[cfg_attr(published_docs, doc(cfg(before_api = "4.4")))]
pub(crate) type GodotGetVirtual = <sys::GDExtensionClassGetVirtual as sys::Inner>::FnPtr;
#[cfg(since_api = "4.4")] #[cfg_attr(published_docs, doc(cfg(since_api = "4.4")))]
pub(crate) type GodotGetVirtual = <sys::GDExtensionClassGetVirtual2 as sys::Inner>::FnPtr;

#[derive(Debug)]
struct ClassRegistrationInfo {
    class_name: ClassId,
    parent_class_name: Option<ClassId>,
    // Following functions are stored separately, since their order matters.
    register_methods_constants_fn: Option<ErasedRegisterFn>,
    register_properties_fn: Option<ErasedRegisterFn>,
    user_register_fn: Option<ErasedRegisterFn>,
    default_virtual_fn: Option<GodotGetVirtual>, // Optional (set if there is at least one OnReady field)
    user_virtual_fn: Option<GodotGetVirtual>, // Optional (set if there is a `#[godot_api] impl I*`)
    register_singleton_fn: Option<fn()>,
    unregister_singleton_fn: Option<fn()>,

    /// Godot low-level class creation parameters.
    godot_params: GodotCreationInfo,

    #[allow(dead_code)] // Currently unused; may be useful for diagnostics in the future.
    init_level: InitLevel,
    is_editor_plugin: bool,

    /// One entry for each `dyn Trait` implemented (and registered) for this class.
    dynify_fns_by_trait: HashMap<any::TypeId, DynTraitImpl>,

    /// Used to ensure that each component is only filled once.
    component_already_filled: [bool; 4],
}

impl ClassRegistrationInfo {
    fn validate_unique(&mut self, item: &PluginItem) {
        // We could use mem::Discriminant, but match will fail to compile when a new component is added.

        // Note: when changing this match, make sure the array has sufficient size.
        let index = match item {
            PluginItem::Struct { .. } => 0,
            PluginItem::InherentImpl(_) => 1,
            PluginItem::ITraitImpl { .. } => 2,

            // Multiple dyn traits can be registered, thus don't validate for uniqueness.
            // (Still keep array size, so future additions don't have to regard this).
            PluginItem::DynTraitImpl { .. } => return,
        };

        if self.component_already_filled[index] {
            panic!(
                "Godot class `{}` is defined multiple times in Rust; you can rename it with #[class(rename=NewName)]",
                self.class_name,
            )
        }

        self.component_already_filled[index] = true;
    }
}

/// Registers a class with static type information.
#[expect(dead_code)] // Will be needed for builder API. Don't remove.
pub(crate) fn register_class<
    T: cap::GodotDefault
        + cap::ImplementsGodotVirtual
        + cap::GodotToString
        + cap::GodotNotification
        + cap::GodotRegisterClass
        + GodotClass,
>() {
    // TODO: provide overloads with only some trait impls

    out!("Manually register class {}", std::any::type_name::<T>());

    let godot_params = GodotCreationInfo {
        to_string_func: Some(callbacks::to_string::<T>),
        notification_func: Some(callbacks::on_notification::<T>),
        reference_func: Some(callbacks::reference::<T>),
        unreference_func: Some(callbacks::unreference::<T>),
        create_instance_func: Some(callbacks::create::<T>),
        free_instance_func: Some(callbacks::free::<T>),
        get_virtual_func: Some(callbacks::get_virtual::<T>),
        class_userdata: ptr::null_mut(), // will be passed to create fn, but global per class
        ..default_creation_info()
    };

    assert!(
        !T::class_id().is_none(),
        "cannot register () or unnamed class"
    );

    register_class_raw(ClassRegistrationInfo {
        class_name: T::class_id(),
        parent_class_name: Some(T::Base::class_id()),
        register_methods_constants_fn: None,
        register_properties_fn: None,
        user_register_fn: Some(ErasedRegisterFn {
            raw: callbacks::register_class_by_builder::<T>,
        }),
        user_virtual_fn: None,
        default_virtual_fn: None,
        godot_params,
        init_level: T::INIT_LEVEL,
        is_editor_plugin: false,
        dynify_fns_by_trait: HashMap::new(),
        component_already_filled: Default::default(), // [false; N]
        register_singleton_fn: None,
        unregister_singleton_fn: None,
    });
}

/// Lets Godot know about all classes that have self-registered through the plugin system.
pub fn auto_register_classes(init_level: InitLevel) {
    out!("Auto-register classes at level `{init_level:?}`...");

    // Note: many errors are already caught by the compiler, before this runtime validation even takes place:
    // * missing #[derive(GodotClass)] or impl GodotClass for T
    // * duplicate impl GodotDefault for T
    //
    let mut map = HashMap::<ClassId, ClassRegistrationInfo>::new();

    crate::private::iterate_plugins(|elem: &ClassPlugin| {
        // Filter per ClassPlugin and not PluginItem, because all components of all classes are mixed together in one huge list.
        if elem.init_level != init_level {
            return;
        }

        //out!("* Plugin: {elem:#?}");

        let name = elem.class_name;
        let class_info = map
            .entry(name)
            .or_insert_with(|| default_registration_info(name));

        fill_class_info(elem.item.clone(), class_info);
    });

    // First register all the loaded classes and dyn traits.
    // We need all the dyn classes in the registry to properly register DynGd properties;
    // one can do it directly inside the loop – by locking and unlocking the mutex –
    // but it is much slower and doesn't guarantee that all the dependent classes will be already loaded in most cases.
    register_classes_and_dyn_traits(&mut map, init_level);

    // Before Godot 4.4.1, editor plugins were added to the editor immediately, triggering their lifecycle methods –- even before their
    // dependencies (e.g. properties) have been registered.
    // During hot-reload, Godot erases all GDExtension instance bindings (the "rust part"), effectively changing them to the base classes.
    // These two behaviors combined were leading to crashes.
    //
    // Since Godot 4.4.1, adding new EditorPlugin to the editor is being postponed until the end of the frame (i.e. after library registration).
    // See also: https://github.com/godot-rust/gdext/issues/1132.
    let mut editor_plugins: Vec<ClassId> = Vec::new();

    // Similarly to EnginePlugins – freshly instantiated engine singleton might depend on some not-yet-registered classes.
    let mut singletons: Vec<fn()> = Vec::new();

    // Actually register all the classes.
    for info in map.into_values() {
        #[cfg(feature = "debug-log")] #[cfg_attr(published_docs, doc(cfg(feature = "debug-log")))]
        let class_name = info.class_name;

        if info.is_editor_plugin {
            editor_plugins.push(info.class_name);
        }

        if let Some(register_singleton_fn) = info.register_singleton_fn {
            singletons.push(register_singleton_fn)
        }

        register_class_raw(info);

        out!("Class {class_name} loaded.");
    }

    for register_singleton_fn in singletons {
        register_singleton_fn()
    }

    for editor_plugin_class_name in editor_plugins {
        unsafe { interface_fn!(editor_add_plugin)(editor_plugin_class_name.string_sys()) };
    }

    out!("All classes for level `{init_level:?}` auto-registered.");
}

fn register_classes_and_dyn_traits(
    map: &mut HashMap<ClassId, ClassRegistrationInfo>,
    init_level: InitLevel,
) {
    let mut loaded_classes_by_level = global_loaded_classes_by_init_level();
    let mut loaded_classes_by_name = global_loaded_classes_by_name();
    let mut dyn_traits_by_typeid = global_dyn_traits_by_typeid();

    for info in map.values_mut() {
        let class_name = info.class_name;
        out!("Register class:   {class_name} at level `{init_level:?}`");

        let loaded_class = LoadedClass {
            name: class_name,
            is_editor_plugin: info.is_editor_plugin,
            unregister_singleton_fn: info.unregister_singleton_fn,
        };
        let metadata = ClassMetadata {};

        // Transpose Class->Trait relations to Trait->Class relations.
        for (trait_type_id, mut dyn_trait_impl) in info.dynify_fns_by_trait.drain() {
            // Note: Must be done after filling out the class info since plugins are being iterated in unspecified order.
            dyn_trait_impl.parent_class_name = info.parent_class_name;

            dyn_traits_by_typeid
                .entry(trait_type_id)
                .or_default()
                .push(dyn_trait_impl);
        }

        loaded_classes_by_level
            .entry(init_level)
            .or_default()
            .push(loaded_class);

        loaded_classes_by_name.insert(class_name, metadata);
    }
}

pub fn unregister_classes(init_level: InitLevel) {
    let mut loaded_classes_by_level = global_loaded_classes_by_init_level();
    let mut loaded_classes_by_name = global_loaded_classes_by_name();
    // TODO clean up dyn traits

    let loaded_classes_current_level = loaded_classes_by_level
        .remove(&init_level)
        .unwrap_or_default();

    out!("Unregister classes of level {init_level:?}...");
    for class in loaded_classes_current_level.into_iter().rev() {
        // Remove from other map.
        loaded_classes_by_name.remove(&class.name);

        // Unregister from Godot.
        unregister_class_raw(class);
    }
}

#[cfg(feature = "codegen-full")] #[cfg_attr(published_docs, doc(cfg(feature = "codegen-full")))]
pub fn auto_register_rpcs<T: GodotClass>(object: &mut T) {
    // Find the element that matches our class, and call the closure if it exists.
    if let Some(InherentImpl {
        register_rpcs_fn: Some(closure),
        ..
    }) = crate::private::find_inherent_impl(T::class_id())
    {
        (closure.raw)(object);
    }
}

/// Tries to convert a `Gd<T>` to a `DynGd<T, D>` for some class `T` and trait object `D`, where the trait may only be implemented for
/// some subclass of `T`.
///
/// This works even when `T` doesn't implement `AsDyn<D>`, as long as the dynamic class of `object` implements `AsDyn<D>`.
///
/// This only looks for an `AsDyn<D>` implementation in the dynamic class; the conversion will fail if the dynamic class doesn't
/// implement `AsDyn<D>`, even if there exists some superclass that does implement `AsDyn<D>`. This restriction could in theory be
/// lifted, but would need quite a bit of extra machinery to work.
pub(crate) fn try_dynify_object<T: GodotClass, D: ?Sized + 'static>(
    mut object: Gd<T>,
) -> Result<DynGd<T, D>, (FromGodotError, Gd<T>)> {
    let typeid = any::TypeId::of::<D>();
    let trait_name = sys::short_type_name::<D>();

    // Iterate all classes that implement the trait.
    let dyn_traits_by_typeid = global_dyn_traits_by_typeid();
    let Some(relations) = dyn_traits_by_typeid.get(&typeid) else {
        return Err((FromGodotError::UnregisteredDynTrait { trait_name }, object));
    };

    // TODO maybe use 2nd hashmap instead of linear search.
    // (probably not pair of typeid/classname, as that wouldn't allow the above check).
    for relation in relations {
        match relation.get_dyn_gd(object) {
            Ok(dyn_gd) => return Ok(dyn_gd),
            Err(obj) => object = obj,
        }
    }

    let error = FromGodotError::UnimplementedDynTrait {
        trait_name,
        class_name: object.dynamic_class_string().to_string(),
    };

    Err((error, object))
}

/// Returns the `ClassId`s of all concrete implementors of trait `D` that inherit from `T`.
///
/// Used by [`DynGd<T, D>`][crate::obj::DynGd] to populate [`ClassAncestor::DynResource`][crate::registry::property::ClassAncestor::DynResource]
/// with the set of valid implementor classes from the `#[godot_dyn]` registry.
///
/// See also [Godot docs for PropertyHint](https://docs.godotengine.org/en/stable/classes/class_@globalscope.html#enum-globalscope-propertyhint).
pub(crate) fn get_dyn_implementor_class_ids<T, D>() -> Vec<ClassId>
where
    T: GodotClass,
    D: ?Sized + 'static,
{
    let typeid = any::TypeId::of::<D>();
    let dyn_traits_by_typeid = global_dyn_traits_by_typeid();

    let Some(relations) = dyn_traits_by_typeid.get(&typeid) else {
        let trait_name = sys::short_type_name::<D>();
        godot_warn!(
            "godot-rust: No class has been linked to trait {trait_name} with #[godot_dyn]."
        );
        return Vec::new();
    };
    assert!(
        !relations.is_empty(),
        "Trait {trait_name} has been registered as DynGd Trait \
        despite no class being related to it \n\
        **this is a bug, please report it**",
        trait_name = sys::short_type_name::<D>()
    );

    // Include only implementors inheriting given T.
    // For example — don't include Nodes or Objects while creating hint_string for Resource.
    relations
        .iter()
        .filter_map(|implementor| {
            // TODO — check if caching it (using is_derived_base_cached) yields any benefits.
            if implementor.parent_class_name? == T::class_id()
                || ClassDb::singleton().is_parent_class(
                    &implementor.parent_class_name?.to_string_name(),
                    &T::class_id().to_string_name(),
                )
            {
                Some(*implementor.class_name())
            } else {
                None
            }
        })
        .collect()
}

/// Populate `c` with all the relevant data from `component` (depending on component type).
fn fill_class_info(item: PluginItem, c: &mut ClassRegistrationInfo) {
    c.validate_unique(&item);

    // out!("|   reg (before):    {c:?}");
    // out!("|   comp:            {component:?}");
    match item {
        PluginItem::Struct(Struct {
            base_class_name,
            generated_create_fn,
            generated_recreate_fn,
            register_properties_fn,
            free_fn,
            default_get_virtual_fn,
            unregister_singleton_fn,
            register_singleton_fn,
            is_tool,
            is_editor_plugin,
            is_internal,
            is_instantiable,
            reference_fn,
            unreference_fn,
        }) => {
            c.parent_class_name = Some(base_class_name);
            c.default_virtual_fn = default_get_virtual_fn;
            c.register_properties_fn = Some(register_properties_fn);
            c.is_editor_plugin = is_editor_plugin;
            c.register_singleton_fn = register_singleton_fn;
            c.unregister_singleton_fn = unregister_singleton_fn;

            // Classes marked #[class(no_init)] are translated to "abstract" in Godot. This disables their default constructor.
            // "Abstract" is a misnomer -- it's not an abstract base class, but rather a "utility/static class" (although it can have instance
            // methods). Examples are Input, IP, FileAccess, DisplayServer.
            //
            // Abstract base classes on the other hand are called "virtual" in Godot. Examples are Mesh, Material, Texture.
            // For some reason, certain ABCs like PhysicsBody2D are not marked "virtual" but "abstract".
            //
            // See also: https://github.com/godotengine/godot/pull/58972
            c.godot_params.is_abstract = sys::conv::bool_to_sys(!is_instantiable);
            c.godot_params.free_instance_func = Some(free_fn);
            c.godot_params.reference_func = reference_fn;
            c.godot_params.unreference_func = unreference_fn;

            fill_into(
                &mut c.godot_params.create_instance_func,
                generated_create_fn,
            )
            .expect("duplicate: create_instance_func (def)");

            fill_into(
                &mut c.godot_params.recreate_instance_func,
                generated_recreate_fn,
            )
            .expect("duplicate: recreate_instance_func (def)");

            c.godot_params.is_exposed = sys::conv::bool_to_sys(!is_internal);

            #[cfg(before_api = "4.3")] #[cfg_attr(published_docs, doc(cfg(before_api = "4.3")))]
            let _ = is_tool; // mark used
            #[cfg(since_api = "4.3")]
            {
                c.godot_params.is_runtime =
                    sys::conv::bool_to_sys(crate::private::is_class_runtime(is_tool));
            }
        }

        PluginItem::InherentImpl(InherentImpl {
            register_methods_constants_fn,
            register_rpcs_fn: _,
        }) => {
            c.register_methods_constants_fn = Some(register_methods_constants_fn);
        }

        PluginItem::ITraitImpl(ITraitImpl {
            user_register_fn,
            user_create_fn,
            user_recreate_fn,
            user_to_string_fn,
            user_on_notification_fn,
            user_set_fn,
            user_get_fn,
            get_virtual_fn,
            user_get_property_list_fn,
            user_free_property_list_fn,
            user_property_can_revert_fn,
            user_property_get_revert_fn,
            validate_property_fn,
        }) => {
            c.user_register_fn = user_register_fn;

            // The following unwraps of fill_into() shouldn't panic, since rustc will error if there are
            // multiple `impl I{Class} for Thing` definitions.

            fill_into(&mut c.godot_params.create_instance_func, user_create_fn)
                .expect("duplicate: create_instance_func (i)");

            fill_into(&mut c.godot_params.recreate_instance_func, user_recreate_fn)
                .expect("duplicate: recreate_instance_func (i)");

            c.godot_params.to_string_func = user_to_string_fn;
            c.godot_params.notification_func = user_on_notification_fn;
            c.godot_params.set_func = user_set_fn;
            c.godot_params.get_func = user_get_fn;
            c.godot_params.get_property_list_func = user_get_property_list_fn;
            c.godot_params.free_property_list_func = user_free_property_list_fn;
            c.godot_params.property_can_revert_func = user_property_can_revert_fn;
            c.godot_params.property_get_revert_func = user_property_get_revert_fn;
            c.user_virtual_fn = get_virtual_fn;
            {
                c.godot_params.validate_property_func = validate_property_fn;
            }
        }
        PluginItem::DynTraitImpl(dyn_trait_impl) => {
            let type_id = dyn_trait_impl.dyn_trait_typeid();

            let prev = c.dynify_fns_by_trait.insert(type_id, dyn_trait_impl);

            assert!(
                prev.is_none(),
                "Duplicate registration of {:?} for class {}",
                type_id,
                c.class_name
            );
        }
    }
    // out!("|   reg (after):     {c:?}");
    // out!();
}

/// If `src` is occupied, it moves the value into `dst`, while ensuring that no previous value is present in `dst`.
fn fill_into<T>(dst: &mut Option<T>, src: Option<T>) -> Result<(), ()> {
    match (dst, src) {
        (dst @ None, src) => *dst = src,
        (Some(_), Some(_)) => return Err(()),
        (Some(_), None) => { /* do nothing */ }
    }
    Ok(())
}

/// Registers a class with given the dynamic type information `info`.
fn register_class_raw(mut info: ClassRegistrationInfo) {
    // Some metadata like dynify fns are already emptied at this point. Only consider registrations for Godot.

    // First register class...
    validate_class_constraints(&info);

    let class_name = info.class_name;
    let parent_class_name = info
        .parent_class_name
        .expect("class defined (parent_class_name)");

    // Register virtual functions -- if the user provided some via #[godot_api], take those; otherwise, use the
    // ones generated alongside #[derive(GodotClass)]. The latter can also be null, if no OnReady is provided.
    if info.godot_params.get_virtual_func.is_none() {
        info.godot_params.get_virtual_func = info.user_virtual_fn.or(info.default_virtual_fn);
    }

    // The explicit () type notifies us if Godot API ever adds a return type.
    let registration_failed = unsafe {
        // Try to register class...

        #[cfg(before_api = "4.3")] #[cfg_attr(published_docs, doc(cfg(before_api = "4.3")))]
        let register_fn = interface_fn!(classdb_register_extension_class2);

        #[cfg(all(since_api = "4.3", before_api = "4.4"))] #[cfg_attr(published_docs, doc(cfg(all(since_api = "4.3", before_api = "4.4"))))]
        let register_fn = interface_fn!(classdb_register_extension_class3);

        #[cfg(since_api = "4.4")] #[cfg_attr(published_docs, doc(cfg(since_api = "4.4")))]
        let register_fn = interface_fn!(classdb_register_extension_class4);

        let _: () = register_fn(
            sys::get_library(),
            class_name.string_sys(),
            parent_class_name.string_sys(),
            ptr::addr_of!(info.godot_params),
        );

        // ...then see if it worked.
        // This is necessary because the above registration does not report errors (apart from console output).
        let tag = interface_fn!(classdb_get_class_tag)(class_name.string_sys());
        tag.is_null()
    };

    // Do not panic here; otherwise lock is poisoned and the whole extension becomes unusable.
    // This can happen during hot reload if a class changes base type in an incompatible way (e.g. RefCounted -> Node).
    if registration_failed {
        godot_error!(
            "Failed to register class `{class_name}`; check preceding Godot stderr messages."
        );
    }

    // ...then custom symbols

    //let mut class_builder = crate::builder::ClassBuilder::<?>::new();
    let mut class_builder = 0; // TODO dummy argument; see callbacks

    // Order of the following registrations is crucial:
    // 1. Methods and constants.
    // 2. Properties (they may depend on get/set methods).
    // 3. User-defined registration function (intuitively, user expects their own code to run after proc-macro generated code).
    if let Some(register_fn) = info.register_methods_constants_fn {
        (register_fn.raw)(&mut class_builder);
    }

    if let Some(register_fn) = info.register_properties_fn {
        (register_fn.raw)(&mut class_builder);
    }

    if let Some(register_fn) = info.user_register_fn {
        (register_fn.raw)(&mut class_builder);
    }
}

fn validate_class_constraints(_class: &ClassRegistrationInfo) {
    // TODO: if we add builder API, the proc-macro checks in parse_struct_attributes() etc. should be duplicated here.
}

fn unregister_class_raw(class: LoadedClass) {
    let class_name = class.name;
    out!("Unregister class: {class_name}");

    // If class is an editor plugin, unregister that first.
    if class.is_editor_plugin {
        unsafe {
            interface_fn!(editor_remove_plugin)(class_name.string_sys());
        }

        out!("> Editor plugin removed");
    }

    // Similarly to EditorPlugin – given instance is being freed and will not be recreated
    // during hot reload (a new, independent one will be created instead).
    if let Some(unregister_singleton_fn) = class.unregister_singleton_fn {
        unregister_singleton_fn();
    }

    #[allow(clippy::let_unit_value)]
    let _: () = unsafe {
        interface_fn!(classdb_unregister_extension_class)(
            sys::get_library(),
            class_name.string_sys(),
        )
    };

    out!("Class {class_name} unloaded");
}

fn lock_or_panic<T>(global: &'static Global<T>, ctx: &str) -> GlobalGuard<'static, T> {
    match global.try_lock() {
        Ok(it) => it,
        Err(err) => match err {
            GlobalLockError::Poisoned { .. } => panic!(
                "global lock for {ctx} poisoned; class registration or deregistration may have panicked"
            ),
            GlobalLockError::WouldBlock => {
                panic!("unexpected concurrent access to global lock for {ctx}")
            }
            GlobalLockError::InitFailed => unreachable!("global lock for {ctx} not initialized"),
        },
    }
}

// ----------------------------------------------------------------------------------------------------------------------------------------------
// Substitutes for Default impl

// Yes, bindgen can implement Default, but only for _all_ types (with single exceptions).
// For FFI types, it's better to have explicit initialization in the general case though.
fn default_registration_info(class_name: ClassId) -> ClassRegistrationInfo {
    ClassRegistrationInfo {
        class_name,
        parent_class_name: None,
        register_methods_constants_fn: None,
        register_properties_fn: None,
        user_register_fn: None,
        default_virtual_fn: None,
        user_virtual_fn: None,
        register_singleton_fn: None,
        unregister_singleton_fn: None,
        godot_params: default_creation_info(),
        init_level: InitLevel::Scene,
        is_editor_plugin: false,
        dynify_fns_by_trait: HashMap::new(),
        component_already_filled: Default::default(), // [false; N]
    }
}

#[cfg(before_api = "4.3")] #[cfg_attr(published_docs, doc(cfg(before_api = "4.3")))]
fn default_creation_info() -> sys::GDExtensionClassCreationInfo2 {
    sys::GDExtensionClassCreationInfo2 {
        is_virtual: false as u8,
        is_abstract: false as u8,
        is_exposed: sys::conv::SYS_TRUE,
        set_func: None,
        get_func: None,
        get_property_list_func: None,
        free_property_list_func: None,
        property_can_revert_func: None,
        property_get_revert_func: None,
        validate_property_func: None,
        notification_func: None,
        to_string_func: None,
        reference_func: None,
        unreference_func: None,
        create_instance_func: None,
        free_instance_func: None,
        recreate_instance_func: None,
        get_virtual_func: None,
        get_virtual_call_data_func: None,
        call_virtual_with_data_func: None,
        get_rid_func: None,
        class_userdata: ptr::null_mut(),
    }
}

#[cfg(all(since_api = "4.3", before_api = "4.4"))] #[cfg_attr(published_docs, doc(cfg(all(since_api = "4.3", before_api = "4.4"))))]
fn default_creation_info() -> sys::GDExtensionClassCreationInfo3 {
    sys::GDExtensionClassCreationInfo3 {
        is_virtual: false as u8,
        is_abstract: false as u8,
        is_exposed: sys::conv::SYS_TRUE,
        is_runtime: sys::conv::SYS_TRUE,
        set_func: None,
        get_func: None,
        get_property_list_func: None,
        free_property_list_func: None,
        property_can_revert_func: None,
        property_get_revert_func: None,
        validate_property_func: None,
        notification_func: None,
        to_string_func: None,
        reference_func: None,
        unreference_func: None,
        create_instance_func: None,
        free_instance_func: None,
        recreate_instance_func: None,
        get_virtual_func: None,
        get_virtual_call_data_func: None,
        call_virtual_with_data_func: None,
        get_rid_func: None,
        class_userdata: ptr::null_mut(),
    }
}

#[cfg(since_api = "4.4")] #[cfg_attr(published_docs, doc(cfg(since_api = "4.4")))]
fn default_creation_info() -> sys::GDExtensionClassCreationInfo4 {
    sys::GDExtensionClassCreationInfo4 {
        is_virtual: false as u8,
        is_abstract: false as u8,
        is_exposed: sys::conv::SYS_TRUE,
        is_runtime: sys::conv::SYS_TRUE,
        icon_path: ptr::null(),
        set_func: None,
        get_func: None,
        get_property_list_func: None,
        free_property_list_func: None,
        property_can_revert_func: None,
        property_get_revert_func: None,
        validate_property_func: None,
        notification_func: None,
        to_string_func: None,
        reference_func: None,
        unreference_func: None,
        create_instance_func: None,
        free_instance_func: None,
        recreate_instance_func: None,
        get_virtual_func: None,
        get_virtual_call_data_func: None,
        call_virtual_with_data_func: None,
        class_userdata: ptr::null_mut(),
    }
}