getty-zig / getty

A (de)serialization framework for Zig
https://getty.so
MIT License
189 stars 13 forks source link

Add attributes support to enum types #100

Closed ion232 closed 1 year ago

ion232 commented 1 year ago

Problem

I'm currently trying to add support for Zig to quicktype - a tool for generating language types from example JSON files or JSON schema.

I've ran into an issue in which enum types being generated from my quicktype branch have tag names that are invalid. An example of this is when generating zig types for us-senators.json. The senator_class_label is translated into the following:

const SenatorClassLabel = enum {
    Class 1,
    Class 2,
    Class 3,
};

These are invalid enum types and therefore definitely can't be deserialized by getty as is.

Proposal

To solve this I want to generate enum types with rename attributes, like quicktype currently does for Rust and generate the following in the previous case:

 const SenatorClassLabel = enum {
    class1,
    class2,
    class3,

    pub const @"getty.sb" = struct {
        pub const attributes = .{
            .class1 = .{ .rename = "Class 1" },
            .class2 = .{ .rename = "Class 2" },
            .class3 = .{ .rename = "Class 3" },
        };
    };
};

Currently, there isn't attributes support for enums, so this would have to be added on both the serialization and deserialization side.

I think the following attributes would be useful to support for enum types:

In the case of serialization serializeEnum will need to be modified to accommodate the alternative name from rename.

Alternatives

No response

Additional Context

While investigating this, I made a fork with attributes support implemented for serialization of enums, and found that the changes were relatively simple.

ibokuri commented 1 year ago

fyi, I think SenatorClassLabel can be (de)serialized without attributes if you name the variants like so:

const SenatorClassLabel = enum {
    @"Class 1",
    @"Class 2",
    @"Class 3",
};

I still think attributes should be added for enums despite that though 👍

ion232 commented 1 year ago

Ah interesting - I didn't realise you could do that. Although there is still the corner case of empty strings that isn't handled by that method. This field in the us_senators dataset is an enum that can be an empty string, and @"" is invalid in Zig.