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
790
791
792
793
794
/*
 * 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::sync::OnceLock;
use std::{fmt, ptr};

use godot_ffi as sys;
use sys::{ExtVariantType, GodotFfi, ffi_methods};

use crate::builtin::{AnyArray, CowStr, StringName, Variant, inner};
use crate::meta::{GodotType, ToGodot};
use crate::obj::bounds::DynMemory;
use crate::obj::{Bounds, Gd, GodotClass, InstanceId, Singleton};
use crate::{classes, meta};

#[cfg(before_api = "4.3")] #[cfg_attr(published_docs, doc(cfg(before_api = "4.3")))]
type CallableCustomInfo = sys::GDExtensionCallableCustomInfo;
#[cfg(since_api = "4.3")] #[cfg_attr(published_docs, doc(cfg(since_api = "4.3")))]
type CallableCustomInfo = sys::GDExtensionCallableCustomInfo2;

/// A `Callable` represents a function in Godot.
///
/// Callables can be created in many ways:
/// - From an `Object` and a (non-static) method name. This is a _standard_ callable.
/// - From a GDScript class name and a static function name. (This typically works because classes are instances of `GDScript`).
/// - From a GDScript lambda function.
/// - By modifying an existing `Callable` with [`bind()`][Self::bind] or [`unbind()`][Self::unbind].
/// - By creating a custom callable from Rust.
///
/// # Godot docs
///
/// [`Callable` (stable)](https://docs.godotengine.org/en/stable/classes/class_callable.html)
pub struct Callable {
    opaque: sys::types::OpaqueCallable,
}

impl Callable {
    fn from_opaque(opaque: sys::types::OpaqueCallable) -> Self {
        Self { opaque }
    }

    /// Create a callable for the non-static method `object.method_name`.
    ///
    /// See also [`Gd::callable()`].
    ///
    /// _Godot equivalent: `Callable(Object object, StringName method)`_
    pub fn from_object_method<T, S>(object: &Gd<T>, method_name: S) -> Self
    where
        T: GodotClass, // + Inherits<Object>,
        S: meta::AsArg<StringName>,
    {
        meta::arg_into_ref!(method_name);

        unsafe {
            Self::new_with_uninit(|self_ptr| {
                let ctor = sys::builtin_fn!(callable_from_object_method);
                let raw = object.to_ffi();
                let args = [raw.as_arg_ptr(), method_name.sys()];
                ctor(self_ptr, args.as_ptr());
            })
        }
    }

    /// Create a callable for a method on any [`Variant`].
    ///
    /// Allows to dynamically call methods on builtin types (e.g. `String.md5_text`). Note that Godot method names are used, not Rust ones.
    /// If the variant type is `Object`, the behavior will match that of `from_object_method()`.
    ///
    /// If the builtin type does not have the method, the returned callable will be invalid.
    ///
    /// Static builtin methods (e.g. `String.humanize_size`) are not supported in reflection as of Godot 4.4. For static _class_ functions,
    /// use [`from_class_static()`][Self::from_class_static] instead.
    ///
    /// _Godot equivalent: `Callable.create(Variant variant, StringName method)`_
    #[cfg(since_api = "4.3")] #[cfg_attr(published_docs, doc(cfg(since_api = "4.3")))]
    pub fn from_variant_method<S>(variant: &Variant, method_name: S) -> Self
    where
        S: meta::AsArg<StringName>,
    {
        meta::arg_into_ref!(method_name);
        inner::InnerCallable::create(variant, method_name)
    }

    /// Create a callable for the static method `class_name::function`
    ///
    /// Allows you to call static functions through `Callable`. Allows both single- and multi-threaded calls; what happens on Godot side
    /// is your responsibility.
    ///
    /// Does not support built-in types (such as `String`), only classes. Static functions on built-in types are not supported in Godot's
    /// reflection APIs at the moment.
    #[cfg(since_api = "4.4")] #[cfg_attr(published_docs, doc(cfg(since_api = "4.4")))]
    pub fn from_class_static(
        class_name: impl meta::AsArg<StringName>,
        function_name: impl meta::AsArg<StringName>,
    ) -> Self {
        meta::arg_into_owned!(class_name);
        meta::arg_into_owned!(function_name);

        let callable_name = format!("{class_name}.{function_name}");

        let function = move |args: &[&Variant]| {
            let args = args.iter().cloned().cloned().collect::<Vec<_>>();

            let result: Variant = classes::ClassDb::singleton().class_call_static(
                &class_name,
                &function_name,
                args.as_slice(),
            );
            result
        };

        #[cfg(feature = "experimental-threads")] #[cfg_attr(published_docs, doc(cfg(feature = "experimental-threads")))]
        let callable = Self::from_sync_fn(callable_name, function);

        #[cfg(not(feature = "experimental-threads"))] #[cfg_attr(published_docs, doc(cfg(not(feature = "experimental-threads"))))]
        let callable = Self::from_fn(callable_name, function);

        callable
    }

    fn default_callable_custom_info() -> CallableCustomInfo {
        CallableCustomInfo {
            callable_userdata: ptr::null_mut(),
            token: ptr::null_mut(),
            object_id: 0,
            call_func: None,
            is_valid_func: None, // overwritten later.
            free_func: None,
            hash_func: None,
            equal_func: None,
            // Op < is only used in niche scenarios and default is usually good enough, see https://github.com/godotengine/godot/issues/81901.
            less_than_func: None,
            to_string_func: None,
            #[cfg(since_api = "4.3")] #[cfg_attr(published_docs, doc(cfg(since_api = "4.3")))]
            get_argument_count_func: None,
        }
    }

    /// Create callable from **single-threaded** Rust function or closure.
    ///
    /// `name` is used for the string representation of the closure, which helps debugging.
    ///
    /// This constructor only allows the callable to be invoked from the same thread as creating it. If you need to invoke it from any thread,
    /// use [`from_sync_fn`][Self::from_sync_fn] instead (requires crate feature `experimental-threads`; only enable if really needed).
    ///
    /// You can also couple the callable to the lifetime of an object, see [`from_linked_fn()`][Self::from_linked_fn].
    pub fn from_fn<R, F, S>(name: S, rust_function: F) -> Self
    where
        R: ToGodot,
        F: 'static + FnMut(&[&Variant]) -> R,
        S: Into<CowStr>,
    {
        Self::from_fn_wrapper(name, rust_function, None)
    }

    /// Creates a new callable linked to the given object from **single-threaded** Rust function or closure.
    ///
    /// `name` is used for the string representation of the closure, which helps with debugging.
    ///
    /// Such a callable will be automatically invalidated by Godot when a linked object is freed.
    /// Prefer using [`Gd::linked_callable()`] instead.
    ///
    /// If you need a callable which can live indefinitely, use [`Callable::from_fn()`].
    pub fn from_linked_fn<R, F, T, S>(name: S, linked_object: &Gd<T>, rust_function: F) -> Self
    where
        R: ToGodot,
        T: GodotClass,
        F: 'static + FnMut(&[&Variant]) -> R,
        S: Into<CowStr>,
    {
        Self::from_fn_wrapper(name, rust_function, Some(linked_object.instance_id()))
    }

    /// Create callable from **single-threaded** Rust function or closure that can only be called once.
    ///
    /// `name` is used for the string representation of the closure, which helps debugging.
    ///
    /// After the first invocation, subsequent calls will panic with a message indicating the callable has already been consumed. This is
    /// useful for deferred operations that should only execute once. For repeated execution, use [`from_fn()][Self::from_fn].
    pub(crate) fn from_once_fn<R, F, S>(name: S, rust_function: F) -> Self
    where
        R: ToGodot,
        F: 'static + FnOnce(&[&Variant]) -> R,
        S: Into<CowStr>,
    {
        let mut rust_fn_once = Some(rust_function);
        Self::from_fn_wrapper(
            name,
            move |args| {
                let rust_fn_once = rust_fn_once
                    .take()
                    .expect("callable created with from_once_fn() has already been consumed");

                rust_fn_once(args)
            },
            None,
        )
    }

    #[cfg(feature = "trace")] // Test only.
    #[doc(hidden)]
    pub fn __once_fn<F, S>(name: S, rust_function: F) -> Self
    where
        F: 'static + FnOnce(&[&Variant]) -> Variant,
        S: Into<CowStr>,
    {
        Self::from_once_fn(name, rust_function)
    }

    pub(crate) fn with_scoped_fn<S, F, Fc, R>(name: S, rust_function: F, callable_usage: Fc) -> R
    where
        S: Into<CowStr>,
        F: FnMut(&[&Variant]) -> Variant,
        Fc: FnOnce(&Callable) -> R,
    {
        let callable = Self::from_fn_wrapper(name, rust_function, None);

        callable_usage(&callable)
    }

    /// Create callable from **thread-safe** Rust function or closure.
    ///
    /// `name` is used for the string representation of the closure, which helps debugging.
    ///
    /// This constructor requires `Send` + `Sync` bound and allows the callable to be invoked from any thread. If you guarantee that you invoke
    /// it from the same thread as creating it, use [`from_fn`][Self::from_fn] instead.
    ///
    /// Callables created through multiple `from_fn` or `from_sync_fn()` calls are never equal, even if they refer to the same function.
    /// If you want to use equality, either clone an existing `Callable` instance, or define your own `PartialEq` impl with
    /// [`Callable::from_custom`].
    ///
    /// # Example
    /// ```no_run
    /// # use godot::prelude::*;
    /// let callable = Callable::from_sync_fn("sum", |args: &[&Variant]| {
    ///     let sum: i32 = args.iter().map(|arg| arg.to::<i32>()).sum();
    ///     sum
    /// });
    /// ```
    #[cfg(feature = "experimental-threads")] #[cfg_attr(published_docs, doc(cfg(feature = "experimental-threads")))]
    pub fn from_sync_fn<R, F, S>(name: S, rust_function: F) -> Self
    where
        R: ToGodot,
        F: 'static + Send + Sync + FnMut(&[&Variant]) -> R,
        S: Into<CowStr>,
    {
        Self::from_fn_wrapper_with_thread(name, rust_function, None, None)
    }

    /// Create a highly configurable callable from Rust.
    ///
    /// See [`RustCallable`] for requirements on the type.
    pub fn from_custom<C: RustCallable>(callable: C) -> Self {
        // Could theoretically use `dyn` but would need:
        // - double boxing
        // - a type-erased workaround for PartialEq supertrait (which has a `Self` type parameter and thus is not object-safe)
        let userdata = CallableUserdata::new(callable);

        let info = CallableCustomInfo {
            // We could technically associate an object_id with the custom callable. is_valid_func would then check that for validity.
            callable_userdata: Box::into_raw(Box::new(userdata)) as *mut std::ffi::c_void,
            call_func: Some(rust_callable_call_custom::<C>),
            free_func: Some(rust_callable_destroy::<C>),
            hash_func: Some(rust_callable_hash::<C>),
            equal_func: Some(rust_callable_equal::<C>),
            to_string_func: Some(rust_callable_to_string_display::<C>),
            is_valid_func: Some(rust_callable_is_valid_custom::<C>),
            ..Self::default_callable_custom_info()
        };

        Self::from_custom_info(info)
    }

    fn from_fn_wrapper<F, R, S>(
        name: S,
        rust_function: F,
        linked_object_id: Option<InstanceId>,
    ) -> Self
    where
        F: FnMut(&[&Variant]) -> R,
        R: ToGodot,
        S: Into<CowStr>,
    {
        let thread_id = if cfg!(safeguards_balanced) {
            Some(std::thread::current().id())
        } else {
            None // Thread not checked.
        };

        Self::from_fn_wrapper_with_thread(name, rust_function, linked_object_id, thread_id)
    }

    fn from_fn_wrapper_with_thread<F, R, S>(
        name: S,
        rust_function: F,
        linked_object_id: Option<InstanceId>,
        // No #[cfg] on param; would be converted to (invalid) #[doc(cfg)].
        _thread_id: Option<std::thread::ThreadId>,
    ) -> Self
    where
        F: FnMut(&[&Variant]) -> R,
        R: ToGodot,
        S: Into<CowStr>,
    {
        let name = name.into();

        let wrapper = FnWrapper {
            rust_function,
            name,
            name_cached: OnceLock::new(),
            #[cfg(safeguards_balanced)] #[cfg_attr(published_docs, doc(cfg(safeguards_balanced)))]
            thread_id: _thread_id,
            linked_object_id,
        };

        let object_id = wrapper.linked_object_id();
        let userdata = CallableUserdata::new(wrapper);

        let info = CallableCustomInfo {
            object_id,
            callable_userdata: Box::into_raw(Box::new(userdata)) as *mut std::ffi::c_void,
            call_func: Some(rust_callable_call_fn::<F, R>),
            free_func: Some(rust_callable_destroy::<FnWrapper<F>>),
            to_string_func: Some(rust_callable_to_string_named::<F>),
            is_valid_func: Some(rust_callable_is_valid),
            ..Self::default_callable_custom_info()
        };

        Self::from_custom_info(info)
    }

    fn from_custom_info(mut info: CallableCustomInfo) -> Callable {
        // SAFETY: callable_custom_create() is a valid way of creating callables.
        unsafe {
            Callable::new_with_uninit(|type_ptr| {
                #[cfg(before_api = "4.3")]
                {
                    sys::interface_fn!(callable_custom_create)(type_ptr, ptr::addr_of_mut!(info))
                }
                #[cfg(since_api = "4.3")]
                {
                    sys::interface_fn!(callable_custom_create2)(type_ptr, ptr::addr_of_mut!(info))
                }
            })
        }
    }

    /// Creates an invalid/empty object that cannot be called.
    ///
    /// _Godot equivalent: `Callable()`_
    pub fn invalid() -> Self {
        unsafe {
            Self::new_with_uninit(|self_ptr| {
                let ctor = sys::builtin_fn!(callable_construct_default);
                ctor(self_ptr, ptr::null_mut())
            })
        }
    }

    /// Calls the method represented by this callable.
    ///
    /// Arguments passed should match the method's signature.
    ///
    /// - If called with more arguments than expected by the method, the extra arguments will be ignored and
    ///   the call continues as normal.
    /// - If called with fewer arguments than expected it will crash Godot, without triggering UB.
    /// - If called with arguments of the wrong type then an error will be printed and the call will return
    ///   `NIL`.
    /// - If called on an invalid Callable then no error is printed, and `NIL` is returned.
    ///
    /// _Godot equivalent: `callv`_
    pub fn callv(&self, arguments: &AnyArray) -> Variant {
        self.as_inner().callv(arguments)
    }

    /// Returns a copy of this Callable with one or more arguments bound, reading them from an array.
    ///
    /// _Godot equivalent: `bindv`_
    pub fn bindv(&self, arguments: &AnyArray) -> Self {
        self.as_inner().bindv(arguments)
    }

    /// Returns the name of the method represented by this callable. If the callable is a lambda function,
    /// returns the surrounding function's name.
    ///
    /// ## Known Bugs
    ///
    /// Getting the name of a lambda errors instead of returning its name, see [godot#73052].
    ///
    /// _Godot equivalent: `get_method`_
    ///
    /// [godot#73052]: https://github.com/godotengine/godot/issues/73052
    #[doc(alias = "get_method")]
    pub fn method_name(&self) -> Option<StringName> {
        let method_name = self.as_inner().get_method();
        if method_name.is_empty() {
            None
        } else {
            Some(method_name)
        }
    }

    /// Returns the object on which this callable is called.
    ///
    /// Returns `None` when this callable doesn't have any target object to call a method on (regardless of whether the method exists for that
    /// target or not). Also returns `None` if the object is dead. You can differentiate these two cases using [`object_id()`][Self::object_id].
    ///
    /// _Godot equivalent: `get_object`_
    pub fn object(&self) -> Option<Gd<classes::Object>> {
        // Increment refcount because we're getting a reference, and `InnerCallable::get_object` doesn't
        // increment the refcount.
        self.as_inner().get_object().map(|mut object| {
            <classes::Object as Bounds>::DynMemory::maybe_inc_ref(&mut object.raw);
            object
        })
    }

    /// Returns the ID of this callable's object, see also [`Gd::instance_id`].
    ///
    /// Returns `None` when this callable doesn't have any target to call a method on.
    ///
    /// If the pointed-to object is dead, the ID will still be returned. Use [`object()`][Self::object] to check for liveness.
    ///
    /// _Godot equivalent: `get_object_id`_
    pub fn object_id(&self) -> Option<InstanceId> {
        let id = self.as_inner().get_object_id();
        InstanceId::try_from_i64(id)
    }

    crate::declare_hash_u32_method! {
        /// Returns the 32-bit hash value of this callable's object.
        ///
        /// _Godot equivalent: `hash`_
    }

    /// Returns true if this callable is a custom callable.
    ///
    /// Custom callables are mainly created from bind or unbind. In GDScript, lambda functions are also
    /// custom callables.
    ///
    /// If a callable is not a custom callable, then it is considered a standard callable, this function is
    /// the opposite of [`Callable.is_standard`].
    ///
    /// _Godot equivalent: `is_custom`_
    ///
    /// [`Callable.is_standard`]: https://docs.godotengine.org/en/stable/classes/class_callable.html#class-callable-method-is-standard
    #[doc(alias = "is_standard")]
    pub fn is_custom(&self) -> bool {
        self.as_inner().is_custom()
    }

    /// Returns true if this callable has no target to call the method on.
    ///
    /// This is not the negated form of [`is_valid`][Self::is_valid], as `is_valid` will return `false` if the callable has a
    /// target but the method does not exist.
    ///
    /// _Godot equivalent: `is_null`_
    pub fn is_null(&self) -> bool {
        self.as_inner().is_null()
    }

    /// Returns true if the callable's object exists and has a valid method name assigned, or is a custom
    /// callable.
    ///
    /// _Godot equivalent: `is_valid`_
    pub fn is_valid(&self) -> bool {
        self.as_inner().is_valid()
    }

    /// Returns a copy of the callable, ignoring `args` user arguments.
    ///
    /// Despite its name, this does **not** directly undo previous `bind()` calls. See
    /// [Godot docs](https://docs.godotengine.org/en/latest/classes/class_callable.html#class-callable-method-unbind) for up-to-date semantics.
    pub fn unbind(&self, args: usize) -> Callable {
        self.as_inner().unbind(args as i64)
    }

    #[cfg(since_api = "4.3")] #[cfg_attr(published_docs, doc(cfg(since_api = "4.3")))]
    pub fn get_argument_count(&self) -> usize {
        self.as_inner().get_argument_count() as usize
    }

    /// Get number of bound arguments.
    ///
    /// Note: for Godot < 4.4, this function returns incorrect results when applied on a callable that used `unbind()`.
    /// See [#98713](https://github.com/godotengine/godot/pull/98713) for details.
    pub fn get_bound_arguments_count(&self) -> usize {
        // This does NOT fix the bug before Godot 4.4, just cap it at zero. unbind() will still erroneously decrease the bound arguments count.
        let alleged_count = self.as_inner().get_bound_arguments_count();

        alleged_count.max(0) as usize
    }

    #[doc(hidden)]
    pub fn as_inner(&self) -> inner::InnerCallable<'_> {
        inner::InnerCallable::from_outer(self)
    }
}

impl_builtin_traits! {
    for Callable {
        // Default is absent by design, to encourage explicit valid initialization.

        Clone => callable_construct_copy;
        Drop => callable_destroy;

        // Equality for custom callables depend on the equality implementation of that custom callable.
        // So we cannot implement `Eq` here and be confident equality will be total for all future custom callables.
        PartialEq => callable_operator_equal;
        // Godot does not define a less-than operator, so there is no `PartialOrd`.
        // Hash could be added, but without Eq it's not that useful; wait for actual use cases.
    }
}

// SAFETY:
// The `opaque` in `Callable` is just a pair of pointers, and requires no special initialization or cleanup
// beyond what is done in `from_opaque` and `drop`. So using `*mut Opaque` is safe.
unsafe impl GodotFfi for Callable {
    const VARIANT_TYPE: ExtVariantType = ExtVariantType::Concrete(sys::VariantType::CALLABLE);

    ffi_methods! { type sys::GDExtensionTypePtr = *mut Opaque;
        fn new_from_sys;
        fn new_with_uninit;
        fn from_arg_ptr;
        fn sys;
        fn sys_mut;
        fn move_return_ptr;
    }

    unsafe fn new_with_init(init_fn: impl FnOnce(sys::GDExtensionTypePtr)) -> Self {
        let mut result = Self::invalid();
        init_fn(result.sys_mut());
        result
    }
}

meta::impl_godot_as_self!(Callable: ByRef);

impl fmt::Debug for Callable {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let method = self.method_name();
        let object = self.object();

        f.debug_struct("Callable")
            .field("method", &method)
            .field("object", &object)
            .finish()
    }
}

impl fmt::Display for Callable {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.to_variant())
    }
}

// ----------------------------------------------------------------------------------------------------------------------------------------------
// Callbacks for custom implementations

pub use custom_callable::RustCallable;
use custom_callable::*;

mod custom_callable {
    use std::hash::Hash;

    use godot_ffi::GDObjectInstanceID;

    use super::*;
    use crate::builtin::GString;

    pub struct CallableUserdata<T> {
        pub inner: T,
    }

    impl<T> CallableUserdata<T> {
        pub fn new(inner: T) -> Self {
            Self { inner }
        }

        /// # Safety
        /// Returns an unbounded reference. `void_ptr` must be a valid pointer to a `CallableUserdata`.
        #[allow(unsafe_op_in_unsafe_fn)] // Safety preconditions forwarded 1:1.
        unsafe fn inner_from_raw<'a>(void_ptr: *mut std::ffi::c_void) -> &'a mut T {
            let ptr = void_ptr as *mut CallableUserdata<T>;
            &mut (*ptr).inner
        }
    }

    pub(crate) struct FnWrapper<F> {
        pub(super) rust_function: F,

        /// Stored as `Cow<'static, str>` to optimize the hot path (callable invocation, needing call context), vs. cold path (`to_string`).
        pub(super) name: CowStr,

        /// Lazy cache for `GString` representation of name. Uses `OnceLock` (not `OnceCell`) to support `from_sync_fn()`, which requires
        /// `Sync`. Could be split into separate single/multi-threaded locks, but atomic overhead of `OnceLock` is good enough for now.
        pub(super) name_cached: OnceLock<GString>,

        /// `None` if the callable is multi-threaded ([`Callable::from_sync_fn`]).       
        #[cfg(safeguards_balanced)] #[cfg_attr(published_docs, doc(cfg(safeguards_balanced)))]
        pub(super) thread_id: Option<std::thread::ThreadId>,

        /// `None` if callable is not linked with any object.
        pub(super) linked_object_id: Option<InstanceId>,
    }

    impl<F> FnWrapper<F> {
        pub(crate) fn linked_object_id(&self) -> GDObjectInstanceID {
            self.linked_object_id.map(InstanceId::to_u64).unwrap_or(0)
        }
    }

    /// Represents a custom callable object defined in Rust.
    ///
    /// This trait has a single method, `invoke`, which is called upon invocation.
    ///
    /// Since callables can be invoked from anywhere, they must be self-contained (`'static`) and thread-safe (`Send + Sync`).
    /// They also should implement `Display` for the Godot string representation.
    /// Furthermore, `Hash` is required for usage as a key in a `Dictionary` and for checking signal connections –
    /// Godot considers a custom callable to be connected to a signal if a callable with the same hash is already connected to that signal.
    /// Finally, `PartialEq` is necessary for equality checks.
    // TODO(v0.6): possibly replace this with a builder approach. if not, add object_id().
    pub trait RustCallable: 'static + PartialEq + Hash + fmt::Display + Send + Sync {
        /// Invokes the callable with the given arguments as `Variant` references.
        ///
        /// Errors are supported via panics.
        fn invoke(&mut self, args: &[&Variant]) -> Variant;

        /// Returns the name of this callable for error messages and display.
        ///
        /// By default, the `Display` impl is used. You can override this for a cached/constant name.
        fn callable_name(&self) -> CowStr {
            CowStr::Owned(self.to_string())
        }

        /// Returns whether the callable is considered valid.
        ///
        /// True by default.
        ///
        /// If this Callable stores an object, this method should return whether that object is alive.
        fn is_valid(&self) -> bool {
            true
        }
    }

    pub unsafe extern "C" fn rust_callable_call_custom<C: RustCallable>(
        callable_userdata: *mut std::ffi::c_void,
        p_args: *const sys::GDExtensionConstVariantPtr,
        p_argument_count: sys::GDExtensionInt,
        r_return: sys::GDExtensionVariantPtr,
        r_error: *mut sys::GDExtensionCallError,
    ) {
        // SAFETY (whole function):
        // all pointers are valid per Godot GDExtension calling convention; callable_userdata set during construction.

        let arg_refs: &[&Variant] =
            unsafe { Variant::borrow_ref_slice(p_args, p_argument_count as usize) };

        let name = {
            let c: &C = unsafe { CallableUserdata::inner_from_raw(callable_userdata) };
            c.callable_name()
        };
        let ctx = meta::CallContext::custom_callable(name.as_ref());

        let err = unsafe { &mut *r_error };
        crate::private::handle_fallible_varcall(&ctx, err, move || {
            // Re-borrow inside closure so C doesn't have to be UnwindSafe.
            let c: &mut C = unsafe { CallableUserdata::inner_from_raw(callable_userdata) };
            let result = c.invoke(arg_refs);

            unsafe { meta::varcall_return_checked(Ok(result), r_return, r_error) };
            Ok(())
        });
    }

    pub unsafe extern "C" fn rust_callable_call_fn<F, R>(
        callable_userdata: *mut std::ffi::c_void,
        p_args: *const sys::GDExtensionConstVariantPtr,
        p_argument_count: sys::GDExtensionInt,
        r_return: sys::GDExtensionVariantPtr,
        r_error: *mut sys::GDExtensionCallError,
    ) where
        F: FnMut(&[&Variant]) -> R,
        R: ToGodot,
    {
        // SAFETY (whole function):
        // all pointers are valid per Godot GDExtension calling convention; callable_userdata set during construction.

        let arg_refs: &[&Variant] =
            unsafe { Variant::borrow_ref_slice(p_args, p_argument_count as usize) };

        let w: &FnWrapper<F> = unsafe { CallableUserdata::inner_from_raw(callable_userdata) };
        let ctx = meta::CallContext::custom_callable(&w.name);

        let err = unsafe { &mut *r_error };
        crate::private::handle_fallible_varcall(&ctx, err, move || {
            // Re-borrow inside closure so FnMut doesn't have to be UnwindSafe.
            let w: &mut FnWrapper<F> =
                unsafe { CallableUserdata::inner_from_raw(callable_userdata) };

            // NOTE: this panic is currently not propagated to the caller, but results in an error message and Nil return.
            // See comments in itest callable_call() for details.
            sys::balanced_assert!(
                w.thread_id.is_none() || w.thread_id == Some(std::thread::current().id()),
                "Callable '{}' created with from_fn() must be called from the same thread it was created in.\n\
                If you need to call it from any thread, use from_sync_fn() instead (requires `experimental-threads` feature).",
                w.name
            );

            let result = (w.rust_function)(arg_refs).to_variant();
            unsafe { meta::varcall_return_checked(Ok(result), r_return, r_error) };
            Ok(())
        });
    }

    /// `T` here is entire object stored in [`CallableUserdata`], not just the actual [`RustCallable`] or closure instance.
    pub unsafe extern "C" fn rust_callable_destroy<T>(callable_userdata: *mut std::ffi::c_void) {
        let rust_ptr = callable_userdata as *mut CallableUserdata<T>;

        // SAFETY: pointer was extracted using Box::into_raw().
        let _drop = unsafe { Box::from_raw(rust_ptr) };
    }

    pub unsafe extern "C" fn rust_callable_hash<C: RustCallable + Hash>(
        callable_userdata: *mut std::ffi::c_void,
    ) -> u32 {
        let c: &C = unsafe { CallableUserdata::inner_from_raw(callable_userdata) };

        // Just cut off top bits, not best-possible hash.
        sys::hash_value(c) as u32
    }

    #[allow(unsafe_op_in_unsafe_fn)] // Pointer validity asserted by Godot.
    pub unsafe extern "C" fn rust_callable_equal<C: RustCallable + PartialEq>(
        callable_userdata_a: *mut std::ffi::c_void,
        callable_userdata_b: *mut std::ffi::c_void,
    ) -> sys::GDExtensionBool {
        let a: &C = CallableUserdata::inner_from_raw(callable_userdata_a);
        let b: &C = CallableUserdata::inner_from_raw(callable_userdata_b);

        sys::conv::bool_to_sys(a == b)
    }

    #[allow(unsafe_op_in_unsafe_fn)] // Pointer validity asserted by Godot.
    pub unsafe extern "C" fn rust_callable_to_string_display<C: RustCallable + fmt::Display>(
        callable_userdata: *mut std::ffi::c_void,
        r_is_valid: *mut sys::GDExtensionBool,
        r_out: sys::GDExtensionStringPtr,
    ) {
        let c: &C = CallableUserdata::inner_from_raw(callable_userdata);
        let name = c.callable_name();
        let s = GString::from(name.as_ref());

        s.move_into_string_ptr(r_out);
        *r_is_valid = sys::conv::SYS_TRUE;
    }

    #[allow(unsafe_op_in_unsafe_fn)] // Pointer validity asserted by Godot.
    pub unsafe extern "C" fn rust_callable_to_string_named<F>(
        callable_userdata: *mut std::ffi::c_void,
        r_is_valid: *mut sys::GDExtensionBool,
        r_out: sys::GDExtensionStringPtr,
    ) {
        let w: &FnWrapper<F> = CallableUserdata::inner_from_raw(callable_userdata);

        // Use cached GString if available, otherwise create and cache it (rare cold path).
        let gstring = w.name_cached.get_or_init(|| GString::from(w.name.as_ref()));
        gstring.clone().move_into_string_ptr(r_out);
        *r_is_valid = sys::conv::SYS_TRUE;
    }

    // Necessary to avoid false invalidity for custom callables with default callback.
    pub unsafe extern "C" fn rust_callable_is_valid_custom<C: RustCallable>(
        callable_userdata: *mut std::ffi::c_void,
    ) -> sys::GDExtensionBool {
        let c: &C = unsafe { CallableUserdata::inner_from_raw(callable_userdata) };
        let valid = c.is_valid();

        sys::conv::bool_to_sys(valid)
    }

    // Implementing this is necessary because the default (nullptr) may consider custom callables as invalid in some cases.
    pub unsafe extern "C" fn rust_callable_is_valid(
        _callable_userdata: *mut std::ffi::c_void,
    ) -> sys::GDExtensionBool {
        // If we had an object (CallableCustomInfo::object_id field), we could check whether that object is alive.
        // But since we just take a Rust function/closure, not knowing what happens inside, we assume always valid.
        sys::conv::SYS_TRUE
    }
}