samcrow / canadensis

A Rust implementation of Cyphal
Apache License 2.0
44 stars 5 forks source link

codegen: enum #16

Closed joleeee closed 1 year ago

joleeee commented 1 year ago

I don't know the best way to do this, but it'd be really great if the dsdl definitions could compile into rust enums, for instance if you have

uint8 REQ_A = 0
uint8 REQ_B = 1

it would be compiled into

enum REQ {
    A = 0,
    B = 1,
}

Of course this would be kinda hard to do automatically as well as this with regards to naming in a predictable way, but anything like this would be really great. Could do it automatically if the file just contains a bunch of defines like this, maybe look for a specific comment, or take a config file / cli args.

Ways I can think of

Note: we can use rust-like #[] because # declares a comment in dsdl

Start & end

#[canadensis(enum_start)]
uint8 REQ_A = 0
uint8 REQ_B = 1
#[canadensis(enum_end)]

Explicit member

Here we can specify the name of the enum, and it would remove this prefix from the enum members, like in the rust example above.

#[canadensis_enum(REQ)]
uint8 REQ_A = 0
#[canadensis_enum(REQ)]
uint8 REQ_B = 1

Smart compiler

If the "block" consists of constants of the same type, just turn them into an enum

pavel-kirienko commented 1 year ago

Related: https://github.com/OpenCyphal/specification/issues/52

samcrow commented 1 year ago

I made some changes a while ago, but now I've released the new version. It uses a special #[canadensis(enum)] comment in a DSDL type to trigger enum code generation.

Documentation: https://github.com/samcrow/canadensis/blob/85cb16bc7c06f5d42438d4e34afd42d002e6ca14/canadensis_codegen_rust/src/struct_as_enum.rs Example DSDL files: https://github.com/samcrow/canadensis/tree/master/canadensis_codegen_rust/tests/compile_pass/canadensis

joleeee commented 1 year ago

amazing!