"#define" constants as methods
Maurizio Cimadamore
maurizio.cimadamore at oracle.com
Fri Apr 5 08:54:34 UTC 2024
Hi
On 04/04/2024 19:38, Jorn Vernee wrote:
> This is a good point. The result of a method call can not be used as a
> case label in a switch. We could potentially change jextract to just
> expose string constants using methods, and use fields for the others.
> This would be inconsistent, but I think better, since it allows
> constants to be used as switch case labels. I suspect Maurizio will
> want to weigh in on this as well.
Unfortunately this is a case where the language puts us in a difficult
corner - for a value to be usable in a switch label it must be a
constant expression, and constant expressions include a very limited
subset of the Java language (including static final fields whose
initializer is a constant expression).
This creates a tension between usabilty (I think it's natural to want to
switch on constant values!) and laziness (a constant value must be
evaluated eagerly, when the class containing the constant field is
initialized). Given the high number of constants in header classes, we
preferred laziness (for the reasons Jorn mentions, as there are some
constants that require some non-trivial setup).
I believe there is also an element of uniformity - e.g. wanting to
generate similar code for _all_ defined macro constants, rather than
generating different code based on the constant type. While generating
different code is definitively possible, we should also be mindful that
using different codegen strategies for different constant kinds might
also be confusing on its own.
One possibility I considered at some point was to _not_ convert C
strings to memory segment constants, and leave them as Java Strings (and
leave conversion to the user). Then all constants would be of the
"simple kind". But I'm afraid this would be harsh on string-heavy libraries.
Maurizio
More information about the jextract-dev
mailing list