com.sun.source.util.TreePathScanner Java Examples

The following examples show how to use com.sun.source.util.TreePathScanner. 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: TreePruner.java    From bazel with Apache License 2.0 6 votes vote down vote up
private static void removeUnusedImports(JCCompilationUnit unit) {
  Set<String> usedNames = new HashSet<>();
  // TODO(cushon): consider folding this into PruningVisitor to avoid a second pass
  new TreePathScanner<Void, Void>() {
    @Override
    public Void visitImport(ImportTree importTree, Void usedSymbols) {
      return null;
    }

    @Override
    public Void visitIdentifier(IdentifierTree tree, Void unused) {
      if (tree == null) {
        return null;
      }
      usedNames.add(tree.getName().toString());
      return null;
    }
  }.scan(unit, null);
  com.sun.tools.javac.util.List<JCTree> replacements = com.sun.tools.javac.util.List.nil();
  for (JCTree def : unit.defs) {
    if (!def.hasTag(JCTree.Tag.IMPORT) || !isUnused(unit, usedNames, (JCImport) def)) {
      replacements = replacements.append(def);
    }
  }
  unit.defs = replacements;
}
 
Example #2
Source File: TypesCachesCleared.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
public boolean process(Set<? extends TypeElement> annotations,
                       RoundEnvironment roundEnv) {
    new TestPathScanner<Void>() {
        @Override
        public void visit(Void t) {
        }
    };
    TypeElement currentClass = elements.getTypeElement("TypesCachesCleared");
    Trees trees = Trees.instance(processingEnv);
    TreePath path = trees.getPath(currentClass);
    new TreePathScanner<Void, Void>() {
        @Override public Void visitClass(ClassTree node, Void p) {
            trees.getElement(getCurrentPath());
            return super.visitClass(node, p);
        }
    }.scan(path, null);
    return false;
}
 
Example #3
Source File: JavacParser.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private String treeToString(CompilationInfoImpl info, CompilationUnitTree cut) {
    StringBuilder dump = new StringBuilder();
    new TreePathScanner<Void, Void>() {
        @Override
        public Void scan(Tree tree, Void p) {
            if (tree == null) {
                dump.append("null,");
            } else {
                TreePath tp = new TreePath(getCurrentPath(), tree);
                dump.append(tree.getKind()).append(":");
                dump.append(Trees.instance(info.getJavacTask()).getSourcePositions().getStartPosition(tp.getCompilationUnit(), tree)).append(":");
                dump.append(Trees.instance(info.getJavacTask()).getSourcePositions().getEndPosition(tp.getCompilationUnit(), tree)).append(":");
                dump.append(String.valueOf(Trees.instance(info.getJavacTask()).getElement(tp))).append(":");
                dump.append(String.valueOf(Trees.instance(info.getJavacTask()).getTypeMirror(tp))).append(":");
                dump.append(",");
            }
            return super.scan(tree, p);
        }
    }.scan(cut, null);
    return dump.toString();
}
 
Example #4
Source File: PartialReparseTest.java    From netbeans with Apache License 2.0 6 votes vote down vote up
public void testAnonymousName() throws Exception {
    doRunTest("package test;\n" +
              "public class Test {\n" +
              "    private Object o = new Object() {};\n" +
              "    private void test() {\n" +
              "        new Object() {\n" +
              "        };" +
              "        final int i = 5;\n" +
              "        ^^\n" +
              "    }" +
              "}",
              "final int j = 5;\n",
              info -> {
                  new TreePathScanner<Void, Void>() {
                      public Void visitNewClass(NewClassTree tree, Void p) {
                          if (getCurrentPath().getParentPath().getLeaf().getKind() == Kind.METHOD) {
                              TypeElement el = (TypeElement) info.getTrees().getElement(new TreePath(getCurrentPath(), tree.getClassBody()));
                              assertEquals("test.Test$2", info.getElements().getBinaryName(el).toString());
                          }
                          return super.visitNewClass(tree, p);
                      }
                  }.scan(info.getCompilationUnit(), null);
              });
}
 
Example #5
Source File: ScopeTest.java    From hottub with GNU General Public License v2.0 5 votes vote down vote up
private static void verifyLambdaScopeCorrect(final String packageClause) throws Exception {
    JavacTool tool = JavacTool.create();
    JavaFileObject source = new SimpleJavaFileObject(URI.create("mem://Test.java"), Kind.SOURCE) {
        @Override public CharSequence getCharContent(boolean ignoreEncodingErrors) throws IOException {
            return packageClause + SOURCE_CODE;
        }
        @Override public boolean isNameCompatible(String simpleName, Kind kind) {
            return true;
        }
    };
    Iterable<? extends JavaFileObject> fos = Collections.singletonList(source);
    JavacTask task = tool.getTask(null, null, null, new ArrayList<String>(), null, fos);
    final Types types = JavacTypes.instance(((JavacTaskImpl) task).getContext());
    final Trees trees = Trees.instance(task);
    CompilationUnitTree cu = task.parse().iterator().next();

    task.analyze();

    new TreePathScanner<Void, Void>() {
        @Override public Void visitMemberSelect(MemberSelectTree node, Void p) {
            if (node.getIdentifier().contentEquals("correct")) {
                TypeMirror xType = trees.getTypeMirror(new TreePath(getCurrentPath(), node.getExpression()));
                Scope scope = trees.getScope(getCurrentPath());
                for (Element l : scope.getLocalElements()) {
                    if (!l.getSimpleName().contentEquals("x")) continue;
                    if (!types.isSameType(xType, l.asType())) {
                        throw new IllegalStateException("Incorrect variable type in scope: " + l.asType() + "; should be: " + xType);
                    }
                }
            }
            return super.visitMemberSelect(node, p);
        }
    }.scan(cu, null);
}
 
Example #6
Source File: ScopeTest.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
private static void verifyLambdaScopeCorrect(final String packageClause) throws Exception {
    JavacTool tool = JavacTool.create();
    JavaFileObject source = new SimpleJavaFileObject(URI.create("mem://Test.java"), Kind.SOURCE) {
        @Override public CharSequence getCharContent(boolean ignoreEncodingErrors) throws IOException {
            return packageClause + SOURCE_CODE;
        }
        @Override public boolean isNameCompatible(String simpleName, Kind kind) {
            return !"module-info".equals(simpleName);
        }
    };
    Iterable<? extends JavaFileObject> fos = Collections.singletonList(source);
    JavacTask task = tool.getTask(null, null, null, new ArrayList<String>(), null, fos);
    final Types types = JavacTypes.instance(((JavacTaskImpl) task).getContext());
    final Trees trees = Trees.instance(task);
    CompilationUnitTree cu = task.parse().iterator().next();

    task.analyze();

    new TreePathScanner<Void, Void>() {
        @Override public Void visitMemberSelect(MemberSelectTree node, Void p) {
            if (node.getIdentifier().contentEquals("correct")) {
                TypeMirror xType = trees.getTypeMirror(new TreePath(getCurrentPath(), node.getExpression()));
                Scope scope = trees.getScope(getCurrentPath());
                for (Element l : scope.getLocalElements()) {
                    if (!l.getSimpleName().contentEquals("x")) continue;
                    if (!types.isSameType(xType, l.asType())) {
                        throw new IllegalStateException("Incorrect variable type in scope: " + l.asType() + "; should be: " + xType);
                    }
                }
            }
            return super.visitMemberSelect(node, p);
        }
    }.scan(cu, null);
}
 
Example #7
Source File: ScopeTest.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 5 votes vote down vote up
private static void verifyLambdaScopeCorrect(final String packageClause) throws Exception {
    JavacTool tool = JavacTool.create();
    JavaFileObject source = new SimpleJavaFileObject(URI.create("mem://Test.java"), Kind.SOURCE) {
        @Override public CharSequence getCharContent(boolean ignoreEncodingErrors) throws IOException {
            return packageClause + SOURCE_CODE;
        }
        @Override public boolean isNameCompatible(String simpleName, Kind kind) {
            return true;
        }
    };
    Iterable<? extends JavaFileObject> fos = Collections.singletonList(source);
    JavacTask task = tool.getTask(null, null, null, new ArrayList<String>(), null, fos);
    final Types types = JavacTypes.instance(((JavacTaskImpl) task).getContext());
    final Trees trees = Trees.instance(task);
    CompilationUnitTree cu = task.parse().iterator().next();

    task.analyze();

    new TreePathScanner<Void, Void>() {
        @Override public Void visitMemberSelect(MemberSelectTree node, Void p) {
            if (node.getIdentifier().contentEquals("correct")) {
                TypeMirror xType = trees.getTypeMirror(new TreePath(getCurrentPath(), node.getExpression()));
                Scope scope = trees.getScope(getCurrentPath());
                for (Element l : scope.getLocalElements()) {
                    if (!l.getSimpleName().contentEquals("x")) continue;
                    if (!types.isSameType(xType, l.asType())) {
                        throw new IllegalStateException("Incorrect variable type in scope: " + l.asType() + "; should be: " + xType);
                    }
                }
            }
            return super.visitMemberSelect(node, p);
        }
    }.scan(cu, null);
}
 
Example #8
Source File: ScopeTest.java    From TencentKona-8 with GNU General Public License v2.0 5 votes vote down vote up
private static void verifyLambdaScopeCorrect(final String packageClause) throws Exception {
    JavacTool tool = JavacTool.create();
    JavaFileObject source = new SimpleJavaFileObject(URI.create("mem://Test.java"), Kind.SOURCE) {
        @Override public CharSequence getCharContent(boolean ignoreEncodingErrors) throws IOException {
            return packageClause + SOURCE_CODE;
        }
        @Override public boolean isNameCompatible(String simpleName, Kind kind) {
            return true;
        }
    };
    Iterable<? extends JavaFileObject> fos = Collections.singletonList(source);
    JavacTask task = tool.getTask(null, null, null, new ArrayList<String>(), null, fos);
    final Types types = JavacTypes.instance(((JavacTaskImpl) task).getContext());
    final Trees trees = Trees.instance(task);
    CompilationUnitTree cu = task.parse().iterator().next();

    task.analyze();

    new TreePathScanner<Void, Void>() {
        @Override public Void visitMemberSelect(MemberSelectTree node, Void p) {
            if (node.getIdentifier().contentEquals("correct")) {
                TypeMirror xType = trees.getTypeMirror(new TreePath(getCurrentPath(), node.getExpression()));
                Scope scope = trees.getScope(getCurrentPath());
                for (Element l : scope.getLocalElements()) {
                    if (!l.getSimpleName().contentEquals("x")) continue;
                    if (!types.isSameType(xType, l.asType())) {
                        throw new IllegalStateException("Incorrect variable type in scope: " + l.asType() + "; should be: " + xType);
                    }
                }
            }
            return super.visitMemberSelect(node, p);
        }
    }.scan(cu, null);
}
 
Example #9
Source File: NBAttrTest.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public void testNETBEANS_228() throws Exception {
    String code = "package test; public class Test { Object t() { return new Undef() { public void test() { test(); } }; } }";
    Pair<JavacTask, CompilationUnitTree> parsed = compile(code);

    new TreePathScanner<Void, Void>() {
        public Void visitMethodInvocation(MethodInvocationTree tree, Void p) {
            Trees trees = Trees.instance(parsed.first());
            assertNotNull(trees.getElement(getCurrentPath()));
            return super.visitMethodInvocation(tree, p);
        }
    }.scan(parsed.second(), null);
}
 
Example #10
Source File: ScopeTest.java    From openjdk-8-source with GNU General Public License v2.0 5 votes vote down vote up
private static void verifyLambdaScopeCorrect(final String packageClause) throws Exception {
    JavacTool tool = JavacTool.create();
    JavaFileObject source = new SimpleJavaFileObject(URI.create("mem://Test.java"), Kind.SOURCE) {
        @Override public CharSequence getCharContent(boolean ignoreEncodingErrors) throws IOException {
            return packageClause + SOURCE_CODE;
        }
        @Override public boolean isNameCompatible(String simpleName, Kind kind) {
            return true;
        }
    };
    Iterable<? extends JavaFileObject> fos = Collections.singletonList(source);
    JavacTask task = tool.getTask(null, null, null, new ArrayList<String>(), null, fos);
    final Types types = JavacTypes.instance(((JavacTaskImpl) task).getContext());
    final Trees trees = Trees.instance(task);
    CompilationUnitTree cu = task.parse().iterator().next();

    task.analyze();

    new TreePathScanner<Void, Void>() {
        @Override public Void visitMemberSelect(MemberSelectTree node, Void p) {
            if (node.getIdentifier().contentEquals("correct")) {
                TypeMirror xType = trees.getTypeMirror(new TreePath(getCurrentPath(), node.getExpression()));
                Scope scope = trees.getScope(getCurrentPath());
                for (Element l : scope.getLocalElements()) {
                    if (!l.getSimpleName().contentEquals("x")) continue;
                    if (!types.isSameType(xType, l.asType())) {
                        throw new IllegalStateException("Incorrect variable type in scope: " + l.asType() + "; should be: " + xType);
                    }
                }
            }
            return super.visitMemberSelect(node, p);
        }
    }.scan(cu, null);
}
 
Example #11
Source File: ElementHandleTest.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public void testAnonymousFromSource() throws Exception {
    try (PrintWriter out = new PrintWriter ( new OutputStreamWriter (data.getOutputStream()))) {
        out.println ("public class Test {" +
                    "    public void test() {" +
                    "        Object o = new Object() {};" +
                    "    }" +
                     "}");
    }
    final JavaSource js = JavaSource.create(ClasspathInfo.create(ClassPathProviderImpl.getDefault().findClassPath(data,ClassPath.BOOT), ClassPathProviderImpl.getDefault().findClassPath(data, ClassPath.COMPILE), null), data);
    assertNotNull(js);
    AtomicBoolean didTest = new AtomicBoolean();

    js.runUserActionTask(new Task<CompilationController>() {
        public void run(CompilationController parameter) throws Exception {
            parameter.toPhase(JavaSource.Phase.RESOLVED);
            new TreePathScanner<Void, Void>() {
                @Override
                public Void visitNewClass(NewClassTree node, Void p) {
                    TreePath clazz = new TreePath(getCurrentPath(), node.getClassBody());
                    Element el = parameter.getTrees().getElement(clazz);
                    assertNotNull(el);
                    assertNotNull(ElementHandle.create(el).resolve(parameter));
                    didTest.set(true);
                    return super.visitNewClass(node, p);
                }
            }.scan(parameter.getCompilationUnit(), null);
        }
    }, true);

    assertTrue(didTest.get());
}
 
Example #12
Source File: PartialReparseTest.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private static List<TreeDescription> dumpTree(CompilationInfo info) {
    List<TreeDescription> result = new ArrayList<>();
    new TreePathScanner<Void, Void>() {
        @Override
        public Void scan(Tree tree, Void p) {
            if (tree == null) {
                result.add(null);
            } else {
                TreePath tp = new TreePath(getCurrentPath(), tree);
                Element el = info.getTrees().getElement(tp);
                StringBuilder elDesc = new StringBuilder();
                if (el != null) {
                    elDesc.append(el.getKind().name());
                    while (el != null && !SUPPORTED_ELEMENTS.contains(el.getKind())) {
                        elDesc.append(":");
                        elDesc.append(el.getSimpleName());
                        el = el.getEnclosingElement();
                    }
                    if (el != null) {
                        for (String part : SourceUtils.getJVMSignature(ElementHandle.create(el))) {
                            elDesc.append(":");
                            elDesc.append(part);
                        }
                    }
                }
                result.add(new TreeDescription(tree.getKind(),
                                               info.getTrees().getSourcePositions().getStartPosition(info.getCompilationUnit(), tree),
                                               info.getTrees().getSourcePositions().getEndPosition(info.getCompilationUnit(), tree),
                                               elDesc.toString(),
                                               String.valueOf(info.getTrees().getTypeMirror(tp)),
                                               info.getTrees().getDocComment(tp)));
            }
            return super.scan(tree, p);
        }
    }.scan(info.getCompilationUnit(), null);
    return result;
}
 
Example #13
Source File: ScopeTest.java    From openjdk-8 with GNU General Public License v2.0 5 votes vote down vote up
private static void verifyLambdaScopeCorrect(final String packageClause) throws Exception {
    JavacTool tool = JavacTool.create();
    JavaFileObject source = new SimpleJavaFileObject(URI.create("mem://Test.java"), Kind.SOURCE) {
        @Override public CharSequence getCharContent(boolean ignoreEncodingErrors) throws IOException {
            return packageClause + SOURCE_CODE;
        }
        @Override public boolean isNameCompatible(String simpleName, Kind kind) {
            return true;
        }
    };
    Iterable<? extends JavaFileObject> fos = Collections.singletonList(source);
    JavacTask task = tool.getTask(null, null, null, new ArrayList<String>(), null, fos);
    final Types types = JavacTypes.instance(((JavacTaskImpl) task).getContext());
    final Trees trees = Trees.instance(task);
    CompilationUnitTree cu = task.parse().iterator().next();

    task.analyze();

    new TreePathScanner<Void, Void>() {
        @Override public Void visitMemberSelect(MemberSelectTree node, Void p) {
            if (node.getIdentifier().contentEquals("correct")) {
                TypeMirror xType = trees.getTypeMirror(new TreePath(getCurrentPath(), node.getExpression()));
                Scope scope = trees.getScope(getCurrentPath());
                for (Element l : scope.getLocalElements()) {
                    if (!l.getSimpleName().contentEquals("x")) continue;
                    if (!types.isSameType(xType, l.asType())) {
                        throw new IllegalStateException("Incorrect variable type in scope: " + l.asType() + "; should be: " + xType);
                    }
                }
            }
            return super.visitMemberSelect(node, p);
        }
    }.scan(cu, null);
}
 
Example #14
Source File: ScopeTest.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
private static void verifyLambdaScopeCorrect(final String packageClause) throws Exception {
    JavacTool tool = JavacTool.create();
    JavaFileObject source = new SimpleJavaFileObject(URI.create("mem://Test.java"), Kind.SOURCE) {
        @Override public CharSequence getCharContent(boolean ignoreEncodingErrors) throws IOException {
            return packageClause + SOURCE_CODE;
        }
        @Override public boolean isNameCompatible(String simpleName, Kind kind) {
            return true;
        }
    };
    Iterable<? extends JavaFileObject> fos = Collections.singletonList(source);
    JavacTask task = tool.getTask(null, null, null, new ArrayList<String>(), null, fos);
    final Types types = JavacTypes.instance(((JavacTaskImpl) task).getContext());
    final Trees trees = Trees.instance(task);
    CompilationUnitTree cu = task.parse().iterator().next();

    task.analyze();

    new TreePathScanner<Void, Void>() {
        @Override public Void visitMemberSelect(MemberSelectTree node, Void p) {
            if (node.getIdentifier().contentEquals("correct")) {
                TypeMirror xType = trees.getTypeMirror(new TreePath(getCurrentPath(), node.getExpression()));
                Scope scope = trees.getScope(getCurrentPath());
                for (Element l : scope.getLocalElements()) {
                    if (!l.getSimpleName().contentEquals("x")) continue;
                    if (!types.isSameType(xType, l.asType())) {
                        throw new IllegalStateException("Incorrect variable type in scope: " + l.asType() + "; should be: " + xType);
                    }
                }
            }
            return super.visitMemberSelect(node, p);
        }
    }.scan(cu, null);
}
 
Example #15
Source File: ModelBuilder.java    From vertx-codetrans with Apache License 2.0 5 votes vote down vote up
private VariableScope resolvescope(VisitContext context, ElementKind kind, final String name) {
  VariableScope scope;
  switch (kind) {
    case LOCAL_VARIABLE:
      scope = VariableScope.VARIABLE;
      break;
    case PARAMETER:
      scope = VariableScope.PARAMETER;
      break;
    case FIELD:
      AtomicReference<VariableScope> resolvedScope = new AtomicReference<>(VariableScope.GLOBAL);
      new TreePathScanner<Void, Void>() {
        @Override
        public Void visitVariable(VariableTree node, Void aVoid) {
          if (node.getName().toString().equals(name)) {
            resolvedScope.set(VariableScope.FIELD);
          }
          return null;
        };
      }.scan(path, null);
      if (resolvedScope.get() == VariableScope.FIELD) {
        context.getReferencedFields().add(name);
      }
      scope = resolvedScope.get();
      break;
    default:
      throw new UnsupportedOperationException("Unsupported kind " + kind);
  }
  return scope;
}
 
Example #16
Source File: ScopeTest.java    From jdk8u60 with GNU General Public License v2.0 5 votes vote down vote up
private static void verifyLambdaScopeCorrect(final String packageClause) throws Exception {
    JavacTool tool = JavacTool.create();
    JavaFileObject source = new SimpleJavaFileObject(URI.create("mem://Test.java"), Kind.SOURCE) {
        @Override public CharSequence getCharContent(boolean ignoreEncodingErrors) throws IOException {
            return packageClause + SOURCE_CODE;
        }
        @Override public boolean isNameCompatible(String simpleName, Kind kind) {
            return true;
        }
    };
    Iterable<? extends JavaFileObject> fos = Collections.singletonList(source);
    JavacTask task = tool.getTask(null, null, null, new ArrayList<String>(), null, fos);
    final Types types = JavacTypes.instance(((JavacTaskImpl) task).getContext());
    final Trees trees = Trees.instance(task);
    CompilationUnitTree cu = task.parse().iterator().next();

    task.analyze();

    new TreePathScanner<Void, Void>() {
        @Override public Void visitMemberSelect(MemberSelectTree node, Void p) {
            if (node.getIdentifier().contentEquals("correct")) {
                TypeMirror xType = trees.getTypeMirror(new TreePath(getCurrentPath(), node.getExpression()));
                Scope scope = trees.getScope(getCurrentPath());
                for (Element l : scope.getLocalElements()) {
                    if (!l.getSimpleName().contentEquals("x")) continue;
                    if (!types.isSameType(xType, l.asType())) {
                        throw new IllegalStateException("Incorrect variable type in scope: " + l.asType() + "; should be: " + xType);
                    }
                }
            }
            return super.visitMemberSelect(node, p);
        }
    }.scan(cu, null);
}
 
Example #17
Source File: CheckErrorsForSource7.java    From hottub with GNU General Public License v2.0 4 votes vote down vote up
private void run(String... args) throws IOException, URISyntaxException {
    //the first and only parameter must be the name of the file to be analyzed:
    if (args.length != 1) throw new IllegalStateException("Must provide source file!");
    File testSrc = new File(System.getProperty("test.src"));
    File testFile = new File(testSrc, args[0]);
    if (!testFile.canRead()) throw new IllegalStateException("Cannot read the test source");
    JavacFileManager fm = JavacTool.create().getStandardFileManager(null, null, null);

    //gather spans of the @TA annotations into typeAnnotationSpans:
    JavacTask task = JavacTool.create().getTask(null,
                                                fm,
                                                null,
                                                Collections.<String>emptyList(),
                                                null,
                                                fm.getJavaFileObjects(testFile));
    final Trees trees = Trees.instance(task);
    final CompilationUnitTree cut = task.parse().iterator().next();
    final List<int[]> typeAnnotationSpans = new ArrayList<>();

    new TreePathScanner<Void, Void>() {
        @Override
        public Void visitAnnotation(AnnotationTree node, Void p) {
            if (node.getAnnotationType().getKind() == Kind.IDENTIFIER &&
                ((IdentifierTree) node.getAnnotationType()).getName().contentEquals("TA")) {
                int start = (int) trees.getSourcePositions().getStartPosition(cut, node);
                int end = (int) trees.getSourcePositions().getEndPosition(cut, node);
                typeAnnotationSpans.add(new int[] {start, end});
            }
            return null;
        }
    }.scan(cut, null);

    //sort the spans in the reverse order, to simplify removing them from the source:
    Collections.sort(typeAnnotationSpans, new Comparator<int[]>() {
        @Override
        public int compare(int[] o1, int[] o2) {
            return o2[0] - o1[0];
        }
    });

    //verify the errors are produce correctly:
    String originalSource = cut.getSourceFile().getCharContent(false).toString();

    for (int[] toKeep : typeAnnotationSpans) {
        //prepare updated source code by removing all the annotations except the toKeep one:
        String updated = originalSource;

        for (int[] span : typeAnnotationSpans) {
            if (span == toKeep) continue;

            updated = updated.substring(0, span[0]) + updated.substring(span[1]);
        }

        //parse and verify:
        JavaFileObject updatedFile = new TestFO(cut.getSourceFile().toUri(), updated);
        DiagnosticCollector<JavaFileObject> errors = new DiagnosticCollector<>();
        JavacTask task2 = JavacTool.create().getTask(null,
                                                     fm,
                                                     errors,
                                                     Arrays.asList("-source", "7"),
                                                     null,
                                                     Arrays.asList(updatedFile));
        task2.parse();

        boolean found = false;

        for (Diagnostic<? extends JavaFileObject> d : errors.getDiagnostics()) {
            if (d.getKind() == Diagnostic.Kind.ERROR && EXPECTED_ERRORS.contains(d.getCode())) {
                if (found) {
                    throw new IllegalStateException("More than one expected error found.");
                }
                found = true;
            }
        }

        if (!found)
            throw new IllegalStateException("Did not produce proper errors for: " + updated);
    }
}
 
Example #18
Source File: ModulesHint.java    From netbeans with Apache License 2.0 4 votes vote down vote up
static void computeModulesAndPackages(final CompilationInfo info,
                                      CompilationUnitTree cut,
                                      Map<String, Set<String>> module2UsedUnexportedPackages,
                                      final Set<TypeElement> seenClasses,
                                      Set<Project> seenProjects,
                                      Set<CompilationUnitTree> seen) {
    if (!seen.add(cut))
        return ;

    final Set<TypeElement> classes = new HashSet<>();

    new TreePathScanner<Void, Void>() {
        @Override
        public Void scan(Tree tree, Void p) {
            if (tree == null)
                return null;

            Element el = info.getTrees().getElement(new TreePath(getCurrentPath(), tree));

            if (el != null && el.getKind() != ElementKind.PACKAGE && el.getKind() != ElementKind.OTHER) {
                TypeElement outermost = info.getElementUtilities().outermostTypeElement(el);
                if (outermost != null) {
                    if (seenClasses.add(outermost)) {
                        classes.add(outermost);
                    }
                } else ;//XXX: array .length!
            }

            return super.scan(tree, p);
        }
    }.scan(cut, null);

    Map<FileObject, Set<String>> module2Packages = new HashMap<>();

    for (TypeElement outtermost : classes) {
        FileObject file = SourceUtils.getFile(ElementHandle.create(outtermost), info.getClasspathInfo());
        if (file == null) {
            continue;
        }

        Project prj = FileOwnerQuery.getOwner(file);

        if (prj != null && /*XXX*/FileUtil.isParentOf(prj.getProjectDirectory(), file)) {
            FileObject prjDir = prj.getProjectDirectory();
            Set<String> currentModulePackages = module2Packages.get(prjDir);

            if (currentModulePackages == null) {
                module2Packages.put(prjDir, currentModulePackages = new HashSet<>());
            }

            currentModulePackages.add(info.getElements().getPackageOf(outtermost).getQualifiedName().toString());

            seenProjects.add(prj);
        } else {
            TreePath tp = info.getTrees().getPath(outtermost);

            if (tp != null) {
                computeModulesAndPackages(info, tp.getCompilationUnit(), module2UsedUnexportedPackages, seenClasses, seenProjects, seen);
            }
        }
    }

    for (Map.Entry<FileObject, Set<String>> e : module2Packages.entrySet()) {
        FileObject moduleInfo = BuildUtils.getFileObject(e.getKey(), "share/classes/module-info.java");
        if (moduleInfo == null) { //XXX
            continue;
        }
        Set<String> exported = readExports(moduleInfo);

        for (Iterator<String> it = e.getValue().iterator(); it.hasNext();) {
            String pack = it.next();

            if (exported.contains(pack)) {
                it.remove();
            }
        }

        String moduleName = e.getKey().getNameExt();
        Set<String> currentUnexportedpackages = module2UsedUnexportedPackages.get(moduleName);

        if (currentUnexportedpackages == null) {
            module2UsedUnexportedPackages.put(moduleName, currentUnexportedpackages = new HashSet<>());
        }

        currentUnexportedpackages.addAll(e.getValue());
    }
}
 
Example #19
Source File: CheckErrorsForSource7.java    From openjdk-jdk9 with GNU General Public License v2.0 4 votes vote down vote up
private void run(String... args) throws IOException, URISyntaxException {
    //the first and only parameter must be the name of the file to be analyzed:
    if (args.length != 1) throw new IllegalStateException("Must provide source file!");
    File testSrc = new File(System.getProperty("test.src"));
    File testFile = new File(testSrc, args[0]);
    if (!testFile.canRead()) throw new IllegalStateException("Cannot read the test source");
    try (JavacFileManager fm = JavacTool.create().getStandardFileManager(null, null, null)) {

        //gather spans of the @TA annotations into typeAnnotationSpans:
        JavacTask task = JavacTool.create().getTask(null,
                                                    fm,
                                                    null,
                                                    Collections.<String>emptyList(),
                                                    null,
                                                    fm.getJavaFileObjects(testFile));
        final Trees trees = Trees.instance(task);
        final CompilationUnitTree cut = task.parse().iterator().next();
        final List<int[]> typeAnnotationSpans = new ArrayList<>();

        new TreePathScanner<Void, Void>() {
            @Override
            public Void visitAnnotation(AnnotationTree node, Void p) {
                if (node.getAnnotationType().getKind() == Kind.IDENTIFIER &&
                    ((IdentifierTree) node.getAnnotationType()).getName().contentEquals("TA")) {
                    int start = (int) trees.getSourcePositions().getStartPosition(cut, node);
                    int end = (int) trees.getSourcePositions().getEndPosition(cut, node);
                    typeAnnotationSpans.add(new int[] {start, end});
                }
                return null;
            }
        }.scan(cut, null);

        //sort the spans in the reverse order, to simplify removing them from the source:
        Collections.sort(typeAnnotationSpans, new Comparator<int[]>() {
            @Override
            public int compare(int[] o1, int[] o2) {
                return o2[0] - o1[0];
            }
        });

        //verify the errors are produce correctly:
        String originalSource = cut.getSourceFile().getCharContent(false).toString();

        for (int[] toKeep : typeAnnotationSpans) {
            //prepare updated source code by removing all the annotations except the toKeep one:
            String updated = originalSource;

            for (int[] span : typeAnnotationSpans) {
                if (span == toKeep) continue;

                updated = updated.substring(0, span[0]) + updated.substring(span[1]);
            }

            //parse and verify:
            JavaFileObject updatedFile = new TestFO(cut.getSourceFile().toUri(), updated);
            DiagnosticCollector<JavaFileObject> errors = new DiagnosticCollector<>();
            JavacTask task2 = JavacTool.create().getTask(null,
                                                         fm,
                                                         errors,
                                                         Arrays.asList("-source", "7"),
                                                         null,
                                                         Arrays.asList(updatedFile));
            task2.parse();

            boolean found = false;

            for (Diagnostic<? extends JavaFileObject> d : errors.getDiagnostics()) {
                if (d.getKind() == Diagnostic.Kind.ERROR && EXPECTED_ERRORS.contains(d.getCode())) {
                    if (found) {
                        throw new IllegalStateException("More than one expected error found.");
                    }
                    found = true;
                }
            }

            if (!found)
                throw new IllegalStateException("Did not produce proper errors for: " + updated);
        }
    }
}
 
Example #20
Source File: CheckErrorsForSource7.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 4 votes vote down vote up
private void run(String... args) throws IOException, URISyntaxException {
    //the first and only parameter must be the name of the file to be analyzed:
    if (args.length != 1) throw new IllegalStateException("Must provide source file!");
    File testSrc = new File(System.getProperty("test.src"));
    File testFile = new File(testSrc, args[0]);
    if (!testFile.canRead()) throw new IllegalStateException("Cannot read the test source");
    JavacFileManager fm = JavacTool.create().getStandardFileManager(null, null, null);

    //gather spans of the @TA annotations into typeAnnotationSpans:
    JavacTask task = JavacTool.create().getTask(null,
                                                fm,
                                                null,
                                                Collections.<String>emptyList(),
                                                null,
                                                fm.getJavaFileObjects(testFile));
    final Trees trees = Trees.instance(task);
    final CompilationUnitTree cut = task.parse().iterator().next();
    final List<int[]> typeAnnotationSpans = new ArrayList<>();

    new TreePathScanner<Void, Void>() {
        @Override
        public Void visitAnnotation(AnnotationTree node, Void p) {
            if (node.getAnnotationType().getKind() == Kind.IDENTIFIER &&
                ((IdentifierTree) node.getAnnotationType()).getName().contentEquals("TA")) {
                int start = (int) trees.getSourcePositions().getStartPosition(cut, node);
                int end = (int) trees.getSourcePositions().getEndPosition(cut, node);
                typeAnnotationSpans.add(new int[] {start, end});
            }
            return null;
        }
    }.scan(cut, null);

    //sort the spans in the reverse order, to simplify removing them from the source:
    Collections.sort(typeAnnotationSpans, new Comparator<int[]>() {
        @Override
        public int compare(int[] o1, int[] o2) {
            return o2[0] - o1[0];
        }
    });

    //verify the errors are produce correctly:
    String originalSource = cut.getSourceFile().getCharContent(false).toString();

    for (int[] toKeep : typeAnnotationSpans) {
        //prepare updated source code by removing all the annotations except the toKeep one:
        String updated = originalSource;

        for (int[] span : typeAnnotationSpans) {
            if (span == toKeep) continue;

            updated = updated.substring(0, span[0]) + updated.substring(span[1]);
        }

        //parse and verify:
        JavaFileObject updatedFile = new TestFO(cut.getSourceFile().toUri(), updated);
        DiagnosticCollector<JavaFileObject> errors = new DiagnosticCollector<>();
        JavacTask task2 = JavacTool.create().getTask(null,
                                                     fm,
                                                     errors,
                                                     Arrays.asList("-source", "7"),
                                                     null,
                                                     Arrays.asList(updatedFile));
        task2.parse();

        boolean found = false;

        for (Diagnostic<? extends JavaFileObject> d : errors.getDiagnostics()) {
            if (d.getKind() == Diagnostic.Kind.ERROR && EXPECTED_ERRORS.contains(d.getCode())) {
                if (found) {
                    throw new IllegalStateException("More than one expected error found.");
                }
                found = true;
            }
        }

        if (!found)
            throw new IllegalStateException("Did not produce proper errors for: " + updated);
    }
}
 
Example #21
Source File: TreeUtilitiesTest.java    From netbeans with Apache License 2.0 4 votes vote down vote up
public void testNotUsingLiveScope() throws Exception {
    try {
        SourceVersion.valueOf("RELEASE_12");
    } catch (IllegalArgumentException ex) {
        //this test cannot pass on JDK <12, as javac there does not allow variables to own other variables
        return ;
    }
    ClassPath boot = ClassPathSupport.createClassPath(SourceUtilsTestUtil.getBootClassPath().toArray(new URL[0]));
    FileObject testFile = FileUtil.createData(FileUtil.createMemoryFileSystem().getRoot(), "Test.java");
    try (Writer w = new OutputStreamWriter(testFile.getOutputStream())) {
        w.append("import java.lang.String;\n" +
                 "public class Test {\n" +
                 "    void test(boolean b) {\n" +
                 "        int i1;\n" +
                 "        int i2;\n" +
                 "        int i3;\n" +
                 "        int i4;\n" +
                 "        int i5;\n" +
                 "        int i6;\n" +
                 "        int scopeHere = 0;\n" +
                 "    }\n" +
                 "}\n");
    }
    JavaSource js = JavaSource.create(ClasspathInfo.create(boot, ClassPath.EMPTY, ClassPath.EMPTY), testFile);
    js.runUserActionTask(new Task<CompilationController>() {
        @Override
        public void run(CompilationController parameter) throws Exception {
            parameter.toPhase(Phase.RESOLVED);
            TreePath[] path = new TreePath[1];
            new TreePathScanner<Void, Void>() {
                @Override
                public Void visitVariable(VariableTree node, Void p) {
                    if (node.getName().contentEquals("scopeHere")) {
                        path[0] = new TreePath(getCurrentPath(), node.getInitializer());
                    }
                    return super.visitVariable(node, p);
                }
            }.scan(parameter.getCompilationUnit(), null);
            Scope scope = parameter.getTrees().getScope(path[0]);
            StatementTree st = parameter.getTreeUtilities().parseStatement("{ String t; }", new SourcePositions[1]);
            assertEquals(Kind.BLOCK, st.getKind());
            parameter.getTreeUtilities().attributeTree(st, scope);
        }
    }, true);
}
 
Example #22
Source File: CheckErrorsForSource7.java    From openjdk-jdk8u with GNU General Public License v2.0 4 votes vote down vote up
private void run(String... args) throws IOException, URISyntaxException {
    //the first and only parameter must be the name of the file to be analyzed:
    if (args.length != 1) throw new IllegalStateException("Must provide source file!");
    File testSrc = new File(System.getProperty("test.src"));
    File testFile = new File(testSrc, args[0]);
    if (!testFile.canRead()) throw new IllegalStateException("Cannot read the test source");
    JavacFileManager fm = JavacTool.create().getStandardFileManager(null, null, null);

    //gather spans of the @TA annotations into typeAnnotationSpans:
    JavacTask task = JavacTool.create().getTask(null,
                                                fm,
                                                null,
                                                Collections.<String>emptyList(),
                                                null,
                                                fm.getJavaFileObjects(testFile));
    final Trees trees = Trees.instance(task);
    final CompilationUnitTree cut = task.parse().iterator().next();
    final List<int[]> typeAnnotationSpans = new ArrayList<>();

    new TreePathScanner<Void, Void>() {
        @Override
        public Void visitAnnotation(AnnotationTree node, Void p) {
            if (node.getAnnotationType().getKind() == Kind.IDENTIFIER &&
                ((IdentifierTree) node.getAnnotationType()).getName().contentEquals("TA")) {
                int start = (int) trees.getSourcePositions().getStartPosition(cut, node);
                int end = (int) trees.getSourcePositions().getEndPosition(cut, node);
                typeAnnotationSpans.add(new int[] {start, end});
            }
            return null;
        }
    }.scan(cut, null);

    //sort the spans in the reverse order, to simplify removing them from the source:
    Collections.sort(typeAnnotationSpans, new Comparator<int[]>() {
        @Override
        public int compare(int[] o1, int[] o2) {
            return o2[0] - o1[0];
        }
    });

    //verify the errors are produce correctly:
    String originalSource = cut.getSourceFile().getCharContent(false).toString();

    for (int[] toKeep : typeAnnotationSpans) {
        //prepare updated source code by removing all the annotations except the toKeep one:
        String updated = originalSource;

        for (int[] span : typeAnnotationSpans) {
            if (span == toKeep) continue;

            updated = updated.substring(0, span[0]) + updated.substring(span[1]);
        }

        //parse and verify:
        JavaFileObject updatedFile = new TestFO(cut.getSourceFile().toUri(), updated);
        DiagnosticCollector<JavaFileObject> errors = new DiagnosticCollector<>();
        JavacTask task2 = JavacTool.create().getTask(null,
                                                     fm,
                                                     errors,
                                                     Arrays.asList("-source", "7"),
                                                     null,
                                                     Arrays.asList(updatedFile));
        task2.parse();

        boolean found = false;

        for (Diagnostic<? extends JavaFileObject> d : errors.getDiagnostics()) {
            if (d.getKind() == Diagnostic.Kind.ERROR && EXPECTED_ERRORS.contains(d.getCode())) {
                if (found) {
                    throw new IllegalStateException("More than one expected error found.");
                }
                found = true;
            }
        }

        if (!found)
            throw new IllegalStateException("Did not produce proper errors for: " + updated);
    }
}
 
Example #23
Source File: CheckErrorsForSource7.java    From jdk8u60 with GNU General Public License v2.0 4 votes vote down vote up
private void run(String... args) throws IOException, URISyntaxException {
    //the first and only parameter must be the name of the file to be analyzed:
    if (args.length != 1) throw new IllegalStateException("Must provide source file!");
    File testSrc = new File(System.getProperty("test.src"));
    File testFile = new File(testSrc, args[0]);
    if (!testFile.canRead()) throw new IllegalStateException("Cannot read the test source");
    JavacFileManager fm = JavacTool.create().getStandardFileManager(null, null, null);

    //gather spans of the @TA annotations into typeAnnotationSpans:
    JavacTask task = JavacTool.create().getTask(null,
                                                fm,
                                                null,
                                                Collections.<String>emptyList(),
                                                null,
                                                fm.getJavaFileObjects(testFile));
    final Trees trees = Trees.instance(task);
    final CompilationUnitTree cut = task.parse().iterator().next();
    final List<int[]> typeAnnotationSpans = new ArrayList<>();

    new TreePathScanner<Void, Void>() {
        @Override
        public Void visitAnnotation(AnnotationTree node, Void p) {
            if (node.getAnnotationType().getKind() == Kind.IDENTIFIER &&
                ((IdentifierTree) node.getAnnotationType()).getName().contentEquals("TA")) {
                int start = (int) trees.getSourcePositions().getStartPosition(cut, node);
                int end = (int) trees.getSourcePositions().getEndPosition(cut, node);
                typeAnnotationSpans.add(new int[] {start, end});
            }
            return null;
        }
    }.scan(cut, null);

    //sort the spans in the reverse order, to simplify removing them from the source:
    Collections.sort(typeAnnotationSpans, new Comparator<int[]>() {
        @Override
        public int compare(int[] o1, int[] o2) {
            return o2[0] - o1[0];
        }
    });

    //verify the errors are produce correctly:
    String originalSource = cut.getSourceFile().getCharContent(false).toString();

    for (int[] toKeep : typeAnnotationSpans) {
        //prepare updated source code by removing all the annotations except the toKeep one:
        String updated = originalSource;

        for (int[] span : typeAnnotationSpans) {
            if (span == toKeep) continue;

            updated = updated.substring(0, span[0]) + updated.substring(span[1]);
        }

        //parse and verify:
        JavaFileObject updatedFile = new TestFO(cut.getSourceFile().toUri(), updated);
        DiagnosticCollector<JavaFileObject> errors = new DiagnosticCollector<>();
        JavacTask task2 = JavacTool.create().getTask(null,
                                                     fm,
                                                     errors,
                                                     Arrays.asList("-source", "7"),
                                                     null,
                                                     Arrays.asList(updatedFile));
        task2.parse();

        boolean found = false;

        for (Diagnostic<? extends JavaFileObject> d : errors.getDiagnostics()) {
            if (d.getKind() == Diagnostic.Kind.ERROR && EXPECTED_ERRORS.contains(d.getCode())) {
                if (found) {
                    throw new IllegalStateException("More than one expected error found.");
                }
                found = true;
            }
        }

        if (!found)
            throw new IllegalStateException("Did not produce proper errors for: " + updated);
    }
}
 
Example #24
Source File: CheckErrorsForSource7.java    From TencentKona-8 with GNU General Public License v2.0 4 votes vote down vote up
private void run(String... args) throws IOException, URISyntaxException {
    //the first and only parameter must be the name of the file to be analyzed:
    if (args.length != 1) throw new IllegalStateException("Must provide source file!");
    File testSrc = new File(System.getProperty("test.src"));
    File testFile = new File(testSrc, args[0]);
    if (!testFile.canRead()) throw new IllegalStateException("Cannot read the test source");
    JavacFileManager fm = JavacTool.create().getStandardFileManager(null, null, null);

    //gather spans of the @TA annotations into typeAnnotationSpans:
    JavacTask task = JavacTool.create().getTask(null,
                                                fm,
                                                null,
                                                Collections.<String>emptyList(),
                                                null,
                                                fm.getJavaFileObjects(testFile));
    final Trees trees = Trees.instance(task);
    final CompilationUnitTree cut = task.parse().iterator().next();
    final List<int[]> typeAnnotationSpans = new ArrayList<>();

    new TreePathScanner<Void, Void>() {
        @Override
        public Void visitAnnotation(AnnotationTree node, Void p) {
            if (node.getAnnotationType().getKind() == Kind.IDENTIFIER &&
                ((IdentifierTree) node.getAnnotationType()).getName().contentEquals("TA")) {
                int start = (int) trees.getSourcePositions().getStartPosition(cut, node);
                int end = (int) trees.getSourcePositions().getEndPosition(cut, node);
                typeAnnotationSpans.add(new int[] {start, end});
            }
            return null;
        }
    }.scan(cut, null);

    //sort the spans in the reverse order, to simplify removing them from the source:
    Collections.sort(typeAnnotationSpans, new Comparator<int[]>() {
        @Override
        public int compare(int[] o1, int[] o2) {
            return o2[0] - o1[0];
        }
    });

    //verify the errors are produce correctly:
    String originalSource = cut.getSourceFile().getCharContent(false).toString();

    for (int[] toKeep : typeAnnotationSpans) {
        //prepare updated source code by removing all the annotations except the toKeep one:
        String updated = originalSource;

        for (int[] span : typeAnnotationSpans) {
            if (span == toKeep) continue;

            updated = updated.substring(0, span[0]) + updated.substring(span[1]);
        }

        //parse and verify:
        JavaFileObject updatedFile = new TestFO(cut.getSourceFile().toUri(), updated);
        DiagnosticCollector<JavaFileObject> errors = new DiagnosticCollector<>();
        JavacTask task2 = JavacTool.create().getTask(null,
                                                     fm,
                                                     errors,
                                                     Arrays.asList("-source", "7"),
                                                     null,
                                                     Arrays.asList(updatedFile));
        task2.parse();

        boolean found = false;

        for (Diagnostic<? extends JavaFileObject> d : errors.getDiagnostics()) {
            if (d.getKind() == Diagnostic.Kind.ERROR && EXPECTED_ERRORS.contains(d.getCode())) {
                if (found) {
                    throw new IllegalStateException("More than one expected error found.");
                }
                found = true;
            }
        }

        if (!found)
            throw new IllegalStateException("Did not produce proper errors for: " + updated);
    }
}