Skip to content

Allow ignoring enum variants in To/FromVariant #697

Open
@wyattjsmith1

Description

@wyattjsmith1

Note: In this issue, I will discuss both rust's enum variants, and Godot's Variants. To avoid confusion I will use an upper case V for Godot's as it is a class, and lowercase v for rust's enums.

Problem

Currently, we can derive ToVariant: https://docs.rs/gdnative/0.9.3/gdnative/core_types/trait.ToVariant.html. This works well, and for the cases where it isn't perfect, we can add #[variant(...)] attributes to specify how the macro should process certain pieces of data. One group of these attributes is #[variant(skip_to_variant|skip_from_variant|skip)]. As the name implies, this will skip a field when converting to/from a Variant. Currently, this must be placed on a struct's field:

#[derive(ToVariant, FromVariant)]
struct MyStruct {
  converted_field: u8,
  #[variant(skip)]
  skipped_field: u8,
}

One area this could be expanded is to skipping enum variants. For example, the following currently results in a compiler error:

#[derive(ToVariant, FromVariant)]
enum MyEnum {
   VariantA,
  #[variant(skip)]
  VariantB(NonToVariantType),
}

In this example, the variant(skip) is ignored, and because VariantB contains a non-ToVariant field, this fails to compile.

Proposal

Allow #[variant(skip)] (and its siblings) to be placed on enum variants. This does pose the following issues:

  1. What if we try to call from_variant with a skipped variant?: We should consider this a failure and return an Err as if we called from_variant with a Dictionary that isn't a variant.
  2. What if we try to call to_variant with a skipped variant?: There are a couple possibilities:
  • Return Nil or possible empty dict. Benefits are no crashing, disadvantages is that there may be silent bugs.
  • panic. Benefits are that we are bringing the issues up to the developer immediately, disadvantage is that panic is not really rusty when it could be better represented as an Result or something.
  1. Why bother ignoring certain variants?: This admittedly comes from a specific use case I have, but I believe it would be good to expand the use of variant(skip). There may be cases where we need to convert a subset of enum variants to Variants while still retaining the non-To/FromVariant variants. My solution in the short-term will be to add #[variant(skip)] to the fields in my variant that are non-To/FromVariant.

Metadata

Metadata

Assignees

No one assigned

    Labels

    c: exportComponent: export (mod export, derive)featureAdds functionality to the library

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions