godot-rust / godot-rust/gdext

Register enums/bitfields in classes

Open
#890 5 comments 6 reactions 0 assignees View on GitHub
c: register feature
Dominant language
Rust
Stars
5.2k
Forks
312
Avg merge
11h 10m
Merged PRs (30d)
10

Description

In Godot, a class can have integer constants as well as enums/bitfields. These enums and bitfields are largely just a convenient way of grouping together integer constants, since under the hood they are just integer constants and not fully-featured [sum types](https://en.wikipedia.org/wiki/Tagged_union) like what rust has. From what i understand, enums and bitfields are largely the same from the perspective of ffi.

We have long had support for registering integer constants associated with a class, when this was added we also made the infrastructure needed to register enums and bitfields with a class. However it wasn't clear what syntax should be used to actually register them with the proc-macros. The most obvious syntax, something like
```rs
impl Foo {
enum Bar { .. }
}
```
Does not work since enums cannot be declared in an impl block. This would be helped by [inherent associated types](https://github.com/rust-lang/rust/issues/8995) since we could then declare a type alias in the impl block.

The main things to take into account for enums and bitfields are:
- These enums and bitfields must be registered with a specific class
- They can only contain integer variants

Some possible syntaxes:

```rs
#[derive(GodotClass)]
struct Foo { .. }

#[godot_enum_bikeshed_macro(Foo)]
#[repr(u8)]
enum Bar {
..
}
```

```rs
#[derive(GodotClass)]
struct Foo { .. }

#[godot_api]
impl Foo {
#[enum(Bar)]
const A: u8 = 10;
#[enum(Bar)]
const B: u8 = 10;
}
```

@Houtamelo [made a declarative macro that emulates this](https://discord.com/channels/723850269347283004/1283480344884023297/1283552107986948146):
```rs
gdscript_rust_enum! {
GDSCRIPT: TerrainVariant; // Name of the Godot class that will contain the constants

pub enum TerrainVariant {
Water = 0, // Integer values must be provided for each variant
Plains = 1,
}
}
```

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.