smallrye / jandex

Java Annotation Indexer

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

consider adding `FieldInfo.enumConstantOrdinal()`

Ladicek opened this issue · comments

Currently, Jandex doesn't expose an operation to obtain the ordinal of an enum constant. The only way is to obtain the list of enum constants in declaration order (see #253), find the desired constant in that list, and use the position.

It would be best to just store the ordinal of each enum constant in the index, so that we can return it directly.

This would require an index version bump and so can only be added in a minor release.

Alternatively, we could expose this operation implemented in a crude way: obtain the list of enum constants and find the position in that list. That doesn't require storing anything in the index and so can be added in a micro version.

Technically bytecode order doesn't have to correspond to declaration order. Therefore, implementing this (and #253) based on the bytecode order is fragile. It seems to work well in practice, both with javac and ECJ, though, so we can go with it.

To be able to obtain an ordinal of an enum constant faithfully, the only truly reliable way would be to load and initialize the enum class and then interrogate it. Alternatively, we could inspect the class initializer bytecode, but the JLS explicitly says that different bytecode compilers may compile enum constructors differently, so we would actually have to implement a small part of a JVM :-) Technically both javac and ECJ use the same strategy: the 1st synthetic parameter of the enum constructor is the enum constant name and the 2nd synthetic parameter is the ordinal. Resorting to just that would still require a decent amount of abstract interpretation (track the values on the stack before invoking the constructor).

As mentioned above, we can go just with the bytecode order.