eclipse-jdt / eclipse-jdt/eclipse.jdt.core

Dynamically infer support source/target version from chosen CompilationUnitResolver

Open
#3,908 1 comment 0 reactions 0 assignees View on GitHub
Dominant language
Java
Stars
237
Forks
195
Avg merge
1d 12h
Merged PRs (30d)
47

Description

Currently, JDT uses hardcoded values in ECJ to derive the possible max source/target versions for compilation. However, this static approach tends to require more maintenance and make support for new Java versions harder to unleash, particularly when using an alternative compiler/CompilationUnitResolver.

Instead of using the hardcoded version, one could consider having a method `int lastSupportedCompileVersion()` that would query the chosen compiler. Consumers should be encouraged to use such a method instead of `ClassFileConstants.getLatestJDKLevel()` which is specific to built-in ECJ.

this new method could be kind of implemented as follows (drafting idea, not tested/executable):
```java
public boolean isVersionSupported(int version) {
ASTParser parser = new ASTParser(AST.getJLSLatest());
parser.setCompilerOptions(Map.of(
OPTION_Source, Integer.toString(version),
OPTION_Target, Integer.toString(version)
));
parser.setSource("class Test {}");
var ast = parser.createAST(null);
return Arrays.stream(ast.getProblems()).noneMatch(p -> p.getId() == IProblem.JavaVersionTooRecent);
}

public int lastSupportedCompilerVersion() {
int startVersion = Runtime.getRuntime().version().feature(); // choose some probable enough heuristic
if (isVersionSupported(startVersion)) {
do {
startVersion++;
} while (isVersionSupported(startVersion));
return startVersion - 1;
}
do {
startVersion--;
} while (!isVersionSupported(startVersion));
return startVersion;
}
```

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.