Skip to content

Commit 006adca

Browse files
authored
Try #775:
2 parents 6dc9721 + 1f9c20c commit 006adca

File tree

12 files changed

+256
-3
lines changed

12 files changed

+256
-3
lines changed

gdnative-core/src/export/property/hint.rs

Lines changed: 56 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
//! Strongly typed property hints.
22
3-
use std::fmt::{self, Write};
3+
use std::fmt::{self, Display, Write};
44
use std::ops::RangeInclusive;
55

66
use crate::core_types::GodotString;
@@ -116,12 +116,22 @@ where
116116
/// ```
117117
#[derive(Clone, Eq, PartialEq, Debug, Default)]
118118
pub struct EnumHint {
119-
values: Vec<String>,
119+
values: Vec<EnumHintEntry>,
120120
}
121121

122122
impl EnumHint {
123123
#[inline]
124124
pub fn new(values: Vec<String>) -> Self {
125+
let values = values.into_iter().map(EnumHintEntry::new).collect();
126+
EnumHint { values }
127+
}
128+
129+
#[inline]
130+
pub fn with_values(values: Vec<(String, i64)>) -> Self {
131+
let values = values
132+
.into_iter()
133+
.map(|(key, value)| EnumHintEntry::with_value(key, value))
134+
.collect();
125135
EnumHint { values }
126136
}
127137

@@ -136,13 +146,46 @@ impl EnumHint {
136146
}
137147

138148
for rest in iter {
139-
write!(s, ",{rest}").unwrap();
149+
write!(s, ",").unwrap();
150+
write!(s, "{rest}").unwrap();
140151
}
141152

142153
s.into()
143154
}
144155
}
145156

157+
#[derive(Clone, PartialEq, Eq, Debug)]
158+
pub struct EnumHintEntry {
159+
key: String,
160+
value: Option<i64>,
161+
}
162+
163+
impl EnumHintEntry {
164+
#[inline]
165+
pub fn new(key: String) -> Self {
166+
Self { key, value: None }
167+
}
168+
169+
#[inline]
170+
pub fn with_value(key: String, value: i64) -> Self {
171+
Self {
172+
key,
173+
value: Some(value),
174+
}
175+
}
176+
}
177+
178+
impl Display for EnumHintEntry {
179+
#[inline]
180+
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
181+
write!(f, "{}", self.key)?;
182+
if let Some(value) = self.value {
183+
write!(f, ":{}", value)?;
184+
}
185+
Ok(())
186+
}
187+
}
188+
146189
/// Possible hints for integers.
147190
#[derive(Clone, Debug)]
148191
#[non_exhaustive]
@@ -469,3 +512,13 @@ impl ArrayHint {
469512
}
470513
}
471514
}
515+
516+
godot_test!(test_enum_hint_without_mapping {
517+
let hint = EnumHint::new(vec!["Foo".into(), "Bar".into()]);
518+
assert_eq!(hint.to_godot_hint_string().to_string(), "Foo,Bar".to_string(),);
519+
});
520+
521+
godot_test!(test_enum_hint_with_mapping {
522+
let hint = EnumHint::with_values(vec![("Foo".into(), 42), ("Bar".into(), 67)]);
523+
assert_eq!(hint.to_godot_hint_string().to_string(), "Foo:42,Bar:67".to_string(),);
524+
});

gdnative-derive/src/export.rs

Lines changed: 68 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,68 @@
1+
use crate::crate_gdnative_core;
2+
use proc_macro2::{Span, TokenStream as TokenStream2};
3+
use syn::spanned::Spanned;
4+
use syn::{DeriveInput, Fields};
5+
6+
fn err_only_supports_fieldless_enums(span: Span) -> syn::Error {
7+
syn::Error::new(span, "#[derive(Export)] only supports fieldless enums")
8+
}
9+
10+
pub(crate) fn derive_export(input: &DeriveInput) -> syn::Result<TokenStream2> {
11+
let derived_enum = match &input.data {
12+
syn::Data::Enum(data) => data,
13+
syn::Data::Struct(data) => {
14+
return Err(err_only_supports_fieldless_enums(data.struct_token.span()));
15+
}
16+
syn::Data::Union(data) => {
17+
return Err(err_only_supports_fieldless_enums(data.union_token.span()));
18+
}
19+
};
20+
21+
let export_impl = impl_export(&input.ident, derived_enum)?;
22+
Ok(export_impl)
23+
}
24+
25+
fn impl_export(enum_ty: &syn::Ident, data: &syn::DataEnum) -> syn::Result<TokenStream2> {
26+
let err = data
27+
.variants
28+
.iter()
29+
.filter(|variant| !matches!(variant.fields, Fields::Unit))
30+
.map(|variant| err_only_supports_fieldless_enums(variant.ident.span()))
31+
.reduce(|mut acc, err| {
32+
acc.combine(err);
33+
acc
34+
});
35+
if let Some(err) = err {
36+
return Err(err);
37+
}
38+
39+
let mappings = data
40+
.variants
41+
.iter()
42+
.map(|variant| {
43+
let key = &variant.ident;
44+
let val = quote! { #enum_ty::#key as i64 };
45+
quote! { (stringify!(#key).to_string(), #val) }
46+
})
47+
.collect::<Vec<_>>();
48+
let gdnative_core = crate_gdnative_core();
49+
50+
let impl_block = quote! {
51+
const _: () = {
52+
pub enum NoHint {}
53+
54+
impl #gdnative_core::export::Export for #enum_ty {
55+
type Hint = NoHint;
56+
57+
#[inline]
58+
fn export_info(_hint: Option<Self::Hint>) -> #gdnative_core::export::ExportInfo {
59+
let mappings = vec![ #(#mappings),* ];
60+
let enum_hint = #gdnative_core::export::hint::EnumHint::with_values(mappings);
61+
return #gdnative_core::export::hint::IntHint::<i64>::Enum(enum_hint).export_info();
62+
}
63+
}
64+
};
65+
};
66+
67+
Ok(impl_block)
68+
}

gdnative-derive/src/lib.rs

Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@ use proc_macro2::TokenStream as TokenStream2;
1010
use quote::ToTokens;
1111
use syn::{parse::Parser, AttributeArgs, DeriveInput, ItemFn, ItemImpl, ItemType};
1212

13+
mod export;
1314
mod init;
1415
mod methods;
1516
mod native_script;
@@ -663,6 +664,63 @@ pub fn godot_wrap_method(input: TokenStream) -> TokenStream {
663664
}
664665
}
665666

667+
/// Make a rust `enum` has drop-down list in Godot editor.
668+
/// Note that the derived `enum` should also implements `Copy` trait.
669+
///
670+
/// Take the following example, you will see a drop-down list for the `dir`
671+
/// property, and `Up` and `Down` converts to `1` and `-1` in the GDScript
672+
/// side.
673+
///
674+
/// ```
675+
/// use gdnative::prelude::*;
676+
///
677+
/// #[derive(Debug, PartialEq, Clone, Copy, Export, ToVariant, FromVariant)]
678+
/// #[variant(enum = "repr")]
679+
/// #[repr(i32)]
680+
/// enum Dir {
681+
/// Up = 1,
682+
/// Down = -1,
683+
/// }
684+
///
685+
/// #[derive(NativeClass)]
686+
/// #[no_constructor]
687+
/// struct Move {
688+
/// #[property]
689+
/// pub dir: Dir,
690+
/// }
691+
/// ```
692+
///
693+
/// You can't derive `Export` on `enum` that has non-unit variant.
694+
///
695+
/// ```compile_fail
696+
/// use gdnative::prelude::*;
697+
///
698+
/// #[derive(Debug, PartialEq, Clone, Copy, Export)]
699+
/// enum Action {
700+
/// Move((f32, f32, f32)),
701+
/// Attack(u64),
702+
/// }
703+
/// ```
704+
///
705+
/// You can't derive `Export` on `struct` or `union`.
706+
///
707+
/// ```compile_fail
708+
/// use gdnative::prelude::*;
709+
///
710+
/// #[derive(Export)]
711+
/// struct Foo {
712+
/// f1: i32
713+
/// }
714+
/// ```
715+
#[proc_macro_derive(Export)]
716+
pub fn derive_export(input: TokenStream) -> TokenStream {
717+
let derive_input = syn::parse_macro_input!(input as syn::DeriveInput);
718+
match export::derive_export(&derive_input) {
719+
Ok(stream) => stream.into(),
720+
Err(err) => err.to_compile_error().into(),
721+
}
722+
}
723+
666724
/// Returns a standard header for derived implementations.
667725
///
668726
/// Adds the `automatically_derived` attribute and prevents common lints from triggering

gdnative/tests/ui.rs

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -40,6 +40,12 @@ fn ui_tests() {
4040
t.compile_fail("tests/ui/from_variant_fail_07.rs");
4141
t.compile_fail("tests/ui/from_variant_fail_08.rs");
4242
t.compile_fail("tests/ui/from_variant_fail_09.rs");
43+
44+
// Export
45+
t.pass("tests/ui/export_pass.rs");
46+
t.compile_fail("tests/ui/export_fail_01.rs");
47+
t.compile_fail("tests/ui/export_fail_02.rs");
48+
t.compile_fail("tests/ui/export_fail_03.rs");
4349
}
4450

4551
// FIXME(rust/issues/54725): Full path spans are only available on nightly as of now

gdnative/tests/ui/export_fail_01.rs

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
use gdnative::prelude::*;
2+
3+
#[derive(Export, ToVariant)]
4+
pub enum Foo {
5+
Bar(String),
6+
Baz { a: i32, b: u32 },
7+
}
8+
9+
fn main() {}
Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
error: #[derive(Export)] only supports fieldless enums
2+
--> tests/ui/export_fail_01.rs:5:5
3+
|
4+
5 | Bar(String),
5+
| ^^^
6+
7+
error: #[derive(Export)] only supports fieldless enums
8+
--> tests/ui/export_fail_01.rs:6:5
9+
|
10+
6 | Baz { a: i32, b: u32 },
11+
| ^^^

gdnative/tests/ui/export_fail_02.rs

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
use gdnative::prelude::*;
2+
3+
#[derive(Export, ToVariant)]
4+
pub struct Foo {
5+
bar: i32,
6+
}
7+
8+
fn main() {}
Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
error: #[derive(Export)] only supports fieldless enums
2+
--> tests/ui/export_fail_02.rs:4:5
3+
|
4+
4 | pub struct Foo {
5+
| ^^^^^^

gdnative/tests/ui/export_fail_03.rs

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
use gdnative::prelude::*;
2+
3+
#[derive(Export, ToVariant)]
4+
pub union Foo {
5+
bar: i32,
6+
}
7+
8+
fn main() {}
Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
error: #[derive(Export)] only supports fieldless enums
2+
--> tests/ui/export_fail_03.rs:4:5
3+
|
4+
4 | pub union Foo {
5+
| ^^^^^
6+
7+
error: Variant conversion derive macro does not work on unions.
8+
--> tests/ui/export_fail_03.rs:4:1
9+
|
10+
4 | pub union Foo {
11+
| ^^^

gdnative/tests/ui/export_pass.rs

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
use gdnative::prelude::*;
2+
3+
#[derive(Export, ToVariant, Clone, Copy)]
4+
#[variant(enum = "repr")]
5+
#[repr(i32)]
6+
pub enum Foo {
7+
Bar,
8+
Baz,
9+
}
10+
11+
fn main() {}

test/src/lib.rs

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,11 @@ pub extern "C" fn run_tests(
2828

2929
status &= gdnative::core_types::test_core_types();
3030

31+
status &= gdnative::export::hint::test_enum_hint_without_mapping();
32+
status &= gdnative::export::hint::test_enum_hint_with_mapping();
33+
34+
status &= test_underscore_method_binding();
35+
status &= test_rust_class_construction();
3136
status &= test_from_instance_id();
3237
status &= test_nil_object_return_value();
3338
status &= test_rust_class_construction();

0 commit comments

Comments
 (0)