Java Code Examples for com.sun.tools.javac.api.JavacTaskImpl#parse()

The following examples show how to use com.sun.tools.javac.api.JavacTaskImpl#parse() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: JavacParserTest.java    From openjdk-8-source with GNU General Public License v2.0 6 votes vote down vote up
@Test
void testVariableInIfThen5() throws IOException {

    String code = "package t; class Test { "+
            "private static void t() { " +
            "if (true) } }";
    DiagnosticCollector<JavaFileObject> coll =
            new DiagnosticCollector<JavaFileObject>();
    JavacTaskImpl ct = (JavacTaskImpl) tool.getTask(null, null, coll, null,
            null, Arrays.asList(new MyFileObject(code)));

    ct.parse();

    List<String> codes = new LinkedList<String>();

    for (Diagnostic<? extends JavaFileObject> d : coll.getDiagnostics()) {
        codes.add(d.getCode());
    }

    assertEquals("testVariableInIfThen5",
            Arrays.<String>asList("compiler.err.illegal.start.of.stmt"),
            codes);
}
 
Example 2
Source File: NewArrayPretty.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
void run(String code) throws IOException {
    String src = "public class Test {" + code + ";}";

    JavacTaskImpl ct = (JavacTaskImpl) tool.getTask(null, null, null, null,
            null, Arrays.asList(new MyFileObject(src)));

    for (CompilationUnitTree cut : ct.parse()) {
        JCTree.JCVariableDecl var =
                (JCTree.JCVariableDecl) ((ClassTree) cut.getTypeDecls().get(0)).getMembers().get(0);

        if (!code.equals(var.toString())) {
            System.err.println("Expected: " + code);
            System.err.println("Obtained: " + var.toString());
            throw new RuntimeException("strings do not match!");
        }
    }
}
 
Example 3
Source File: JavacParserTest.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
@Test
void testVariableInIfThen3() throws IOException {

    String code = "package t; class Test { "+
            "private static void t() { " +
            "if (true) abstract class F {} }}";
    DiagnosticCollector<JavaFileObject> coll =
            new DiagnosticCollector<JavaFileObject>();
    JavacTaskImpl ct = (JavacTaskImpl) tool.getTask(null, fm, coll, null,
            null, Arrays.asList(new MyFileObject(code)));

    ct.parse();

    List<String> codes = new LinkedList<String>();

    for (Diagnostic<? extends JavaFileObject> d : coll.getDiagnostics()) {
        codes.add(d.getCode());
    }

    assertEquals("testVariableInIfThen3",
            Arrays.<String>asList("compiler.err.class.not.allowed"), codes);
}
 
Example 4
Source File: JavacParserTest.java    From openjdk-8-source with GNU General Public License v2.0 6 votes vote down vote up
@Test
void testVariableInIfThen2() throws IOException {

     String code = "package t; class Test { " +
             "private static void t(String name) { " +
             "if (name != null) class X {} } }";
     DiagnosticCollector<JavaFileObject> coll =
             new DiagnosticCollector<JavaFileObject>();
     JavacTaskImpl ct = (JavacTaskImpl) tool.getTask(null, null, coll, null,
             null, Arrays.asList(new MyFileObject(code)));

     ct.parse();

     List<String> codes = new LinkedList<String>();

     for (Diagnostic<? extends JavaFileObject> d : coll.getDiagnostics()) {
         codes.add(d.getCode());
     }

     assertEquals("testVariableInIfThen2",
             Arrays.<String>asList("compiler.err.class.not.allowed"), codes);
 }
 
Example 5
Source File: JavacParserTest.java    From openjdk-jdk8u with GNU General Public License v2.0 6 votes vote down vote up
@Test
void testVariableInIfThen4() throws IOException {

    String code = "package t; class Test { "+
            "private static void t(String name) { " +
            "if (name != null) interface X {} } }";
    DiagnosticCollector<JavaFileObject> coll =
            new DiagnosticCollector<JavaFileObject>();
    JavacTaskImpl ct = (JavacTaskImpl) tool.getTask(null, null, coll, null,
            null, Arrays.asList(new MyFileObject(code)));

    ct.parse();

    List<String> codes = new LinkedList<String>();

    for (Diagnostic<? extends JavaFileObject> d : coll.getDiagnostics()) {
        codes.add(d.getCode());
    }

    assertEquals("testVariableInIfThen4",
            Arrays.<String>asList("compiler.err.class.not.allowed"), codes);
}
 
Example 6
Source File: JavacParserTest.java    From openjdk-8 with GNU General Public License v2.0 6 votes vote down vote up
@Test
void testVariableInIfThen1() throws IOException {

    String code = "package t; class Test { " +
            "private static void t(String name) { " +
            "if (name != null) String nn = name.trim(); } }";

    DiagnosticCollector<JavaFileObject> coll =
            new DiagnosticCollector<JavaFileObject>();

    JavacTaskImpl ct = (JavacTaskImpl) tool.getTask(null, null, coll, null,
            null, Arrays.asList(new MyFileObject(code)));

    ct.parse();

    List<String> codes = new LinkedList<String>();

    for (Diagnostic<? extends JavaFileObject> d : coll.getDiagnostics()) {
        codes.add(d.getCode());
    }

    assertEquals("testVariableInIfThen1",
            Arrays.<String>asList("compiler.err.variable.not.allowed"),
            codes);
}
 
Example 7
Source File: JavacParserTest.java    From jdk8u60 with GNU General Public License v2.0 6 votes vote down vote up
@Test
void testVariableInIfThen4() throws IOException {

    String code = "package t; class Test { "+
            "private static void t(String name) { " +
            "if (name != null) interface X {} } }";
    DiagnosticCollector<JavaFileObject> coll =
            new DiagnosticCollector<JavaFileObject>();
    JavacTaskImpl ct = (JavacTaskImpl) tool.getTask(null, null, coll, null,
            null, Arrays.asList(new MyFileObject(code)));

    ct.parse();

    List<String> codes = new LinkedList<String>();

    for (Diagnostic<? extends JavaFileObject> d : coll.getDiagnostics()) {
        codes.add(d.getCode());
    }

    assertEquals("testVariableInIfThen4",
            Arrays.<String>asList("compiler.err.class.not.allowed"), codes);
}
 
Example 8
Source File: JavacParserTest.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 6 votes vote down vote up
@Test
void testVariableInIfThen2() throws IOException {

     String code = "package t; class Test { " +
             "private static void t(String name) { " +
             "if (name != null) class X {} } }";
     DiagnosticCollector<JavaFileObject> coll =
             new DiagnosticCollector<JavaFileObject>();
     JavacTaskImpl ct = (JavacTaskImpl) tool.getTask(null, null, coll, null,
             null, Arrays.asList(new MyFileObject(code)));

     ct.parse();

     List<String> codes = new LinkedList<String>();

     for (Diagnostic<? extends JavaFileObject> d : coll.getDiagnostics()) {
         codes.add(d.getCode());
     }

     assertEquals("testVariableInIfThen2",
             Arrays.<String>asList("compiler.err.class.not.allowed"), codes);
 }
 
Example 9
Source File: JavacParserTest.java    From jdk8u60 with GNU General Public License v2.0 6 votes vote down vote up
@Test
void testVariableInIfThen1() throws IOException {

    String code = "package t; class Test { " +
            "private static void t(String name) { " +
            "if (name != null) String nn = name.trim(); } }";

    DiagnosticCollector<JavaFileObject> coll =
            new DiagnosticCollector<JavaFileObject>();

    JavacTaskImpl ct = (JavacTaskImpl) tool.getTask(null, null, coll, null,
            null, Arrays.asList(new MyFileObject(code)));

    ct.parse();

    List<String> codes = new LinkedList<String>();

    for (Diagnostic<? extends JavaFileObject> d : coll.getDiagnostics()) {
        codes.add(d.getCode());
    }

    assertEquals("testVariableInIfThen1",
            Arrays.<String>asList("compiler.err.variable.not.allowed"),
            codes);
}
 
Example 10
Source File: JavacParserTest.java    From hottub with GNU General Public License v2.0 6 votes vote down vote up
@Test
void testVariableInIfThen5() throws IOException {

    String code = "package t; class Test { "+
            "private static void t() { " +
            "if (true) } }";
    DiagnosticCollector<JavaFileObject> coll =
            new DiagnosticCollector<JavaFileObject>();
    JavacTaskImpl ct = (JavacTaskImpl) tool.getTask(null, null, coll, null,
            null, Arrays.asList(new MyFileObject(code)));

    ct.parse();

    List<String> codes = new LinkedList<String>();

    for (Diagnostic<? extends JavaFileObject> d : coll.getDiagnostics()) {
        codes.add(d.getCode());
    }

    assertEquals("testVariableInIfThen5",
            Arrays.<String>asList("compiler.err.illegal.start.of.stmt"),
            codes);
}
 
Example 11
Source File: JavacParserTest.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 6 votes vote down vote up
@Test
void testVariableInIfThen5() throws IOException {

    String code = "package t; class Test { "+
            "private static void t() { " +
            "if (true) } }";
    DiagnosticCollector<JavaFileObject> coll =
            new DiagnosticCollector<JavaFileObject>();
    JavacTaskImpl ct = (JavacTaskImpl) tool.getTask(null, null, coll, null,
            null, Arrays.asList(new MyFileObject(code)));

    ct.parse();

    List<String> codes = new LinkedList<String>();

    for (Diagnostic<? extends JavaFileObject> d : coll.getDiagnostics()) {
        codes.add(d.getCode());
    }

    assertEquals("testVariableInIfThen5",
            Arrays.<String>asList("compiler.err.illegal.start.of.stmt"),
            codes);
}
 
Example 12
Source File: NewArrayPretty.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 6 votes vote down vote up
void run(String code) throws IOException {
    String src = "public class Test {" + code + ";}";

    JavacTaskImpl ct = (JavacTaskImpl) tool.getTask(null, null, null, null,
            null, Arrays.asList(new MyFileObject(src)));

    for (CompilationUnitTree cut : ct.parse()) {
        JCTree.JCVariableDecl var =
                (JCTree.JCVariableDecl) ((ClassTree) cut.getTypeDecls().get(0)).getMembers().get(0);

        if (!code.equals(var.toString())) {
            System.err.println("Expected: " + code);
            System.err.println("Obtained: " + var.toString());
            throw new RuntimeException("strings do not match!");
        }
    }
}
 
Example 13
Source File: JavacParserTest.java    From openjdk-8-source with GNU General Public License v2.0 6 votes vote down vote up
@Test
void testVariableInIfThen1() throws IOException {

    String code = "package t; class Test { " +
            "private static void t(String name) { " +
            "if (name != null) String nn = name.trim(); } }";

    DiagnosticCollector<JavaFileObject> coll =
            new DiagnosticCollector<JavaFileObject>();

    JavacTaskImpl ct = (JavacTaskImpl) tool.getTask(null, null, coll, null,
            null, Arrays.asList(new MyFileObject(code)));

    ct.parse();

    List<String> codes = new LinkedList<String>();

    for (Diagnostic<? extends JavaFileObject> d : coll.getDiagnostics()) {
        codes.add(d.getCode());
    }

    assertEquals("testVariableInIfThen1",
            Arrays.<String>asList("compiler.err.variable.not.allowed"),
            codes);
}
 
Example 14
Source File: EdgeCases.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
@Test
public void testParseEnterAnalyze(Path base) throws Exception {
    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    try (StandardJavaFileManager fm = compiler.getStandardFileManager(null, null, null)) {
        Path moduleSrc = base.resolve("module-src");
        Path m1 = moduleSrc.resolve("m1x");

        tb.writeJavaFiles(m1, "module m1x { }",
                              "package p;",
                              "package p; class T { }");

        Path classes = base.resolve("classes");
        Iterable<? extends JavaFileObject> files = fm.getJavaFileObjects(findJavaFiles(moduleSrc));
        List<String> options = Arrays.asList("-d", classes.toString(), "-Xpkginfo:always");
        JavacTaskImpl task = (JavacTaskImpl) compiler.getTask(null, fm, null, options, null, files);

        Iterable<? extends CompilationUnitTree> parsed = task.parse();
        Iterable<? extends Element> entered = task.enter(parsed);
        Iterable<? extends Element> analyzed = task.analyze(entered);
        Iterable<? extends JavaFileObject> generatedFiles = task.generate(analyzed);

        Set<String> generated = new HashSet<>();

        for (JavaFileObject jfo : generatedFiles) {
            generated.add(jfo.getName());
        }

        Set<String> expected = new HashSet<>(
                Arrays.asList(Paths.get("testParseEnterAnalyze", "classes", "p", "package-info.class").toString(),
                              Paths.get("testParseEnterAnalyze", "classes", "module-info.class").toString(),
                              Paths.get("testParseEnterAnalyze", "classes", "p", "T.class").toString())
        );

        if (!Objects.equals(expected, generated))
            throw new AssertionError("Incorrect generated files: " + generated);
    }
}
 
Example 15
Source File: CodeTransformerTestHelper.java    From Refaster with Apache License 2.0 5 votes vote down vote up
public JavaFileObject transform(JavaFileObject original) {
  JavaCompiler compiler = JavacTool.create();
  DiagnosticCollector<JavaFileObject> diagnosticsCollector =
      new DiagnosticCollector<JavaFileObject>();
  StandardJavaFileManager fileManager =
      compiler.getStandardFileManager(diagnosticsCollector, Locale.ENGLISH, UTF_8);
  JavacTaskImpl task = (JavacTaskImpl) compiler.getTask(CharStreams.nullWriter(),
      fileManager,
      diagnosticsCollector,
      ImmutableList.<String>of(),
      null,
      ImmutableList.of(original));

  try {
    SourceFile sourceFile = SourceFile.create(original);
    Iterable<? extends CompilationUnitTree> trees = task.parse();
    task.analyze();
    JCCompilationUnit tree =
        FluentIterable.from(trees).filter(JCCompilationUnit.class).getOnlyElement();
    DescriptionBasedDiff diff = DescriptionBasedDiff.create(tree);
    transformer().apply(tree, task.getContext(), diff);
    diff.applyDifferences(sourceFile);

    return JavaFileObjects.forSourceString(
        FluentIterable.from(tree.getTypeDecls())
            .filter(JCClassDecl.class)
            .getOnlyElement()
            .sym.getQualifiedName().toString(),
        sourceFile.getSourceText());
  } catch (IOException e) {
    throw new RuntimeException(e);
  }
}
 
Example 16
Source File: T6457284.java    From openjdk-8 with GNU General Public License v2.0 5 votes vote down vote up
public static void main(String[] args) throws IOException {
    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    JavacTaskImpl task = (JavacTaskImpl)compiler.getTask(null, null, null, null, null,
                                                         List.of(new MyFileObject()));
    MyMessages.preRegister(task.getContext());
    task.parse();
    for (Element e : task.analyze()) {
        if (!e.getEnclosingElement().toString().equals("compiler.misc.unnamed.package"))
            throw new AssertionError(e.getEnclosingElement());
        System.out.println("OK: " + e.getEnclosingElement());
        return;
    }
    throw new AssertionError("No top-level classes!");
}
 
Example 17
Source File: TypeAnnotationsPretty.java    From hottub with GNU General Public License v2.0 5 votes vote down vote up
private void runField(String code) throws IOException {
    String src = prefix +
            code + "; }" +
            postfix;

    JavacTaskImpl ct = (JavacTaskImpl) tool.getTask(null, null, null, null,
            null, Arrays.asList(new MyFileObject(src)));

    for (CompilationUnitTree cut : ct.parse()) {
        JCTree.JCVariableDecl var =
                (JCTree.JCVariableDecl) ((ClassTree) cut.getTypeDecls().get(0)).getMembers().get(0);
        checkMatch(code, var);
    }
}
 
Example 18
Source File: TypeAnnotationsPretty.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
private void runMethod(String code) throws IOException {
    String src = prefix +
            code + "}" +
            postfix;

    JavacTaskImpl ct = (JavacTaskImpl) tool.getTask(null, null, null, null,
            null, Arrays.asList(new MyFileObject(src)));


    for (CompilationUnitTree cut : ct.parse()) {
        JCTree.JCMethodDecl meth =
                (JCTree.JCMethodDecl) ((ClassTree) cut.getTypeDecls().get(0)).getMembers().get(0);
        checkMatch(code, meth);
    }
}
 
Example 19
Source File: AnonymousNumberingTest.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public void testCorrectAnonymousIndicesForMethodInvocations() throws Exception {
    String code = "package test;\n" +
                  "public class Test {\n" +
                  "    public Test main(Object o) {\n" +
                  "        return new Test().main(new Runnable() {\n" +
                  "            public void run() {\n" +
                  "                throw new UnsupportedOperationException();\n" +
                  "            }\n" +
                  "        }).main(new Iterable() {\n" +
                  "            public java.util.Iterator iterator() {\n" +
                  "                throw new UnsupportedOperationException();\n" +
                  "            }\n" +
                  "        });\n" +
                  "    }\n" +
                  "}";

    JavacTaskImpl ct = Utilities.createJavac(null, Utilities.fileObjectFor(code));
    
    Iterable<? extends CompilationUnitTree> cuts = ct.parse();
    Iterable<? extends Element> analyze = ct.analyze();
    
    Symtab symTab = Symtab.instance(ct.getContext());
    Modules modules = Modules.instance(ct.getContext());
    TypeElement first = symTab.getClass(modules.getDefaultModule(), (Name)ct.getElements().getName("test.Test$1"));
    TypeElement second = symTab.getClass(modules.getDefaultModule(), (Name)ct.getElements().getName("test.Test$2"));

    assertEquals("java.lang.Iterable", ((TypeElement) ((DeclaredType) first.getInterfaces().get(0)).asElement()).getQualifiedName().toString());
    assertEquals("java.lang.Runnable", ((TypeElement) ((DeclaredType) second.getInterfaces().get(0)).asElement()).getQualifiedName().toString());
}
 
Example 20
Source File: SourceAnalyzerTest.java    From netbeans with Apache License 2.0 4 votes vote down vote up
public void testBrokenReference() throws Exception {
    final FileObject javaFile = FileUtil.toFileObject(TestFileUtils.writeFile(
         new File(FileUtil.toFile(src),"Test.java"),        //NOI18N
         "public class Test {   \n" +                       //NOI18N
         "    public static void main(String[] args) {\n" + //NOI18N
         "        Runnable r = Lib::foo;\n" +               //NOI18N
         "    }\n" +                                        //NOI18N
         "}"));                                             //NOI18N

    final DiagnosticListener<JavaFileObject> diag = new DiagnosticListener<JavaFileObject>() {

        private final Queue<Diagnostic<? extends JavaFileObject>> problems = new ArrayDeque<Diagnostic<? extends JavaFileObject>>();

        @Override
        public void report(Diagnostic<? extends JavaFileObject> diagnostic) {
            problems.offer(diagnostic);
        }
    };
    TransactionContext.beginStandardTransaction(src.toURL(), true, ()->false, true);
    try {
        final ClasspathInfo cpInfo = ClasspathInfoAccessor.getINSTANCE().create(
            src,
            null,
            true,
            true,
            false,
            true);
        final JavaFileObject jfo = FileObjects.sourceFileObject(javaFile, src);
        final JavacTaskImpl jt = JavacParser.createJavacTask(
            cpInfo,
            diag,
            SourceLevelQuery.getSourceLevel(src),  //NOI18N
            SourceLevelQuery.Profile.DEFAULT,
            null, null, null, null, Arrays.asList(jfo));
        final Iterable<? extends CompilationUnitTree> trees = jt.parse();
        jt.enter();
        jt.analyze();
        final SourceAnalyzerFactory.SimpleAnalyzer sa = SourceAnalyzerFactory.createSimpleAnalyzer();
        List<Pair<Pair<BinaryName, String>, Object[]>> data = sa.analyseUnit(trees.iterator().next(), jt);
        assertEquals(1, data.size());
        assertTrue(((Collection)data.iterator().next().second()[0]).contains(
            DocumentUtil.encodeUsage("Lib", EnumSet.<ClassIndexImpl.UsageType>of(   //NOI18N
                ClassIndexImpl.UsageType.TYPE_REFERENCE))));
    } finally {
        TransactionContext.get().rollBack();
    }
}