The following example shows that the end positions reported for synthetic trees like implicit constructors, and the inferred type of `var` variables, changes from -1 before the change to being the same as the start position of the AST node.
Before:
$ java --add-exports=jdk.compiler/com.sun.tools.javac.tree=ALL-UNNAMED CompilerTest.java
[0,-1]
<init>() {
super();
}
[27,-1]
int x = 42
After:
$ java --add-exports=jdk.compiler/com.sun.tools.javac.tree=ALL-UNNAMED CompilerTest.java
[0,0]
<init>() {
super();
}
[27,27]
int x = 42
Repro:
```
import com.sun.source.tree.CompilationUnitTree;
import com.sun.source.tree.MethodTree;
import com.sun.source.tree.Tree;
import com.sun.source.tree.VariableTree;
import com.sun.source.util.JavacTask;
import com.sun.source.util.TreePathScanner;
import com.sun.tools.javac.tree.JCTree;
import javax.tools.JavaCompiler;
import javax.tools.JavaFileObject;
import javax.tools.SimpleJavaFileObject;
import javax.tools.ToolProvider;
import java.io.IOException;
import java.net.URI;
import java.util.List;
public final class CompilerTest {
public static void main(final String[] args) throws IOException {
final JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
final JavacTask task =
(JavacTask) compiler.getTask(null, null, null, null, null, List.of(new TestFileObject()));
final Iterable<? extends CompilationUnitTree> compilationUnitTrees = task.parse();
task.analyze();
for (final CompilationUnitTree compilationUnitTree : compilationUnitTrees) {
var endPosTable = ((JCTree.JCCompilationUnit) compilationUnitTree).endPositions;
new TreePathScanner<Void, Void>() {
@Override
public Void visitMethod(MethodTree node, Void unused) {
if (node.getName().contentEquals("<init>")) {
printPosition(node);
System.err.println(node);
}
return super.visitMethod(node, unused);
}
@Override
public Void visitVariable(VariableTree node, Void unused) {
if (node.getName().contentEquals("x")) {
printPosition(node.getType());
System.err.println(node);
}
return super.visitVariable(node, unused);
}
private void printPosition(Tree tree) {
JCTree jcTree = (JCTree) tree;
System.err.printf(
"[%d,%d]\n", jcTree.getStartPosition(), jcTree.getEndPosition(endPosTable));
}
}.scan(compilationUnitTree, null);
}
}
private static final class TestFileObject extends SimpleJavaFileObject {
public TestFileObject() {
super(URI.create("myfo:/Test.java"), JavaFileObject.Kind.SOURCE);
}
@Override
public CharSequence getCharContent(final boolean ignoreEncodingErrors) throws IOException {
return """
class T {
void f() {
var x = 42;
}
}
""";
}
}
}
```
- caused by
-
JDK-8371309 Diagnostic.getEndPosition can throw an NPE with typical broken code
-
- Resolved
-