|
Java example source code file (JavacParserTest.java)
The JavacParserTest.java Java example source code
/*
* Copyright (c) 2011, 2012, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* @test
* @bug 7073631 7159445 7156633
* @summary tests error and diagnostics positions
* @author Jan Lahoda
*/
import com.sun.source.tree.BinaryTree;
import com.sun.source.tree.BlockTree;
import com.sun.source.tree.ClassTree;
import com.sun.source.tree.CompilationUnitTree;
import com.sun.source.tree.ErroneousTree;
import com.sun.source.tree.ExpressionStatementTree;
import com.sun.source.tree.ExpressionTree;
import com.sun.source.tree.MethodInvocationTree;
import com.sun.source.tree.MethodTree;
import com.sun.source.tree.ModifiersTree;
import com.sun.source.tree.StatementTree;
import com.sun.source.tree.Tree;
import com.sun.source.tree.Tree.Kind;
import com.sun.source.tree.VariableTree;
import com.sun.source.tree.WhileLoopTree;
import com.sun.source.util.SourcePositions;
import com.sun.source.util.TreeScanner;
import com.sun.source.util.Trees;
import com.sun.tools.javac.api.JavacTaskImpl;
import com.sun.tools.javac.tree.JCTree;
import java.io.IOException;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.lang.reflect.Method;
import java.net.URI;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
import java.util.regex.Pattern;
import javax.tools.Diagnostic;
import javax.tools.DiagnosticCollector;
import javax.tools.DiagnosticListener;
import javax.tools.JavaCompiler;
import javax.tools.JavaFileObject;
import javax.tools.SimpleJavaFileObject;
import javax.tools.ToolProvider;
public class JavacParserTest extends TestCase {
static final JavaCompiler tool = ToolProvider.getSystemJavaCompiler();
private JavacParserTest(){}
public static void main(String... args) throws Exception {
new JavacParserTest().run(args);
}
class MyFileObject extends SimpleJavaFileObject {
private String text;
public MyFileObject(String text) {
super(URI.create("myfo:/Test.java"), JavaFileObject.Kind.SOURCE);
this.text = text;
}
@Override
public CharSequence getCharContent(boolean ignoreEncodingErrors) {
return text;
}
}
/*
* converts Windows to Unix style LFs for comparing strings
*/
String normalize(String in) {
return in.replace(System.getProperty("line.separator"), "\n");
}
CompilationUnitTree getCompilationUnitTree(String code) throws IOException {
JavacTaskImpl ct = (JavacTaskImpl) tool.getTask(null, null, null, null,
null, Arrays.asList(new MyFileObject(code)));
CompilationUnitTree cut = ct.parse().iterator().next();
return cut;
}
List<String> getErroneousTreeValues(ErroneousTree node) {
List<String> values = new ArrayList<>();
if (node.getErrorTrees() != null) {
for (Tree t : node.getErrorTrees()) {
values.add(t.toString());
}
} else {
throw new RuntimeException("ERROR: No Erroneous tree "
+ "has been created.");
}
return values;
}
@Test
void testPositionForSuperConstructorCalls() throws IOException {
assert tool != null;
String code = "package test; public class Test {public Test() {super();}}";
JavacTaskImpl ct = (JavacTaskImpl) tool.getTask(null, null, null, null,
null, Arrays.asList(new MyFileObject(code)));
CompilationUnitTree cut = ct.parse().iterator().next();
SourcePositions pos = Trees.instance(ct).getSourcePositions();
MethodTree method =
(MethodTree) ((ClassTree) cut.getTypeDecls().get(0)).getMembers().get(0);
ExpressionStatementTree es =
(ExpressionStatementTree) method.getBody().getStatements().get(0);
final int esStartPos = code.indexOf(es.toString());
final int esEndPos = esStartPos + es.toString().length();
assertEquals("testPositionForSuperConstructorCalls",
esStartPos, pos.getStartPosition(cut, es));
assertEquals("testPositionForSuperConstructorCalls",
esEndPos, pos.getEndPosition(cut, es));
MethodInvocationTree mit = (MethodInvocationTree) es.getExpression();
final int mitStartPos = code.indexOf(mit.toString());
final int mitEndPos = mitStartPos + mit.toString().length();
assertEquals("testPositionForSuperConstructorCalls",
mitStartPos, pos.getStartPosition(cut, mit));
assertEquals("testPositionForSuperConstructorCalls",
mitEndPos, pos.getEndPosition(cut, mit));
final int methodStartPos = mitStartPos;
final int methodEndPos = methodStartPos + mit.getMethodSelect().toString().length();
assertEquals("testPositionForSuperConstructorCalls",
methodStartPos, pos.getStartPosition(cut, mit.getMethodSelect()));
assertEquals("testPositionForSuperConstructorCalls",
methodEndPos, pos.getEndPosition(cut, mit.getMethodSelect()));
}
@Test
void testPositionForEnumModifiers() throws IOException {
final String theString = "public";
String code = "package test; " + theString + " enum Test {A;}";
JavacTaskImpl ct = (JavacTaskImpl) tool.getTask(null, null, null, null,
null, Arrays.asList(new MyFileObject(code)));
CompilationUnitTree cut = ct.parse().iterator().next();
SourcePositions pos = Trees.instance(ct).getSourcePositions();
ClassTree clazz = (ClassTree) cut.getTypeDecls().get(0);
ModifiersTree mt = clazz.getModifiers();
int spos = code.indexOf(theString);
int epos = spos + theString.length();
assertEquals("testPositionForEnumModifiers",
spos, pos.getStartPosition(cut, mt));
assertEquals("testPositionForEnumModifiers",
epos, pos.getEndPosition(cut, mt));
}
@Test
void testNewClassWithEnclosing() throws IOException {
final String theString = "Test.this.new d()";
String code = "package test; class Test { " +
"class d {} private void method() { " +
"Object o = " + theString + "; } }";
JavacTaskImpl ct = (JavacTaskImpl) tool.getTask(null, null, null, null,
null, Arrays.asList(new MyFileObject(code)));
CompilationUnitTree cut = ct.parse().iterator().next();
SourcePositions pos = Trees.instance(ct).getSourcePositions();
ClassTree clazz = (ClassTree) cut.getTypeDecls().get(0);
ExpressionTree est =
((VariableTree) ((MethodTree) clazz.getMembers().get(1)).getBody().getStatements().get(0)).getInitializer();
final int spos = code.indexOf(theString);
final int epos = spos + theString.length();
assertEquals("testNewClassWithEnclosing",
spos, pos.getStartPosition(cut, est));
assertEquals("testNewClassWithEnclosing",
epos, pos.getEndPosition(cut, est));
}
@Test
void testPreferredPositionForBinaryOp() throws IOException {
String code = "package test; public class Test {"
+ "private void test() {"
+ "Object o = null; boolean b = o != null && o instanceof String;"
+ "} private Test() {}}";
CompilationUnitTree cut = getCompilationUnitTree(code);
ClassTree clazz = (ClassTree) cut.getTypeDecls().get(0);
MethodTree method = (MethodTree) clazz.getMembers().get(0);
VariableTree condSt = (VariableTree) method.getBody().getStatements().get(1);
BinaryTree cond = (BinaryTree) condSt.getInitializer();
JCTree condJC = (JCTree) cond;
int condStartPos = code.indexOf("&&");
assertEquals("testPreferredPositionForBinaryOp",
condStartPos, condJC.pos);
}
@Test
void testErrorRecoveryForEnhancedForLoop142381() throws IOException {
String code = "package test; class Test { " +
"private void method() { " +
"java.util.Set<String> s = null; for (a : s) {} } }";
final List<Diagnostic extends JavaFileObject>> errors =
new LinkedList<Diagnostic extends JavaFileObject>>();
JavacTaskImpl ct = (JavacTaskImpl) tool.getTask(null, null,
new DiagnosticListener<JavaFileObject>() {
public void report(Diagnostic<? extends JavaFileObject> diagnostic) {
errors.add(diagnostic);
}
}, null, null, Arrays.asList(new MyFileObject(code)));
CompilationUnitTree cut = ct.parse().iterator().next();
ClassTree clazz = (ClassTree) cut.getTypeDecls().get(0);
StatementTree forStatement =
((MethodTree) clazz.getMembers().get(0)).getBody().getStatements().get(1);
assertEquals("testErrorRecoveryForEnhancedForLoop142381",
Kind.ENHANCED_FOR_LOOP, forStatement.getKind());
assertFalse("testErrorRecoveryForEnhancedForLoop142381", errors.isEmpty());
}
@Test
void testPositionAnnotationNoPackage187551() throws IOException {
String code = "\n@interface Test {}";
JavacTaskImpl ct = (JavacTaskImpl) tool.getTask(null, null, null, null,
null, Arrays.asList(new MyFileObject(code)));
CompilationUnitTree cut = ct.parse().iterator().next();
ClassTree clazz = (ClassTree) cut.getTypeDecls().get(0);
Trees t = Trees.instance(ct);
assertEquals("testPositionAnnotationNoPackage187551",
1, t.getSourcePositions().getStartPosition(cut, clazz));
}
@Test
void testPositionsSane1() throws IOException {
performPositionsSanityTest("package test; class Test { " +
"private void method() { " +
"java.util.List<? extends java.util.List extends String>> l; " +
"} }");
}
@Test
void testPositionsSane2() throws IOException {
performPositionsSanityTest("package test; class Test { " +
"private void method() { " +
"java.util.List<? super java.util.List super String>> l; " +
"} }");
}
@Test
void testPositionsSane3() throws IOException {
performPositionsSanityTest("package test; class Test { " +
"private void method() { " +
"java.util.List<? super java.util.List>> l; } }");
}
private void performPositionsSanityTest(String code) throws IOException {
final List<Diagnostic extends JavaFileObject>> errors =
new LinkedList<Diagnostic extends JavaFileObject>>();
JavacTaskImpl ct = (JavacTaskImpl) tool.getTask(null, null,
new DiagnosticListener<JavaFileObject>() {
public void report(Diagnostic<? extends JavaFileObject> diagnostic) {
errors.add(diagnostic);
}
}, null, null, Arrays.asList(new MyFileObject(code)));
final CompilationUnitTree cut = ct.parse().iterator().next();
final Trees trees = Trees.instance(ct);
new TreeScanner<Void, Void>() {
private long parentStart = 0;
private long parentEnd = Integer.MAX_VALUE;
@Override
public Void scan(Tree node, Void p) {
if (node == null) {
return null;
}
long start = trees.getSourcePositions().getStartPosition(cut, node);
if (start == (-1)) {
return null; // synthetic tree
}
assertTrue(node.toString() + ":" + start + "/" + parentStart,
parentStart <= start);
long prevParentStart = parentStart;
parentStart = start;
long end = trees.getSourcePositions().getEndPosition(cut, node);
assertTrue(node.toString() + ":" + end + "/" + parentEnd,
end <= parentEnd);
long prevParentEnd = parentEnd;
parentEnd = end;
super.scan(node, p);
parentStart = prevParentStart;
parentEnd = prevParentEnd;
return null;
}
private void assertTrue(String message, boolean b) {
if (!b) fail(message);
}
}.scan(cut, null);
}
@Test
void testCorrectWilcardPositions1() throws IOException {
performWildcardPositionsTest("package test; import java.util.List; " +
"class Test { private void method() { List<? extends List extends String>> l; } }",
Arrays.asList("List<? extends List extends String>> l;",
"List<? extends List extends String>>",
"List",
"? extends List<? extends String>",
"List<? extends String>",
"List",
"? extends String",
"String"));
}
@Test
void testCorrectWilcardPositions2() throws IOException {
performWildcardPositionsTest("package test; import java.util.List; "
+ "class Test { private void method() { List<? super List super String>> l; } }",
Arrays.asList("List<? super List super String>> l;",
"List<? super List super String>>",
"List",
"? super List<? super String>",
"List<? super String>",
"List",
"? super String",
"String"));
}
@Test
void testCorrectWilcardPositions3() throws IOException {
performWildcardPositionsTest("package test; import java.util.List; " +
"class Test { private void method() { List<? super List>> l; } }",
Arrays.asList("List<? super List>> l;",
"List<? super List>>",
"List",
"? super List<?>",
"List<?>",
"List",
"?"));
}
@Test
void testCorrectWilcardPositions4() throws IOException {
performWildcardPositionsTest("package test; import java.util.List; " +
"class Test { private void method() { " +
"List<? extends List extends List extends String>>> l; } }",
Arrays.asList("List<? extends List extends List extends String>>> l;",
"List<? extends List extends List extends String>>>",
"List",
"? extends List<? extends List extends String>>",
"List<? extends List extends String>>",
"List",
"? extends List<? extends String>",
"List<? extends String>",
"List",
"? extends String",
"String"));
}
@Test
void testCorrectWilcardPositions5() throws IOException {
performWildcardPositionsTest("package test; import java.util.List; " +
"class Test { private void method() { " +
"List<? extends List extends List extends String >>> l; } }",
Arrays.asList("List<? extends List extends List extends String >>> l;",
"List<? extends List extends List extends String >>>",
"List",
"? extends List<? extends List extends String >>",
"List<? extends List extends String >>",
"List",
"? extends List<? extends String >",
"List<? extends String >",
"List",
"? extends String",
"String"));
}
void performWildcardPositionsTest(final String code,
List<String> golden) throws IOException {
final List<Diagnostic extends JavaFileObject>> errors =
new LinkedList<Diagnostic extends JavaFileObject>>();
JavacTaskImpl ct = (JavacTaskImpl) tool.getTask(null, null,
new DiagnosticListener<JavaFileObject>() {
public void report(Diagnostic<? extends JavaFileObject> diagnostic) {
errors.add(diagnostic);
}
}, null, null, Arrays.asList(new MyFileObject(code)));
final CompilationUnitTree cut = ct.parse().iterator().next();
final List<String> content = new LinkedList
Other Java examples (source code examples)Here is a short list of links related to this Java JavacParserTest.java source code file: |
| ... this post is sponsored by my books ... | |
#1 New Release! |
FP Best Seller |
Copyright 1998-2024 Alvin Alexander, alvinalexander.com
All Rights Reserved.
A percentage of advertising revenue from
pages under the /java/jwarehouse
URI on this website is
paid back to open source projects.