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

The following examples show how to use com.sun.tools.javac.api.JavacTaskImpl#analyze() . 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: CompilerBasedTest.java    From Refaster with Apache License 2.0 6 votes vote down vote up
protected void compile(TreeScanner scanner, JavaFileObject fileObject) {
  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(fileObject));
  try {
    this.sourceFile = SourceFile.create(fileObject);
    Iterable<? extends CompilationUnitTree> trees = task.parse();
    task.analyze();
    for (CompilationUnitTree tree : trees) {
      scanner.scan((JCCompilationUnit) tree);
    }
  } catch (IOException e) {
    throw new RuntimeException(e);
  }
  this.context = task.getContext();
}
 
Example 2
Source File: ElementStructureTest.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
void run(Writer output, String version) throws Exception {
    List<String> options = Arrays.asList("--release", version, "-classpath", "");
    List<ToolBox.JavaSource> files = Arrays.asList(new ToolBox.JavaSource("Test", ""));
    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    JavacTaskImpl task = (JavacTaskImpl) compiler.getTask(null, null, null, options, null, files);

    task.analyze();

    JavaFileManager fm = task.getContext().get(JavaFileManager.class);

    for (String pack : packages(fm)) {
        PackageElement packEl = task.getElements().getPackageElement(pack);
        if (packEl == null) {
            throw new AssertionError("Cannot find package: " + pack);
        }
        new ExhaustiveElementScanner(task, output, p -> true).visit(packEl);
    }
}
 
Example 3
Source File: AvoidInfiniteReattribution.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
void run() throws IOException {
    JavacTool tool = JavacTool.create();
    JavaSource source = new JavaSource("class Test {" +
                                       "    I i = STOP -> {};" +
                                       "    interface I {" +
                                       "        public void test(int i) {}" +
                                       "    }" +
                                       "}");
    Context context = new Context();
    CrashingAttr.preRegister(context);
    List<JavaSource> inputs = Arrays.asList(source);
    JavacTaskImpl task =
            (JavacTaskImpl) tool.getTask(null, null, null, null, null, inputs, context);
    try {
        task.analyze(null);
        throw new AssertionError("Expected exception not seen.");
    } catch (StopException ex) {
        //ok
    }
}
 
Example 4
Source File: T6457284.java    From openjdk-jdk8u-backup 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 5
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 6
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 7
Source File: T6457284.java    From openjdk-8-source 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 8
Source File: T6457284.java    From hottub 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 9
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 10
Source File: T6457284.java    From TencentKona-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 11
Source File: AnonymousNumberingTest.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public void testCorrectNameForAnonymous() throws IOException {
    String code = "package test;\n" +
                  "public class Test {\n" +
                  "    public Test main1(Object o) {\n" +
                  "        new Runnable() {\n" +
                  "            public void run() {\n" +
                  "                throw new UnsupportedOperationException();\n" +
                  "            }\n" +
                  "        };" +
                  "        new Iterable() {\n" +
                  "            public java.util.Iterator iterator() {\n" +
                  "                new java.util.ArrayList() {};\n" +
                  "            }\n" +
                  "        };\n" +
                  "    }\n" +
                  "}";

    JavacTaskImpl ct = Utilities.createJavac(null, Utilities.fileObjectFor(code));
    
    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"));
    TypeElement third = symTab.getClass(modules.getDefaultModule(), (Name)ct.getElements().getName("test.Test$2$1"));

    assertEquals("java.lang.Runnable", ((TypeElement) ((DeclaredType) first.getInterfaces().get(0)).asElement()).getQualifiedName().toString());
    assertEquals("java.lang.Iterable", ((TypeElement) ((DeclaredType) second.getInterfaces().get(0)).asElement()).getQualifiedName().toString());
    assertEquals("java.util.ArrayList", ((TypeElement) ((DeclaredType) third.getSuperclass()).asElement()).getQualifiedName().toString());
}
 
Example 12
Source File: AnonymousNumberingTest.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public void testCorrectAnonymousIndicesForMultipleMethods() throws IOException {
    String code = "package test;\n" +
                  "public class Test {\n" +
                  "    public Test main1(Object o) {\n" +
                  "        new Runnable() {\n" +
                  "            public void run() {\n" +
                  "                throw new UnsupportedOperationException();\n" +
                  "            }\n" +
                  "        };" +
                  "    }" +
                  "    public Test main2(Object o) {\n" +
                  "        new Iterable() {\n" +
                  "            public java.util.Iterator iterator() {\n" +
                  "                throw new UnsupportedOperationException();\n" +
                  "            }\n" +
                  "        };\n" +
                  "    }\n" +
                  "    public Test main3(Object o) {\n" +
                  "        new java.util.ArrayList() {};\n" +
                  "    }\n" +
                  "}";

    JavacTaskImpl ct = Utilities.createJavac(null, Utilities.fileObjectFor(code));

    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"));
    TypeElement third = symTab.getClass(modules.getDefaultModule(), (Name)ct.getElements().getName("test.Test$3"));

    assertEquals("java.lang.Runnable", ((TypeElement) ((DeclaredType) first.getInterfaces().get(0)).asElement()).getQualifiedName().toString());
    assertEquals("java.lang.Iterable", ((TypeElement) ((DeclaredType) second.getInterfaces().get(0)).asElement()).getQualifiedName().toString());
    assertEquals("java.util.ArrayList", ((TypeElement) ((DeclaredType) third.getSuperclass()).asElement()).getQualifiedName().toString());
}
 
Example 13
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 14
Source File: Hacks.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public static Scope constructScope(CompilationInfo info, String... importedClasses) {
    StringBuilder clazz = new StringBuilder();

    clazz.append("package $$;\n");

    for (String i : importedClasses) {
        clazz.append("import ").append(i).append(";\n");
    }

    clazz.append("public class $$scopeclass$").append(inc++).append("{");

    clazz.append("private void test() {\n");
    clazz.append("}\n");
    clazz.append("}\n");

    JavacTaskImpl jti = JavaSourceAccessor.getINSTANCE().getJavacTask(info);
    Context context = jti.getContext();

    JavaCompiler jc = JavaCompiler.instance(context);
    Log.instance(context).nerrors = 0;

    JavaFileObject jfo = FileObjects.memoryFileObject("$$", "$", new File("/tmp/t.java").toURI(), System.currentTimeMillis(), clazz.toString());

    try {
        CompilationUnitTree cut = ParserFactory.instance(context).newParser(jfo.getCharContent(true), true, true, true).parseCompilationUnit();

        jti.analyze(jti.enter(Collections.singletonList(cut)));

        return new ScannerImpl().scan(cut, info);
    } catch (IOException ex) {
        Exceptions.printStackTrace(ex);
        return null;
    } finally {
    }
}
 
Example 15
Source File: T6457284.java    From openjdk-jdk8u 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 16
Source File: T6457284.java    From jdk8u60 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: JavacParser.java    From j2cl with Apache License 2.0 4 votes vote down vote up
/** Returns a map from file paths to compilation units after Javac parsing. */
public List<CompilationUnit> parseFiles(List<FileInfo> filePaths, boolean useTargetPath) {

  if (filePaths.isEmpty()) {
    return ImmutableList.of();
  }

  // The map must be ordered because it will be iterated over later and if it was not ordered then
  // our output would be unstable
  final Map<String, String> targetPathBySourcePath =
      filePaths.stream().collect(Collectors.toMap(FileInfo::sourcePath, FileInfo::targetPath));

  try {
    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<>();
    JavacFileManager fileManager =
        (JavacFileManager)
            compiler.getStandardFileManager(diagnostics, null, StandardCharsets.UTF_8);
    List<File> searchpath = classpathEntries.stream().map(File::new).collect(toList());
    fileManager.setLocation(StandardLocation.PLATFORM_CLASS_PATH, searchpath);
    fileManager.setLocation(StandardLocation.CLASS_PATH, searchpath);
    JavacTaskImpl task =
        (JavacTaskImpl)
            compiler.getTask(
                null,
                fileManager,
                diagnostics,
                // TODO(b/143213486): Remove -source 8 and figure out how to configure
                // SYSTEM_MODULES and MODULE_PATH to prevent searching for modules.
                ImmutableList.of("-source", "8"),
                null,
                fileManager.getJavaFileObjectsFromFiles(
                    targetPathBySourcePath.keySet().stream().map(File::new).collect(toList())));
    List<CompilationUnitTree> javacCompilationUnits = Lists.newArrayList(task.parse());
    task.analyze();
    if (hasErrors(diagnostics, javacCompilationUnits)) {
      return ImmutableList.of();
    }

    JavaEnvironment javaEnvironment =
        new JavaEnvironment(task.getContext(), FrontendConstants.WELL_KNOWN_CLASS_NAMES);
    List<CompilationUnit> compilationUnits =
        CompilationUnitBuilder.build(javacCompilationUnits, javaEnvironment);

    return compilationUnits;
  } catch (IOException e) {
    problems.fatal(FatalError.valueOf(e.getMessage()));
    return null;
  }
}
 
Example 18
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();
    }
}
 
Example 19
Source File: SourceAnalyzerTest.java    From netbeans with Apache License 2.0 4 votes vote down vote up
public void testConstructorReference() throws Exception {
    final FileObject libFile = FileUtil.toFileObject(TestFileUtils.writeFile(
         new File(FileUtil.toFile(src),"Lib.java"), //NOI18N
         "public class Lib {\n" +                   //NOI18N
         "}"));                                     //NOI18N
    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::new;\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.METHOD_REFERENCE,
                ClassIndexImpl.UsageType.TYPE_REFERENCE))));
    } finally {
        TransactionContext.get().rollBack();
    }
}
 
Example 20
Source File: SourceAnalyzerTest.java    From netbeans with Apache License 2.0 4 votes vote down vote up
public void testMethodReference() throws Exception {
    final FileObject libFile = FileUtil.toFileObject(TestFileUtils.writeFile(
         new File(FileUtil.toFile(src),"Lib.java"), //NOI18N
         "public class Lib {\n" +                   //NOI18N
         "    public static void foo(){}\n" +       //NOI18N
         "}"));                                     //NOI18N
    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.METHOD_REFERENCE,
                ClassIndexImpl.UsageType.TYPE_REFERENCE))));
    } finally {
        TransactionContext.get().rollBack();
    }
}