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
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
/*
 * 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 crate::builtin::{Callable, GString, NodePath, Signal, StringName, Variant};
use crate::meta::sealed::Sealed;
use crate::meta::traits::{Element, GodotFfiVariant, GodotNullableType, PackedElement};
use crate::meta::{CowArg, EngineToGodot, FfiArg, GodotType, ObjectArg, ToGodot};
use crate::obj::{DynGd, Gd, GodotClass, Inherits};

/// Implicit conversions for arguments passed to Godot APIs.
///
/// An `impl AsArg<T>` parameter allows values to be passed which can be represented in the target type `T`. Note that unlike `From<T>`,
/// this trait is implemented more conservatively.
///
/// As a result, `AsArg<T>` is currently only implemented for certain argument types:
/// - `T` for **by-value** built-ins: `i32`, `bool`, `Vector3`, `Transform2D`...
///   - These all implement `ToGodot<Pass = ByValue>` and typically also `Copy`.
/// - `&T` for **by-ref** built-ins: `GString`, `Array`, `Dictionary`, `PackedArray`, `Variant`...
///   - These all implement `ToGodot<Pass = ByRef>`.
/// - `&str`, `&String` additionally for string types `GString`, `StringName`, `NodePath`, see [String arguments](#string-arguments).
/// - `&Gd`, `Option<&Gd>` for objects, see [Object arguments](#object-arguments).
///
/// # Owned values vs. references
/// Implicitly converting from `T` for **by-ref** built-ins is explicitly not supported, i.e. you need to pass `&variant` instead of `variant`.
/// This emphasizes that there is no need to consume the object, thus discourages unnecessary cloning. Similarly, you cannot pass by-value
/// types like `i32` by reference.
///
/// Sometimes, you need exactly that for generic programming though: consistently pass `T` or `&T`. For this purpose, the global functions
/// [`owned_into_arg()`] and [`ref_to_arg()`] are provided.
///
/// # Using the trait
/// `AsArg` is meant to be used from the function call site, not the declaration site. If you declare a parameter as `impl AsArg<...>` yourself,
/// you can only forward it as-is to a Godot API -- there are no stable APIs to access the inner object yet.
///
/// The blanket implementations of `AsArg` for `T` (in case of `Pass = ByValue`) and `&T` (`Pass = ByRef`) should readily enable most use
/// cases, as long as your type already supports `ToGodot`. In the majority of cases, you'll simply use by-value passing, e.g. for enums.
///
/// # String arguments
/// Godot has three string types: [`GString`], [`StringName`] and [`NodePath`]. Conversions between those three, as well as between `String` and
/// them, is generally expensive because of allocations, re-encoding, validations, hashing, etc. While this doesn't matter for a few strings
/// passed to engine APIs, it can become a problematic when passing long strings in a hot loop.
///
/// In the case of strings, we allow implicit conversion from Rust types `&str`, `&String` and `&'static CStr` (`StringName` only).
/// While these conversions are not free, those are either explicit because a string literal is used, or they are unsurprising, because Godot
/// cannot deal with raw Rust types. On the other hand, `GString` and `StringName` are sometimes used almost interchangeably (example:
/// [`Node::set_name`](crate::classes::Node::set_name) takes `GString` but [`Node::get_name`](crate::classes::Node::get_name) returns `StringName`).
///
/// If you want to convert between Godot's string types for the sake of argument passing, use the `From` conversions, e.g.
/// `GString::from(&string_name)`.
///
/// # Object arguments
/// This section treats `AsArg<Gd<*>>`. The trait is implemented for **shared references** in multiple ways:
/// - [`&Gd<T>`][crate::obj::Gd]  to pass objects. Subclasses of `T` are explicitly supported.
/// - [`Option<&Gd<T>>`][Option], to pass optional objects. `None` is mapped to a null argument.
/// - [`Gd::null_arg()`], to pass `null` arguments without using `Option`.
///
/// The following table lists the possible argument types and how you can pass them. `Gd` is short for `Gd<T>`.
///
/// | Type              | Closest accepted type | How to transform |
/// |-------------------|-----------------------|------------------|
/// | `Gd`              | `&Gd`                 | `&arg`           |
/// | `&Gd`             | `&Gd`                 | `arg`            |
/// | `&mut Gd`         | `&Gd`                 | `&*arg`          |
/// | `Option<Gd>`      | `Option<&Gd>`         | `arg.as_ref()`   |
/// | `Option<&Gd>`     | `Option<&Gd>`         | `arg`            |
/// | `Option<&mut Gd>` | `Option<&Gd>`         | `arg.as_deref()` |
/// | (null literal)    |                       | `Gd::null_arg()` |
///
/// ## Nullability
/// <div class="warning">
/// The GDExtension API does not inform about nullability of its function parameters. It is up to you to verify that the arguments you pass
/// are only null when this is allowed. Doing this wrong should be safe, but can lead to the function call failing.
/// </div>
#[diagnostic::on_unimplemented(
    message = "Argument of type `{Self}` cannot be passed to an `impl AsArg<{T}>` parameter",
    note = "if you pass by value, consider borrowing instead.",
    note = "GString/StringName/NodePath aren't implicitly convertible for performance reasons; use `From` conversions.",
    note = "see also `AsArg` docs: https://godot-rust.github.io/docs/gdext/master/godot/meta/trait.AsArg.html"
)]
pub trait AsArg<T: ToGodot>
where
    Self: Sized,
{
    // The usage of the CowArg return type introduces a small runtime penalty for values that implement Copy. Currently, the usage
    // ergonomics out weigh the runtime cost. Using the CowArg allows us to create a blanket implementation of the trait for all types that
    // implement ToGodot.
    #[doc(hidden)]
    fn into_arg<'arg>(self) -> CowArg<'arg, T>
    where
        Self: 'arg;

    /// FFI-optimized argument conversion that may use `FfiObject` when beneficial.
    ///
    /// Defaults to calling `into_arg()` and wrapping in `FfiArg::Cow()`, which always works, but might be an `Owned` for a conservative
    /// approach (e.g. object upcast).
    #[doc(hidden)]
    fn into_ffi_arg<'arg>(self) -> FfiArg<'arg, T>
    where
        Self: 'arg,
    {
        FfiArg::Cow(self.into_arg())
    }
}

impl<T> AsArg<T> for &T
where
    T: ToGodot<Pass = ByRef>,
{
    fn into_arg<'arg>(self) -> CowArg<'arg, T>
    where
        Self: 'arg,
    {
        CowArg::Borrowed(self)
    }
}

// Variant has `Pass = ByVariant` (not ByRef), so it's not covered by the ByRef blanket above.
impl AsArg<Variant> for &Variant {
    fn into_arg<'arg>(self) -> CowArg<'arg, Variant>
    where
        Self: 'arg,
    {
        CowArg::Borrowed(self)
    }
}

impl<T> AsArg<T> for T
where
    T: ToGodot<Pass = ByValue> + Sized, // Sized may rule out some coherence issues.
{
    fn into_arg<'arg>(self) -> CowArg<'arg, T>
    where
        Self: 'arg,
    {
        CowArg::Owned(self)
    }
}

// ----------------------------------------------------------------------------------------------------------------------------------------------
// Object (Gd + DynGd) impls

// Convert `Gd` -> `Gd` (with upcast).
impl<T, Base> AsArg<Gd<Base>> for &Gd<T>
where
    T: Inherits<Base>,
    Base: GodotClass,
{
    //noinspection RsConstantConditionIf - false positive in IDE for `T::IS_SAME_CLASS`.
    fn into_arg<'arg>(self) -> CowArg<'arg, Gd<Base>>
    where
        Self: 'arg,
    {
        if T::IS_SAME_CLASS {
            // SAFETY: T == Base, so &Gd<T> can be treated as &Gd<Base>.
            let gd_ref = unsafe { std::mem::transmute::<&Gd<T>, &Gd<Base>>(self) };
            CowArg::Borrowed(gd_ref)
        } else {
            // Different types: clone and upcast. May incur ref-count increment for RefCounted objects, but the common path
            // of FFI passing is already optimized.
            CowArg::Owned(self.clone().upcast())
        }
    }

    fn into_ffi_arg<'arg>(self) -> FfiArg<'arg, Gd<Base>>
    where
        Self: 'arg,
    {
        let arg = ObjectArg::from_gd(self);
        FfiArg::FfiObject(arg)
    }
}

/// Convert `DynGd` -> `DynGd` (with upcast).
impl<T, D, Base> AsArg<DynGd<Base, D>> for &DynGd<T, D>
where
    T: Inherits<Base>,
    D: ?Sized,
    Base: GodotClass,
{
    //noinspection RsConstantConditionIf - false positive in IDE for `T::IS_SAME_CLASS`.
    fn into_arg<'arg>(self) -> CowArg<'arg, DynGd<Base, D>>
    where
        Self: 'arg,
    {
        if T::IS_SAME_CLASS {
            // SAFETY: T == Base, so &DynGd<T, D> can be treated as &DynGd<Base, D>.
            let gd_ref = unsafe { std::mem::transmute::<&DynGd<T, D>, &DynGd<Base, D>>(self) };
            CowArg::Borrowed(gd_ref)
        } else {
            // Different types: clone and upcast. May incur ref-count increment for RefCounted objects, but the common path
            // of FFI passing is already optimized.
            CowArg::Owned(self.clone().upcast())
        }
    }

    fn into_ffi_arg<'arg>(self) -> FfiArg<'arg, DynGd<Base, D>>
    where
        Self: 'arg,
    {
        let arg = ObjectArg::from_gd(self);
        FfiArg::FfiObject(arg)
    }
}

/// Convert `DynGd` -> `Gd` (with upcast).
impl<T, D, Base> AsArg<Gd<Base>> for &DynGd<T, D>
where
    T: Inherits<Base>,
    D: ?Sized,
    Base: GodotClass,
{
    fn into_arg<'arg>(self) -> CowArg<'arg, Gd<Base>>
    where
        Self: 'arg,
    {
        let gd_ref: &Gd<T> = self; // DynGd -> Gd deref.
        AsArg::into_arg(gd_ref)
    }

    fn into_ffi_arg<'arg>(self) -> FfiArg<'arg, Gd<Base>>
    where
        Self: 'arg,
    {
        let gd_ref: &Gd<T> = self; // DynGd -> Gd deref.
        AsArg::into_ffi_arg(gd_ref)
    }
}

// ----------------------------------------------------------------------------------------------------------------------------------------------
// Null arguments

/// Private struct for passing null arguments to optional object parameters.
///
/// This struct implements `AsArg` for both `Option<Gd<T>>` and `Option<DynGd<T, D>>`, allowing [`Gd::null_arg()`] and [`DynGd::null_arg()`]
/// to share implementation.
///
/// Not public, as `impl AsArg<...>` is used by `null_arg()` methods.
pub(crate) struct NullArg<T>(pub std::marker::PhantomData<*mut T>);

impl<T> AsArg<Option<Gd<T>>> for NullArg<T>
where
    T: GodotClass,
{
    fn into_arg<'arg>(self) -> CowArg<'arg, Option<Gd<T>>>
    where
        Self: 'arg,
    {
        CowArg::Owned(None)
    }
}

impl<T, D> AsArg<Option<DynGd<T, D>>> for NullArg<T>
where
    T: GodotClass,
    D: ?Sized + 'static,
{
    fn into_arg<'arg>(self) -> CowArg<'arg, Option<DynGd<T, D>>>
    where
        Self: 'arg,
    {
        CowArg::Owned(None)
    }
}

// ----------------------------------------------------------------------------------------------------------------------------------------------
// Optional object (Gd + DynGd) impls

/// Convert `&Gd` -> `Option<Gd>` (with upcast).
impl<T, Base> AsArg<Option<Gd<Base>>> for &Gd<T>
where
    T: Inherits<Base>,
    Base: GodotClass,
{
    fn into_arg<'arg>(self) -> CowArg<'arg, Option<Gd<Base>>>
    where
        Self: 'arg,
    {
        // Upcasting to an owned value Gd<Base> requires cloning. Optimized path in into_ffi_arg().
        CowArg::Owned(Some(self.clone().upcast::<Base>()))
    }

    fn into_ffi_arg<'arg>(self) -> FfiArg<'arg, Option<Gd<Base>>>
    where
        Self: 'arg,
    {
        let arg = ObjectArg::from_gd(self);
        FfiArg::FfiObject(arg)
    }
}

/// Convert `Option<&Gd>` -> `Option<Gd>` (with upcast).
impl<T, Base> AsArg<Option<Gd<Base>>> for Option<&Gd<T>>
where
    T: Inherits<Base>,
    Base: GodotClass,
{
    fn into_arg<'arg>(self) -> CowArg<'arg, Option<Gd<Base>>>
    where
        Self: 'arg,
    {
        // Upcasting to an owned value Gd<Base> requires cloning. Optimized path in into_ffi_arg().
        match self {
            Some(gd_ref) => AsArg::into_arg(gd_ref),
            None => CowArg::Owned(None),
        }
    }

    fn into_ffi_arg<'arg>(self) -> FfiArg<'arg, Option<Gd<Base>>>
    where
        Self: 'arg,
    {
        let arg = ObjectArg::from_option_gd(self);
        FfiArg::FfiObject(arg)
    }
}

/// Convert `&DynGd` -> `Option<DynGd>` (with upcast).
impl<T, D, Base> AsArg<Option<DynGd<Base, D>>> for &DynGd<T, D>
where
    T: Inherits<Base>,
    D: ?Sized,
    Base: GodotClass,
{
    fn into_arg<'arg>(self) -> CowArg<'arg, Option<DynGd<Base, D>>>
    where
        Self: 'arg,
    {
        // Upcasting to an owned value DynGd<Base, D> requires cloning. Optimized path in into_ffi_arg().
        CowArg::Owned(Some(self.clone().upcast()))
    }

    fn into_ffi_arg<'arg>(self) -> FfiArg<'arg, Option<DynGd<Base, D>>>
    where
        Self: 'arg,
    {
        let arg = ObjectArg::from_gd(self);
        FfiArg::FfiObject(arg)
    }
}

/// Convert `&DynGd` -> `Option<Gd>` (with upcast).
impl<T, D, Base> AsArg<Option<Gd<Base>>> for &DynGd<T, D>
where
    T: Inherits<Base>,
    D: ?Sized,
    Base: GodotClass,
{
    fn into_arg<'arg>(self) -> CowArg<'arg, Option<Gd<Base>>>
    where
        Self: 'arg,
    {
        let gd_ref: &Gd<T> = self; // DynGd -> Gd deref.
        AsArg::into_arg(gd_ref)
    }

    fn into_ffi_arg<'arg>(self) -> FfiArg<'arg, Option<Gd<Base>>>
    where
        Self: 'arg,
    {
        let gd_ref: &Gd<T> = self; // DynGd -> Gd deref.
        AsArg::into_ffi_arg(gd_ref)
    }
}

/// Convert `Option<&DynGd>` -> `Option<DynGd>` (with upcast).
impl<T, D, Base> AsArg<Option<DynGd<Base, D>>> for Option<&DynGd<T, D>>
where
    T: Inherits<Base>,
    D: ?Sized,
    Base: GodotClass,
{
    fn into_arg<'arg>(self) -> CowArg<'arg, Option<DynGd<Base, D>>>
    where
        Self: 'arg,
    {
        // Upcasting to an owned value Gd<Base> requires cloning. Optimized path in into_ffi_arg().
        match self {
            Some(gd_ref) => AsArg::into_arg(gd_ref),
            None => CowArg::Owned(None),
        }
    }

    fn into_ffi_arg<'arg>(self) -> FfiArg<'arg, Option<DynGd<Base, D>>>
    where
        Self: 'arg,
    {
        let option_gd: Option<&Gd<T>> = self.map(|v| &**v); // as_deref() not working.
        let arg = ObjectArg::from_option_gd(option_gd);
        FfiArg::FfiObject(arg)
    }
}

// ----------------------------------------------------------------------------------------------------------------------------------------------
// Public helper functions (T|&T -> AsArg)

/// Generic abstraction over `T` owned values that should be passed as `AsArg<T>`.
///
/// Useful for generic programming: you have owned values, and want the argument conversion to benefit from moving whenever possible.
/// You don't care if the value can truly be moved efficiently, since you don't need the value at the call site anymore.
///
/// Note that the pattern `owned_into_arg(value.clone())` is inefficient -- instead, use [`ref_to_arg(&value)`][ref_to_arg].
///
/// # Example
/// ```
/// use godot::prelude::*;
/// use godot::meta::{Element, owned_into_arg};
///
/// // Creates random values, e.g. for fuzzing, property-based testing, etc.
/// // Assume global state for simplicity.
/// trait Generator {
///    fn next() -> Self;
/// }
///
/// fn fill_randomly<T>(arr: &mut Array<T>, count: usize)
/// where
///     T: Element + ToGodot + Generator,
/// {
///     for _ in 0..count {
///         let value = T::next();
///         arr.push(owned_into_arg(value));
///     }
/// }
/// ```
pub fn owned_into_arg<'arg, T>(owned_val: T) -> impl AsArg<T> + 'arg
where
    T: ToGodot + 'arg,
{
    CowArg::Owned(owned_val)
}

/// Generic abstraction over `&T` references that should be passed as `AsArg<T>`.
///
/// Useful for generic programming: you have references, and want the argument conversion to benefit from borrowing whenever possible.
///
/// If you no longer need the value at the call site, consider using [`owned_into_arg(value)`][owned_into_arg] instead.
///
/// # Example
/// ```
/// use godot::prelude::*;
/// use godot::meta::{Element, ref_to_arg};
///
/// // Could use `impl AsArg<T>` and forward it, but let's demonstrate `&T` here.
/// fn log_and_push<T>(arr: &mut Array<T>, value: &T)
/// where
///     T: Element + ToGodot + std::fmt::Debug,
/// {
///     println!("Add value: {value:?}");
///     arr.push(ref_to_arg(value));
/// }
/// ```
pub fn ref_to_arg<'r, T>(ref_val: &'r T) -> impl AsArg<T> + 'r
where
    T: ToGodot + 'r,
{
    CowArg::Borrowed(ref_val)
}

// ----------------------------------------------------------------------------------------------------------------------------------------------
// Internal helper macros (AsArg -> &T|T)

/// Converts `impl AsArg<T>` into a locally valid `&T`.
///
/// This cannot be done via function, since an intermediate variable (the Cow) is needed, which would go out of scope
/// once the reference is returned. Could use more fancy syntax like `arg_into_ref! { let path = ref; }` or `let path = arg_into_ref!(path)`,
/// but still isn't obvious enough to avoid doc lookup and might give a wrong idea about the scope. So being more exotic is a feature.
#[macro_export]
#[doc(hidden)] // Doesn't work at re-export.
macro_rules! arg_into_ref {
    ($arg_variable:ident) => {
        // Non-generic version allows type inference. Only applicable for CowArg types.
        let $arg_variable = $arg_variable.into_arg();
        let $arg_variable = $arg_variable.cow_as_ref();
    };
    ($arg_variable:ident: $T:ty) => {
        let $arg_variable = $arg_variable.into_arg();
        let $arg_variable: &$T = $arg_variable.cow_as_ref();
    };
}

/// Converts `impl AsArg<T>` into a locally valid `T`.
///
/// A macro for consistency with [`arg_into_ref`][crate::arg_into_ref].
#[macro_export]
#[doc(hidden)] // Doesn't work at re-export.
macro_rules! arg_into_owned {
    ($arg_variable:ident) => {
        // Non-generic version allows type inference. Only applicable for CowArg types.
        let $arg_variable = $arg_variable.into_arg();
        let $arg_variable = $arg_variable.cow_into_owned();
    };
    (infer $arg_variable:ident) => {
        let $arg_variable = $arg_variable.into_arg();
        let $arg_variable = $arg_variable.cow_into_owned();
    };
}

// ----------------------------------------------------------------------------------------------------------------------------------------------
// CowArg

/// `CowArg` can itself be passed as an argument (internal only).
///
/// Allows forwarding of `impl AsArg<T>` arguments to both another signature of `impl AsArg<T>` and signature of `T` for `Copy` types.
/// This is necessary for packed array dispatching to different "inner" backend signatures.
impl<T> AsArg<T> for CowArg<'_, T>
where
    for<'r> T: ToGodot,
{
    fn into_arg<'arg>(self) -> CowArg<'arg, T>
    where
        Self: 'arg,
    {
        self
    }
}

// ----------------------------------------------------------------------------------------------------------------------------------------------
// GString

macro_rules! impl_asarg_string {
    ($Target:ty) => {
        impl AsArg<$Target> for &str {
            fn into_arg<'arg>(self) -> CowArg<'arg, $Target> {
                CowArg::Owned(<$Target>::from(self))
            }
        }
        impl AsArg<$Target> for &String {
            fn into_arg<'arg>(self) -> CowArg<'arg, $Target> {
                CowArg::Owned(<$Target>::from(self.as_str()))
            }
        }
    };
}

impl_asarg_string!(GString);
impl_asarg_string!(StringName);
impl_asarg_string!(NodePath);

// ----------------------------------------------------------------------------------------------------------------------------------------------
// Argument passing (mutually exclusive by-val or by-ref).

/// Determines whether arguments are passed by value or by reference to Godot.
///
/// See [`ToGodot::Pass`].
pub trait ArgPassing: Sealed {
    /// Return type: `T` or `&'r T`.
    type Output<'r, T: 'r>
    where
        Self: 'r;

    /// FFI argument type: `T::Ffi` or `T::ToFfi<'f>`.
    #[doc(hidden)]
    type FfiOutput<'f, T>: GodotFfiVariant
    where
        T: GodotType + 'f;

    /// Convert to owned `T::Via` (cloning if necessary).
    #[doc(hidden)]
    fn ref_to_owned_via<T>(value: &T) -> T::Via
    where
        T: EngineToGodot<Pass = Self>;

    /// Convert to FFI repr in the most efficient way (move or borrow).
    #[doc(hidden)]
    fn ref_to_ffi<T>(value: &T) -> Self::FfiOutput<'_, T::Via>
    where
        T: EngineToGodot<Pass = Self>;

    /// Convert to `Variant` in the most efficient way (move or borrow).
    #[doc(hidden)]
    fn ref_to_variant<T>(value: &T) -> Variant
    where
        T: EngineToGodot<Pass = Self>,
    {
        let ffi_result = Self::ref_to_ffi(value);
        GodotFfiVariant::ffi_to_variant(&ffi_result)
    }
}

/// Pass arguments to Godot by value.
///
/// See [`ToGodot::Pass`].
pub enum ByValue {}
impl Sealed for ByValue {}
impl ArgPassing for ByValue {
    type Output<'r, T: 'r> = T;

    type FfiOutput<'a, T>
        = T::Ffi
    where
        T: GodotType + 'a;

    fn ref_to_owned_via<T>(value: &T) -> T::Via
    where
        T: EngineToGodot<Pass = Self>,
    {
        value.engine_to_godot()
    }

    fn ref_to_ffi<T>(value: &T) -> Self::FfiOutput<'_, T::Via>
    where
        T: EngineToGodot<Pass = Self>,
    {
        // For ByValue: engine_to_godot() returns owned T::Via, move directly to FFI.
        GodotType::into_ffi(value.engine_to_godot())
    }
}

/// Pass arguments to Godot by reference.
///
/// See [`ToGodot::Pass`].
pub enum ByRef {}
impl Sealed for ByRef {}
impl ArgPassing for ByRef {
    type Output<'r, T: 'r> = &'r T;

    type FfiOutput<'f, T>
        = T::ToFfi<'f>
    where
        T: GodotType + 'f;

    fn ref_to_owned_via<T>(value: &T) -> T::Via
    where
        T: EngineToGodot<Pass = Self>,
    {
        // For ByRef types, clone the reference to get owned value.
        value.engine_to_godot().clone()
    }

    fn ref_to_ffi<T>(value: &T) -> <T::Via as GodotType>::ToFfi<'_>
    where
        T: EngineToGodot<Pass = Self>,
    {
        // Use by-ref conversion if possible, avoiding unnecessary clones when passing to FFI.
        GodotType::to_ffi(value.engine_to_godot())
    }
}

/// Pass `Variant` arguments to Godot by reference.
///
/// This is semantically identical to [`ByRef`], but exists as a separate type so that `Variant` has its own `Pass` type.
/// This decoupling enables blanket `AsArg<Variant>` impls for all `ByRef` types without coherence conflicts at `T = Variant`.
///
/// See [`ToGodot::Pass`].
pub enum ByVariant {}
impl Sealed for ByVariant {}
impl ArgPassing for ByVariant {
    type Output<'r, T: 'r> = &'r T;

    type FfiOutput<'f, T>
        = T::ToFfi<'f>
    where
        T: GodotType + 'f;

    fn ref_to_owned_via<T>(value: &T) -> T::Via
    where
        T: EngineToGodot<Pass = Self>,
    {
        value.engine_to_godot().clone()
    }

    fn ref_to_ffi<T>(value: &T) -> <T::Via as GodotType>::ToFfi<'_>
    where
        T: EngineToGodot<Pass = Self>,
    {
        GodotType::to_ffi(value.engine_to_godot())
    }
}

/// Pass arguments to Godot by object pointer (for objects only).
///
/// Currently distinct from [`ByRef`] to not interfere with the blanket impl for `&T` for all `ByRef` types. Semantics are largely the same.
///
/// See [`ToGodot::Pass`].
pub enum ByObject {}
impl Sealed for ByObject {}
impl ArgPassing for ByObject {
    type Output<'r, T: 'r> = &'r T;

    type FfiOutput<'f, T>
        = ObjectArg<'f>
    where
        T: GodotType + 'f;

    fn ref_to_owned_via<T>(value: &T) -> T::Via
    where
        T: EngineToGodot<Pass = Self>,
    {
        // For ByObject types, do like ByRef: clone the reference to get owned value.
        value.engine_to_godot().clone()
    }

    fn ref_to_ffi<T>(value: &T) -> ObjectArg<'_>
    where
        T: EngineToGodot<Pass = Self>,
    {
        let obj_ref: &T::Via = value.engine_to_godot(); // implements GodotType.
        obj_ref.as_object_arg()
    }
}

/// Pass optional arguments by returning `Option<&T::Via>`, allowing delegation to underlying type's strategy.
///
/// This enables `Option<T>` to benefit from the underlying type's efficient passing without cloning. [`ByRef`] doesn't support this because it
/// would transform `Option<T>` to `&Option<T>`; however, we need `Option<&T>` instead.
///
/// See [`ToGodot::Pass`].
pub enum ByOption<Via> {
    // Uses `Via` generic type to work around the near-impossibility of Output<'r, T> pointing to a metafunction that transforms Option<T> to
    // Option<&'r T>. Such a metafunction cannot be implemented via trait (overlapping impls cause coherence issues), and we would need to
    // pollute also the other `By*` types by anything. Using a generic parameter on the trait rather than the associated type avoids that.
    _Phantom(std::marker::PhantomData<Via>),
}
impl<Via> Sealed for ByOption<Via> {}
impl<Via> ArgPassing for ByOption<Via>
where
    Via: GodotNullableType,
{
    type Output<'r, T: 'r>
        = Option<&'r Via>
    where
        Self: 'r;

    type FfiOutput<'f, T>
        = <Via as GodotType>::ToFfi<'f>
    where
        T: GodotType + 'f;

    // value:  &Option<U>
    // return: T::Via = Option<U::Via>
    fn ref_to_owned_via<T>(value: &T) -> T::Via
    where
        T: EngineToGodot<Pass = Self>,
    {
        value.engine_to_godot_owned()
    }

    fn ref_to_ffi<T>(value: &T) -> Self::FfiOutput<'_, T::Via>
    where
        T: EngineToGodot<Pass = Self>,
    {
        // Reuse pattern from impl GodotType for Option<T>:
        // Convert Option<&Via> to Option<Via::ToFfi> and then flatten to Via::ToFfi with null handling.
        value
            .engine_to_godot()
            .map(|via_ref| via_ref.to_ffi())
            .unwrap_or_else(Via::ffi_null_ref)
    }
}

#[doc(hidden)] // Easier for internal use.
pub type ToArg<'r, Via, Pass> = <Pass as ArgPassing>::Output<'r, Via>;

/// This type exists only as a place to add doctests for `AsArg`, which do not need to be in the public documentation.
///
/// `AsArg<Option<Gd<UserClass>>` can be used with signals correctly:
///
/// ```no_run
/// # use godot::prelude::*;
/// #[derive(GodotClass)]
/// #[class(init, base = Node)]
/// struct MyClass {
///     base: Base<Node>
/// }
///
/// #[godot_api]
/// impl MyClass {
///     #[signal]
///     fn signal_optional_user_obj(arg1: Option<Gd<MyClass>>);
///
///     fn foo(&mut self) {
///         let arg = self.to_gd();
///         // Directly:
///         self.signals().signal_optional_user_obj().emit(&arg);
///         // Via Some:
///         self.signals().signal_optional_user_obj().emit(Some(&arg));
///         // With None (Note: Gd::null_arg() is restricted to engine classes):
///         self.signals().signal_optional_user_obj().emit(None::<Gd<MyClass>>.as_ref());
///     }
/// }
/// ```
///
#[allow(dead_code)]
struct PhantomAsArgDoctests;

// ----------------------------------------------------------------------------------------------------------------------------------------------
// AsArg<Variant> impls — replaces former AsVArg/DisjointVArg machinery

// Blanket: ByValue types -> Variant (i32, f64, bool, Vector2, Color, &str, String, user enums, etc.).
impl<T> AsArg<Variant> for T
where
    T: ToGodot<Pass = ByValue>,
{
    fn into_arg<'arg>(self) -> CowArg<'arg, Variant>
    where
        Self: 'arg,
    {
        CowArg::Owned(self.to_variant())
    }
}

// Macro for ByRef types -> Variant. Generic params go in `[]`, empty for non-generic types.
macro_rules! impl_asarg_variant_for_ref {
    ([$($gen:tt)*] $T:ty) => {
        impl<$($gen)*> AsArg<Variant> for &$T {
            fn into_arg<'arg>(self) -> CowArg<'arg, Variant>
            where
                Self: 'arg,
            {
                CowArg::Owned(self.to_variant())
            }
        }
    };
}

impl_asarg_variant_for_ref!([] GString);
impl_asarg_variant_for_ref!([] StringName);
impl_asarg_variant_for_ref!([] NodePath);
impl_asarg_variant_for_ref!([] Callable);
impl_asarg_variant_for_ref!([] Signal);
impl_asarg_variant_for_ref!([T: Element] crate::builtin::Array<T>);
impl_asarg_variant_for_ref!([K: Element, V: Element] crate::builtin::Dictionary<K, V>);
impl_asarg_variant_for_ref!([T: PackedElement] crate::builtin::PackedArray<T>);
impl_asarg_variant_for_ref!([T: GodotClass] Gd<T>);

// ----------------------------------------------------------------------------------------------------------------------------------------------
// AsDirectElement trait for array![] macro

/// Marker trait for types directly usable in the [`array!`][crate::array] and [`dict!`][crate::dict] macros.
///
/// More restrictive than [`AsArg<T>`] — avoids ambiguity once `AsArg<Variant>` impls are added.
/// Implemented for:
/// - `T` when `T: Element + ToGodot<Pass = ByValue>` (e.g. `i32`, `bool`, `Color`).
/// - `&T` when `T: Element + ToGodot<Pass = ByRef>` (e.g. `&GString`, `&Array<T>`).
/// - `&str`, `&String` for `GString` (only; not `StringName`/`NodePath` to avoid ambiguity).
pub trait AsDirectElement<T: Element>: AsArg<T> {}

// ByValue: T directly passes as element (i32, bool, Vector2, ...).
//
// Explicitly supports other integer types than i64.
impl<T> AsDirectElement<T> for T where T: Element + ToGodot<Pass = ByValue> {}

// ByRef: &T passes as element (GString, Array, Dictionary, ...).
impl<T> AsDirectElement<T> for &T where T: Element + ToGodot<Pass = ByRef> {}

// Potentially allow this? However, it encourages manual case differentiation when working with objects,
// which goes against the idea of implicit upcasts/option-casts/dyn-casts.
// impl<T: GodotClass> AsDirectElement<Gd<T>> for &Gd<T> {}

// String coercions: &str / &String -> GString only.
//
// Unlike impl_asarg_string!, we do NOT add impls for StringName/NodePath, to avoid ambiguity.
// iarray!["hello"] would otherwise be ambiguous between Array<GString>, Array<StringName>, Array<NodePath>.
// Users who need Array<StringName> from literals can use iarray![StringName::from("hi")] or
// provide a type annotation: let arr: Array<StringName> = array!["hi"].
impl AsDirectElement<GString> for &str {}
impl AsDirectElement<GString> for &String {}