RFR: Generate Java enums
Maurizio Cimadamore
mcimadamore at openjdk.org
Mon Jul 7 21:36:51 UTC 2025
On Mon, 7 Jul 2025 21:26:46 GMT, Maurizio Cimadamore <mcimadamore at openjdk.org> wrote:
>> Another thing that came to mind: if we translate C enums as Java enums -- how is a native function accepting a C enum type translated? If we translate it as an int-accepting function (what we do now) then the Java enum constants cannot be used to call into native functions. If we translate it as a Java-enum-accepting function, then we would make these function stricter than their C counterparts.
>
>> Hey @mcimadamore please excuse my gap in understanding here, but won't this operation be possible in Java by doing: `Color.Red.ordinal() | Color.Blue.ordinal()`?
>
> As said in another comment, there's no guarantee that the Java enum ordinal and the value of the C enum constant will be the same. So, no, that would not be a good translation. Also, please consider clients passing enums to native functions -- right now they can just say e.g.
>
>
> native_func(RED);
>
>
> It would be sad if they had to do:
>
>
> native_func(RED.ordinal());
>
>
> Of course one could imagine generating one extra overload for each enum-accepting function -- but that has issues:
>
> * you can only use the Java enum-accepting overload in some cases, but not other (where you want to use bitwise ops)
> * if a function uses N enum types, you need 2^N overloads (at least if you want to generate all possible combinations)
>
> I don't think much joy is to be had by modelling C enums with Java enums. We've been at it several times, and we keep retracing our steps back to the same answers.
> Thanks @mcimadamore for your feedback. Yes, if we can at least group related enum constants together under a separate generated class, that will be awesome. Would it be okay if I update this PR to have this change? Please let me know. Thanks!
I think we should ponder this some more. For simple use cases, it is really great to just have all the enum constants "in scope" in the same way as it happens with C. W/o that, the user would be left to try and figure out "what to include" for each enum. This might not be too obvious because the C source file one is trying to convert might only refer to enum _constants_ but never to the _enum type_ bringing these constants into existence. E.g. a C source might just use `Red` and `Green` and pass them to functions (and maybe these functions just take an `int`) -- and the code might never utter `Color`, ever. As a jextract user, how would I know that I need to `import static foo.Color.*` to get there?
I'm not saying this is a blocker -- just listing all the various potential issues with changing the status quo (also as a way to explain why we are where we are).
-------------
PR Comment: https://git.openjdk.org/jextract/pull/284#issuecomment-3046576333
More information about the jextract-dev
mailing list