test/tools/javac/parser/JavacParserTest.java

Mon, 26 Mar 2012 15:28:49 +0100

author
mcimadamore
date
Mon, 26 Mar 2012 15:28:49 +0100
changeset 1239
2827076dbf64
parent 1149
e7d5e1a7cde5
child 1249
9c429f38ca7e
permissions
-rw-r--r--

7133185: Update 292 overload resolution logic to match JLS
Summary: Re-implement special overload resolution support for method handles according to the JLS SE 7 definition
Reviewed-by: jjg, dlsmith, jrose

     1 /*
     2  * Copyright (c) 2011, Oracle and/or its affiliates. All rights reserved.
     3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
     4  *
     5  * This code is free software; you can redistribute it and/or modify it
     6  * under the terms of the GNU General Public License version 2 only, as
     7  * published by the Free Software Foundation.
     8  *
     9  * This code is distributed in the hope that it will be useful, but WITHOUT
    10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
    11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
    12  * version 2 for more details (a copy is included in the LICENSE file that
    13  * accompanied this code).
    14  *
    15  * You should have received a copy of the GNU General Public License version
    16  * 2 along with this work; if not, write to the Free Software Foundation,
    17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
    18  *
    19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
    20  * or visit www.oracle.com if you need additional information or have any
    21  * questions.
    22  */
    24 /*
    25  * @test
    26  * @bug 7073631
    27  * @summary tests error and diagnostics positions
    28  * @author  Jan Lahoda
    29  */
    31 import com.sun.source.tree.BinaryTree;
    32 import com.sun.source.tree.BlockTree;
    33 import com.sun.source.tree.ClassTree;
    34 import com.sun.source.tree.CompilationUnitTree;
    35 import com.sun.source.tree.ErroneousTree;
    36 import com.sun.source.tree.ExpressionStatementTree;
    37 import com.sun.source.tree.ExpressionTree;
    38 import com.sun.source.tree.MethodInvocationTree;
    39 import com.sun.source.tree.MethodTree;
    40 import com.sun.source.tree.ModifiersTree;
    41 import com.sun.source.tree.StatementTree;
    42 import com.sun.source.tree.Tree;
    43 import com.sun.source.tree.Tree.Kind;
    44 import com.sun.source.tree.VariableTree;
    45 import com.sun.source.tree.WhileLoopTree;
    46 import com.sun.source.util.SourcePositions;
    47 import com.sun.source.util.TreeScanner;
    48 import com.sun.source.util.Trees;
    49 import com.sun.tools.javac.api.JavacTaskImpl;
    50 import com.sun.tools.javac.tree.JCTree;
    51 import java.io.IOException;
    52 import java.net.URI;
    53 import java.util.ArrayList;
    54 import java.util.Arrays;
    55 import java.util.LinkedList;
    56 import java.util.List;
    57 import javax.tools.Diagnostic;
    58 import javax.tools.DiagnosticCollector;
    59 import javax.tools.DiagnosticListener;
    60 import javax.tools.JavaCompiler;
    61 import javax.tools.JavaFileObject;
    62 import javax.tools.SimpleJavaFileObject;
    63 import javax.tools.ToolProvider;
    65 public class JavacParserTest extends TestCase {
    66     final JavaCompiler tool;
    67     public JavacParserTest(String testName) {
    68         tool = ToolProvider.getSystemJavaCompiler();
    69         System.out.println("java.home=" + System.getProperty("java.home"));
    70     }
    72     static class MyFileObject extends SimpleJavaFileObject {
    74         private String text;
    76         public MyFileObject(String text) {
    77             super(URI.create("myfo:/Test.java"), JavaFileObject.Kind.SOURCE);
    78             this.text = text;
    79         }
    81         @Override
    82         public CharSequence getCharContent(boolean ignoreEncodingErrors) {
    83             return text;
    84         }
    85     }
    86     /*
    87      * converts Windows to Unix style LFs for comparing strings
    88      */
    89     private String normalize(String in) {
    90         return in.replace(System.getProperty("line.separator"), "\n");
    91     }
    93     public CompilationUnitTree getCompilationUnitTree(String code) throws IOException {
    95         JavacTaskImpl ct = (JavacTaskImpl) tool.getTask(null, null, null, null,
    96                 null, Arrays.asList(new MyFileObject(code)));
    97         CompilationUnitTree cut = ct.parse().iterator().next();
    98         return cut;
    99     }
   101     public List<String> getErroneousTreeValues(ErroneousTree node) {
   103         List<String> values = new ArrayList<>();
   104         if (node.getErrorTrees() != null) {
   105             for (Tree t : node.getErrorTrees()) {
   106                 values.add(t.toString());
   107             }
   108         } else {
   109             throw new RuntimeException("ERROR: No Erroneous tree "
   110                     + "has been created.");
   111         }
   112         return values;
   113     }
   115     public void testPositionForSuperConstructorCalls() throws IOException {
   116         assert tool != null;
   118         String code = "package test; public class Test {public Test() {super();}}";
   120         JavacTaskImpl ct = (JavacTaskImpl) tool.getTask(null, null, null, null,
   121                 null, Arrays.asList(new MyFileObject(code)));
   122         CompilationUnitTree cut = ct.parse().iterator().next();
   123         SourcePositions pos = Trees.instance(ct).getSourcePositions();
   125         MethodTree method =
   126                 (MethodTree) ((ClassTree) cut.getTypeDecls().get(0)).getMembers().get(0);
   127         ExpressionStatementTree es =
   128                 (ExpressionStatementTree) method.getBody().getStatements().get(0);
   130         final int esStartPos = code.indexOf(es.toString());
   131         final int esEndPos = esStartPos + es.toString().length();
   132         assertEquals("testPositionForSuperConstructorCalls",
   133                 esStartPos, pos.getStartPosition(cut, es));
   134         assertEquals("testPositionForSuperConstructorCalls",
   135                 esEndPos, pos.getEndPosition(cut, es));
   137         MethodInvocationTree mit = (MethodInvocationTree) es.getExpression();
   139         final int mitStartPos = code.indexOf(mit.toString());
   140         final int mitEndPos = mitStartPos + mit.toString().length();
   141         assertEquals("testPositionForSuperConstructorCalls",
   142                 mitStartPos, pos.getStartPosition(cut, mit));
   143         assertEquals("testPositionForSuperConstructorCalls",
   144                 mitEndPos, pos.getEndPosition(cut, mit));
   146         final int methodStartPos = mitStartPos;
   147         final int methodEndPos = methodStartPos + mit.getMethodSelect().toString().length();
   148         assertEquals("testPositionForSuperConstructorCalls",
   149                 methodStartPos, pos.getStartPosition(cut, mit.getMethodSelect()));
   150         assertEquals("testPositionForSuperConstructorCalls",
   151                 methodEndPos, pos.getEndPosition(cut, mit.getMethodSelect()));
   153     }
   155     public void testPositionForEnumModifiers() throws IOException {
   157         String code = "package test; public enum Test {A;}";
   159         JavacTaskImpl ct = (JavacTaskImpl) tool.getTask(null, null, null, null,
   160                 null, Arrays.asList(new MyFileObject(code)));
   161         CompilationUnitTree cut = ct.parse().iterator().next();
   162         SourcePositions pos = Trees.instance(ct).getSourcePositions();
   164         ClassTree clazz = (ClassTree) cut.getTypeDecls().get(0);
   165         ModifiersTree mt = clazz.getModifiers();
   167         assertEquals("testPositionForEnumModifiers",
   168                 38 - 24, pos.getStartPosition(cut, mt));
   169         assertEquals("testPositionForEnumModifiers",
   170                 44 - 24, pos.getEndPosition(cut, mt));
   171     }
   173     public void testNewClassWithEnclosing() throws IOException {
   176         String code = "package test; class Test { " +
   177                 "class d {} private void method() { " +
   178                 "Object o = Test.this.new d(); } }";
   180         JavacTaskImpl ct = (JavacTaskImpl) tool.getTask(null, null, null, null,
   181                 null, Arrays.asList(new MyFileObject(code)));
   182         CompilationUnitTree cut = ct.parse().iterator().next();
   183         SourcePositions pos = Trees.instance(ct).getSourcePositions();
   185         ClassTree clazz = (ClassTree) cut.getTypeDecls().get(0);
   186         ExpressionTree est =
   187                 ((VariableTree) ((MethodTree) clazz.getMembers().get(1)).getBody().getStatements().get(0)).getInitializer();
   189         assertEquals("testNewClassWithEnclosing",
   190                 97 - 24, pos.getStartPosition(cut, est));
   191         assertEquals("testNewClassWithEnclosing",
   192                 114 - 24, pos.getEndPosition(cut, est));
   193     }
   195     public void testPreferredPositionForBinaryOp() throws IOException {
   197         String code = "package test; public class Test {"
   198                 + "private void test() {"
   199                 + "Object o = null; boolean b = o != null && o instanceof String;"
   200                 + "} private Test() {}}";
   202         CompilationUnitTree cut = getCompilationUnitTree(code);
   203         ClassTree clazz = (ClassTree) cut.getTypeDecls().get(0);
   204         MethodTree method = (MethodTree) clazz.getMembers().get(0);
   205         VariableTree condSt = (VariableTree) method.getBody().getStatements().get(1);
   206         BinaryTree cond = (BinaryTree) condSt.getInitializer();
   208         JCTree condJC = (JCTree) cond;
   209         int condStartPos = code.indexOf("&&");
   210         assertEquals("testPreferredPositionForBinaryOp",
   211                 condStartPos, condJC.pos);
   212     }
   214     public void testPositionBrokenSource126732a() throws IOException {
   215         String[] commands = new String[]{
   216             "return Runnable()",
   217             "do { } while (true)",
   218             "throw UnsupportedOperationException()",
   219             "assert true",
   220             "1 + 1",};
   222         for (String command : commands) {
   224             String code = "package test;\n"
   225                     + "public class Test {\n"
   226                     + "    public static void test() {\n"
   227                     + "        " + command + " {\n"
   228                     + "                new Runnable() {\n"
   229                     + "        };\n"
   230                     + "    }\n"
   231                     + "}";
   232             JavacTaskImpl ct = (JavacTaskImpl) tool.getTask(null, null, null,
   233                     null, null, Arrays.asList(new MyFileObject(code)));
   234             CompilationUnitTree cut = ct.parse().iterator().next();
   236             ClassTree clazz = (ClassTree) cut.getTypeDecls().get(0);
   237             MethodTree method = (MethodTree) clazz.getMembers().get(0);
   238             List<? extends StatementTree> statements =
   239                     method.getBody().getStatements();
   241             StatementTree ret = statements.get(0);
   242             StatementTree block = statements.get(1);
   244             Trees t = Trees.instance(ct);
   245             int len = code.indexOf(command + " {") + (command + " ").length();
   246             assertEquals(command, len,
   247                     t.getSourcePositions().getEndPosition(cut, ret));
   248             assertEquals(command, len,
   249                     t.getSourcePositions().getStartPosition(cut, block));
   250         }
   251     }
   253     public void testPositionBrokenSource126732b() throws IOException {
   254         String[] commands = new String[]{
   255             "break",
   256             "break A",
   257             "continue ",
   258             "continue A",};
   260         for (String command : commands) {
   262             String code = "package test;\n"
   263                     + "public class Test {\n"
   264                     + "    public static void test() {\n"
   265                     + "        while (true) {\n"
   266                     + "            " + command + " {\n"
   267                     + "                new Runnable() {\n"
   268                     + "        };\n"
   269                     + "        }\n"
   270                     + "    }\n"
   271                     + "}";
   273             JavacTaskImpl ct = (JavacTaskImpl) tool.getTask(null, null, null,
   274                     null, null, Arrays.asList(new MyFileObject(code)));
   275             CompilationUnitTree cut = ct.parse().iterator().next();
   277             ClassTree clazz = (ClassTree) cut.getTypeDecls().get(0);
   278             MethodTree method = (MethodTree) clazz.getMembers().get(0);
   279             List<? extends StatementTree> statements =
   280                     ((BlockTree) ((WhileLoopTree) method.getBody().getStatements().get(0)).getStatement()).getStatements();
   282             StatementTree ret = statements.get(0);
   283             StatementTree block = statements.get(1);
   285             Trees t = Trees.instance(ct);
   286             int len = code.indexOf(command + " {") + (command + " ").length();
   287             assertEquals(command, len,
   288                     t.getSourcePositions().getEndPosition(cut, ret));
   289             assertEquals(command, len,
   290                     t.getSourcePositions().getStartPosition(cut, block));
   291         }
   292     }
   294     public void testErrorRecoveryForEnhancedForLoop142381() throws IOException {
   296         String code = "package test; class Test { " +
   297                 "private void method() { " +
   298                 "java.util.Set<String> s = null; for (a : s) {} } }";
   300         final List<Diagnostic<? extends JavaFileObject>> errors =
   301                 new LinkedList<Diagnostic<? extends JavaFileObject>>();
   303         JavacTaskImpl ct = (JavacTaskImpl) tool.getTask(null, null,
   304                 new DiagnosticListener<JavaFileObject>() {
   305             public void report(Diagnostic<? extends JavaFileObject> diagnostic) {
   306                 errors.add(diagnostic);
   307             }
   308         }, null, null, Arrays.asList(new MyFileObject(code)));
   310         CompilationUnitTree cut = ct.parse().iterator().next();
   312         ClassTree clazz = (ClassTree) cut.getTypeDecls().get(0);
   313         StatementTree forStatement =
   314                 ((MethodTree) clazz.getMembers().get(0)).getBody().getStatements().get(1);
   316         assertEquals("testErrorRecoveryForEnhancedForLoop142381",
   317                 Kind.ENHANCED_FOR_LOOP, forStatement.getKind());
   318         assertFalse("testErrorRecoveryForEnhancedForLoop142381", errors.isEmpty());
   319     }
   321     public void testPositionAnnotationNoPackage187551() throws IOException {
   323         String code = "\n@interface Test {}";
   325         JavacTaskImpl ct = (JavacTaskImpl) tool.getTask(null, null, null, null,
   326                 null, Arrays.asList(new MyFileObject(code)));
   328         CompilationUnitTree cut = ct.parse().iterator().next();
   329         ClassTree clazz = (ClassTree) cut.getTypeDecls().get(0);
   330         Trees t = Trees.instance(ct);
   332         assertEquals("testPositionAnnotationNoPackage187551",
   333                 1, t.getSourcePositions().getStartPosition(cut, clazz));
   334     }
   336     public void testPositionsSane() throws IOException {
   337         performPositionsSanityTest("package test; class Test { " +
   338                 "private void method() { " +
   339                 "java.util.List<? extends java.util.List<? extends String>> l; " +
   340                 "} }");
   341         performPositionsSanityTest("package test; class Test { " +
   342                 "private void method() { " +
   343                 "java.util.List<? super java.util.List<? super String>> l; " +
   344                 "} }");
   345         performPositionsSanityTest("package test; class Test { " +
   346                 "private void method() { " +
   347                 "java.util.List<? super java.util.List<?>> l; } }");
   348     }
   350     private void performPositionsSanityTest(String code) throws IOException {
   352         final List<Diagnostic<? extends JavaFileObject>> errors =
   353                 new LinkedList<Diagnostic<? extends JavaFileObject>>();
   355         JavacTaskImpl ct = (JavacTaskImpl) tool.getTask(null, null,
   356                 new DiagnosticListener<JavaFileObject>() {
   358             public void report(Diagnostic<? extends JavaFileObject> diagnostic) {
   359                 errors.add(diagnostic);
   360             }
   361         }, null, null, Arrays.asList(new MyFileObject(code)));
   363         final CompilationUnitTree cut = ct.parse().iterator().next();
   364         final Trees trees = Trees.instance(ct);
   366         new TreeScanner<Void, Void>() {
   368             private long parentStart = 0;
   369             private long parentEnd = Integer.MAX_VALUE;
   371             @Override
   372             public Void scan(Tree node, Void p) {
   373                 if (node == null) {
   374                     return null;
   375                 }
   377                 long start = trees.getSourcePositions().getStartPosition(cut, node);
   379                 if (start == (-1)) {
   380                     return null; //synthetic tree
   381                 }
   382                 assertTrue(node.toString() + ":" + start + "/" + parentStart,
   383                         parentStart <= start);
   385                 long prevParentStart = parentStart;
   387                 parentStart = start;
   389                 long end = trees.getSourcePositions().getEndPosition(cut, node);
   391                 assertTrue(node.toString() + ":" + end + "/" + parentEnd,
   392                         end <= parentEnd);
   394                 long prevParentEnd = parentEnd;
   396                 parentEnd = end;
   398                 super.scan(node, p);
   400                 parentStart = prevParentStart;
   401                 parentEnd = prevParentEnd;
   403                 return null;
   404             }
   406             private void assertTrue(String message, boolean b) {
   407                 if (!b) fail(message);
   408             }
   409         }.scan(cut, null);
   410     }
   412     public void testCorrectWilcardPositions() throws IOException {
   413         performWildcardPositionsTest("package test; import java.util.List; " +
   414                 "class Test { private void method() { List<? extends List<? extends String>> l; } }",
   416                 Arrays.asList("List<? extends List<? extends String>> l;",
   417                 "List<? extends List<? extends String>>",
   418                 "List",
   419                 "? extends List<? extends String>",
   420                 "List<? extends String>",
   421                 "List",
   422                 "? extends String",
   423                 "String"));
   424         performWildcardPositionsTest("package test; import java.util.List; " +
   425                 "class Test { private void method() { List<? super List<? super String>> l; } }",
   427                 Arrays.asList("List<? super List<? super String>> l;",
   428                 "List<? super List<? super String>>",
   429                 "List",
   430                 "? super List<? super String>",
   431                 "List<? super String>",
   432                 "List",
   433                 "? super String",
   434                 "String"));
   435         performWildcardPositionsTest("package test; import java.util.List; " +
   436                 "class Test { private void method() { List<? super List<?>> l; } }",
   438                 Arrays.asList("List<? super List<?>> l;",
   439                 "List<? super List<?>>",
   440                 "List",
   441                 "? super List<?>",
   442                 "List<?>",
   443                 "List",
   444                 "?"));
   445         performWildcardPositionsTest("package test; import java.util.List; " +
   446                 "class Test { private void method() { " +
   447                 "List<? extends List<? extends List<? extends String>>> l; } }",
   449                 Arrays.asList("List<? extends List<? extends List<? extends String>>> l;",
   450                 "List<? extends List<? extends List<? extends String>>>",
   451                 "List",
   452                 "? extends List<? extends List<? extends String>>",
   453                 "List<? extends List<? extends String>>",
   454                 "List",
   455                 "? extends List<? extends String>",
   456                 "List<? extends String>",
   457                 "List",
   458                 "? extends String",
   459                 "String"));
   460         performWildcardPositionsTest("package test; import java.util.List; " +
   461                 "class Test { private void method() { " +
   462                 "List<? extends List<? extends List<? extends String   >>> l; } }",
   463                 Arrays.asList("List<? extends List<? extends List<? extends String   >>> l;",
   464                 "List<? extends List<? extends List<? extends String   >>>",
   465                 "List",
   466                 "? extends List<? extends List<? extends String   >>",
   467                 "List<? extends List<? extends String   >>",
   468                 "List",
   469                 "? extends List<? extends String   >",
   470                 "List<? extends String   >",
   471                 "List",
   472                 "? extends String",
   473                 "String"));
   474     }
   476     public void performWildcardPositionsTest(final String code,
   477             List<String> golden) throws IOException {
   479         final List<Diagnostic<? extends JavaFileObject>> errors =
   480                 new LinkedList<Diagnostic<? extends JavaFileObject>>();
   482         JavacTaskImpl ct = (JavacTaskImpl) tool.getTask(null, null,
   483                 new DiagnosticListener<JavaFileObject>() {
   484                     public void report(Diagnostic<? extends JavaFileObject> diagnostic) {
   485                         errors.add(diagnostic);
   486                     }
   487                 }, null, null, Arrays.asList(new MyFileObject(code)));
   489         final CompilationUnitTree cut = ct.parse().iterator().next();
   490         final List<String> content = new LinkedList<String>();
   491         final Trees trees = Trees.instance(ct);
   493         new TreeScanner<Void, Void>() {
   494             @Override
   495             public Void scan(Tree node, Void p) {
   496                 if (node == null) {
   497                     return null;
   498                 }
   499                 long start = trees.getSourcePositions().getStartPosition(cut, node);
   501                 if (start == (-1)) {
   502                     return null; //synthetic tree
   503                 }
   504                 long end = trees.getSourcePositions().getEndPosition(cut, node);
   505                 String s = code.substring((int) start, (int) end);
   506                 content.add(s);
   508                 return super.scan(node, p);
   509             }
   510         }.scan(((MethodTree) ((ClassTree) cut.getTypeDecls().get(0)).getMembers().get(0)).getBody().getStatements().get(0), null);
   512         assertEquals("performWildcardPositionsTest",golden.toString(),
   513                 content.toString());
   514     }
   516     public void testStartPositionForMethodWithoutModifiers() throws IOException {
   518         String code = "package t; class Test { <T> void t() {} }";
   520         JavacTaskImpl ct = (JavacTaskImpl) tool.getTask(null, null, null, null,
   521                 null, Arrays.asList(new MyFileObject(code)));
   522         CompilationUnitTree cut = ct.parse().iterator().next();
   523         ClassTree clazz = (ClassTree) cut.getTypeDecls().get(0);
   524         MethodTree mt = (MethodTree) clazz.getMembers().get(0);
   525         Trees t = Trees.instance(ct);
   526         int start = (int) t.getSourcePositions().getStartPosition(cut, mt);
   527         int end = (int) t.getSourcePositions().getEndPosition(cut, mt);
   529         assertEquals("testStartPositionForMethodWithoutModifiers",
   530                 "<T> void t() {}", code.substring(start, end));
   531     }
   533     public void testStartPositionEnumConstantInit() throws IOException {
   535         String code = "package t; enum Test { AAA; }";
   537         JavacTaskImpl ct = (JavacTaskImpl) tool.getTask(null, null, null, null,
   538                 null, Arrays.asList(new MyFileObject(code)));
   539         CompilationUnitTree cut = ct.parse().iterator().next();
   540         ClassTree clazz = (ClassTree) cut.getTypeDecls().get(0);
   541         VariableTree enumAAA = (VariableTree) clazz.getMembers().get(0);
   542         Trees t = Trees.instance(ct);
   543         int start = (int) t.getSourcePositions().getStartPosition(cut,
   544                 enumAAA.getInitializer());
   546         assertEquals("testStartPositionEnumConstantInit", -1, start);
   547     }
   549     public void testVariableInIfThen1() throws IOException {
   551         String code = "package t; class Test { " +
   552                 "private static void t(String name) { " +
   553                 "if (name != null) String nn = name.trim(); } }";
   555         DiagnosticCollector<JavaFileObject> coll =
   556                 new DiagnosticCollector<JavaFileObject>();
   558         JavacTaskImpl ct = (JavacTaskImpl) tool.getTask(null, null, coll, null,
   559                 null, Arrays.asList(new MyFileObject(code)));
   561         ct.parse();
   563         List<String> codes = new LinkedList<String>();
   565         for (Diagnostic<? extends JavaFileObject> d : coll.getDiagnostics()) {
   566             codes.add(d.getCode());
   567         }
   569         assertEquals("testVariableInIfThen1",
   570                 Arrays.<String>asList("compiler.err.variable.not.allowed"),
   571                 codes);
   572     }
   574     public void testVariableInIfThen2() throws IOException {
   576         String code = "package t; class Test { " +
   577                 "private static void t(String name) { " +
   578                 "if (name != null) class X {} } }";
   579         DiagnosticCollector<JavaFileObject> coll =
   580                 new DiagnosticCollector<JavaFileObject>();
   581         JavacTaskImpl ct = (JavacTaskImpl) tool.getTask(null, null, coll, null,
   582                 null, Arrays.asList(new MyFileObject(code)));
   584         ct.parse();
   586         List<String> codes = new LinkedList<String>();
   588         for (Diagnostic<? extends JavaFileObject> d : coll.getDiagnostics()) {
   589             codes.add(d.getCode());
   590         }
   592         assertEquals("testVariableInIfThen2",
   593                 Arrays.<String>asList("compiler.err.class.not.allowed"), codes);
   594     }
   596     public void testVariableInIfThen3() throws IOException {
   598         String code = "package t; class Test { "+
   599                 "private static void t(String name) { " +
   600                 "if (name != null) abstract } }";
   601         DiagnosticCollector<JavaFileObject> coll =
   602                 new DiagnosticCollector<JavaFileObject>();
   603         JavacTaskImpl ct = (JavacTaskImpl) tool.getTask(null, null, coll, null,
   604                 null, Arrays.asList(new MyFileObject(code)));
   606         ct.parse();
   608         List<String> codes = new LinkedList<String>();
   610         for (Diagnostic<? extends JavaFileObject> d : coll.getDiagnostics()) {
   611             codes.add(d.getCode());
   612         }
   614         assertEquals("testVariableInIfThen3",
   615                 Arrays.<String>asList("compiler.err.illegal.start.of.expr"),
   616                 codes);
   617     }
   619     //see javac bug #6882235, NB bug #98234:
   620     public void testMissingExponent() throws IOException {
   622         String code = "\nclass Test { { System.err.println(0e); } }";
   624         JavacTaskImpl ct = (JavacTaskImpl) tool.getTask(null, null, null, null,
   625                 null, Arrays.asList(new MyFileObject(code)));
   627         assertNotNull(ct.parse().iterator().next());
   628     }
   630     public void testTryResourcePos() throws IOException {
   632         final String code = "package t; class Test { " +
   633                 "{ try (java.io.InputStream in = null) { } } }";
   635         CompilationUnitTree cut = getCompilationUnitTree(code);
   637         new TreeScanner<Void, Void>() {
   638             @Override
   639             public Void visitVariable(VariableTree node, Void p) {
   640                 if ("in".contentEquals(node.getName())) {
   641                     JCTree.JCVariableDecl var = (JCTree.JCVariableDecl) node;
   642                     System.out.println(node.getName() + "," + var.pos);
   643                     assertEquals("testTryResourcePos", "in = null) { } } }",
   644                             code.substring(var.pos));
   645                 }
   646                 return super.visitVariable(node, p);
   647             }
   648         }.scan(cut, null);
   649     }
   651     public void testVarPos() throws IOException {
   653         final String code = "package t; class Test { " +
   654                 "{ java.io.InputStream in = null; } }";
   656         CompilationUnitTree cut = getCompilationUnitTree(code);
   658         new TreeScanner<Void, Void>() {
   660             @Override
   661             public Void visitVariable(VariableTree node, Void p) {
   662                 if ("in".contentEquals(node.getName())) {
   663                     JCTree.JCVariableDecl var = (JCTree.JCVariableDecl) node;
   664                     assertEquals("testVarPos","in = null; } }",
   665                             code.substring(var.pos));
   666                 }
   667                 return super.visitVariable(node, p);
   668             }
   669         }.scan(cut, null);
   670     }
   672     // expected erroneous tree: int x = y;(ERROR);
   673     public void testOperatorMissingError() throws IOException {
   675         String code = "package test; public class ErrorTest { "
   676                 + "void method() { int x = y  z } }";
   677         CompilationUnitTree cut = getCompilationUnitTree(code);
   678         final List<String> values = new ArrayList<>();
   679         final List<String> expectedValues =
   680                 new ArrayList<>(Arrays.asList("[z]"));
   682         new TreeScanner<Void, Void>() {
   684             @Override
   685             public Void visitErroneous(ErroneousTree node, Void p) {
   687                 values.add(getErroneousTreeValues(node).toString());
   688                 return null;
   690             }
   691         }.scan(cut, null);
   693         assertEquals("testSwitchError: The Erroneous tree "
   694                 + "error values: " + values
   695                 + " do not match expected error values: "
   696                 + expectedValues, values, expectedValues);
   697     }
   699     //expected erroneous tree:  String s = (ERROR);
   700     public void testMissingParenthesisError() throws IOException {
   702         String code = "package test; public class ErrorTest { "
   703                 + "void f() {String s = new String; } }";
   704         CompilationUnitTree cut = getCompilationUnitTree(code);
   705         final List<String> values = new ArrayList<>();
   706         final List<String> expectedValues =
   707                 new ArrayList<>(Arrays.asList("[new String()]"));
   709         new TreeScanner<Void, Void>() {
   711             @Override
   712             public Void visitErroneous(ErroneousTree node, Void p) {
   714                 values.add(getErroneousTreeValues(node).toString());
   715                 return null;
   716             }
   717         }.scan(cut, null);
   719         assertEquals("testSwitchError: The Erroneous tree "
   720                 + "error values: " + values
   721                 + " do not match expected error values: "
   722                 + expectedValues, values, expectedValues);
   723     }
   725     //expected erroneous tree: package test; (ERROR)(ERROR)
   726     public void testMissingClassError() throws IOException {
   728         String code = "package Test; clas ErrorTest {  "
   729                 + "void f() {String s = new String(); } }";
   730         CompilationUnitTree cut = getCompilationUnitTree(code);
   731         final List<String> values = new ArrayList<>();
   732         final List<String> expectedValues =
   733                 new ArrayList<>(Arrays.asList("[, clas]", "[]"));
   735         new TreeScanner<Void, Void>() {
   737             @Override
   738             public Void visitErroneous(ErroneousTree node, Void p) {
   740                 values.add(getErroneousTreeValues(node).toString());
   741                 return null;
   742             }
   743         }.scan(cut, null);
   745         assertEquals("testSwitchError: The Erroneous tree "
   746                 + "error values: " + values
   747                 + " do not match expected error values: "
   748                 + expectedValues, values, expectedValues);
   749     }
   751     //expected erroneous tree: void m1(int i) {(ERROR);{(ERROR);}
   752     public void testSwitchError() throws IOException {
   754         String code = "package test; public class ErrorTest { "
   755                 + "int numDays; void m1(int i) { switchh {i} { case 1: "
   756                 + "numDays = 31; break; } } }";
   757         CompilationUnitTree cut = getCompilationUnitTree(code);
   758         final List<String> values = new ArrayList<>();
   759         final List<String> expectedValues =
   760                 new ArrayList<>(Arrays.asList("[switchh]", "[i]"));
   762         new TreeScanner<Void, Void>() {
   764             @Override
   765             public Void visitErroneous(ErroneousTree node, Void p) {
   767                 values.add(getErroneousTreeValues(node).toString());
   768                 return null;
   769             }
   770         }.scan(cut, null);
   772         assertEquals("testSwitchError: The Erroneous tree "
   773                 + "error values: " + values
   774                 + " do not match expected error values: "
   775                 + expectedValues, values, expectedValues);
   776     }
   778     //expected erroneous tree: class ErrorTest {(ERROR)
   779     public void testMethodError() throws IOException {
   781         String code = "package Test; class ErrorTest {  "
   782                 + "static final void f) {String s = new String(); } }";
   783         CompilationUnitTree cut = getCompilationUnitTree(code);
   784         final List<String> values = new ArrayList<>();
   785         final List<String> expectedValues =
   786                 new ArrayList<>(Arrays.asList("[\nstatic final void f();]"));
   788         new TreeScanner<Void, Void>() {
   790             @Override
   791             public Void visitErroneous(ErroneousTree node, Void p) {
   793                 values.add(normalize(getErroneousTreeValues(node).toString()));
   794                 return null;
   795             }
   796         }.scan(cut, null);
   798         assertEquals("testMethodError: The Erroneous tree "
   799                 + "error value: " + values
   800                 + " does not match expected error values: "
   801                 + expectedValues, values, expectedValues);
   802     }
   804     void testsNotWorking() throws IOException {
   806         // Fails with nb-javac, needs further investigation
   807         testPositionBrokenSource126732a();
   808         testPositionBrokenSource126732b();
   810         // Fails, these tests yet to be addressed
   811         testVariableInIfThen1();
   812         testVariableInIfThen2();
   813         testPositionForEnumModifiers();
   814         testStartPositionEnumConstantInit();
   815     }
   816     void testPositions() throws IOException {
   817         testPositionsSane();
   818         testCorrectWilcardPositions();
   819         testPositionAnnotationNoPackage187551();
   820         testPositionForSuperConstructorCalls();
   821         testPreferredPositionForBinaryOp();
   822         testStartPositionForMethodWithoutModifiers();
   823         testVarPos();
   824         testVariableInIfThen3();
   825         testMissingExponent();
   826         testTryResourcePos();
   827         testOperatorMissingError();
   828         testMissingParenthesisError();
   829         testMissingClassError();
   830         testSwitchError();
   831         testMethodError();
   832     }
   834     public static void main(String... args) throws IOException {
   835         JavacParserTest jpt = new JavacParserTest("JavacParserTest");
   836         jpt.testPositions();
   837         System.out.println("PASS");
   838     }
   839 }
   841 abstract class TestCase {
   843     void assertEquals(String message, int i, int pos) {
   844         if (i != pos) {
   845             fail(message);
   846         }
   847     }
   849     void assertFalse(String message, boolean empty) {
   850         throw new UnsupportedOperationException("Not yet implemented");
   851     }
   853     void assertEquals(String message, int i, long l) {
   854         if (i != l) {
   855             fail(message + ":" + i + ":" + l);
   856         }
   857     }
   859     void assertEquals(String message, Object o1, Object o2) {
   860         System.out.println(o1);
   861         System.out.println(o2);
   862         if (o1 != null && o2 != null && !o1.equals(o2)) {
   863             fail(message);
   864         }
   865         if (o1 == null && o2 != null) {
   866             fail(message);
   867         }
   868     }
   870     void assertNotNull(Object o) {
   871         if (o == null) {
   872             fail();
   873         }
   874     }
   876     void fail() {
   877         fail("test failed");
   878     }
   880     void fail(String message) {
   881         throw new RuntimeException(message);
   882     }
   883 }

mercurial