• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

Java TreePathScanner类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Java中com.sun.source.util.TreePathScanner的典型用法代码示例。如果您正苦于以下问题:Java TreePathScanner类的具体用法?Java TreePathScanner怎么用?Java TreePathScanner使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。



TreePathScanner类属于com.sun.source.util包,在下文中一共展示了TreePathScanner类的14个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Java代码示例。

示例1: process

import com.sun.source.util.TreePathScanner; //导入依赖的package包/类
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;
}
 
开发者ID:AdoptOpenJDK,项目名称:openjdk-jdk10,代码行数:19,代码来源:TypesCachesCleared.java


示例2: createMethodCache

import com.sun.source.util.TreePathScanner; //导入依赖的package包/类
private Map<String, Element> createMethodCache(String binaryName) throws IOException {
    Pair<JavacTask, CompilationUnitTree> source = findSource(binaryName);

    if (source == null)
        return Collections.emptyMap();

    Map<String, Element> signature2Method = new HashMap<>();
    Trees trees = Trees.instance(source.fst);

    new TreePathScanner<Void, Void>() {
        @Override @DefinedBy(Api.COMPILER_TREE)
        public Void visitMethod(MethodTree node, Void p) {
            Element currentMethod = trees.getElement(getCurrentPath());

            if (currentMethod != null) {
                signature2Method.put(elementHeader(currentMethod, false), currentMethod);
            }

            return null;
        }
    }.scan(source.snd, null);

    return signature2Method;
}
 
开发者ID:campolake,项目名称:openjdk9,代码行数:25,代码来源:SourceCodeAnalysisImpl.java


示例3: qualifiedNameFix

import com.sun.source.util.TreePathScanner; //导入依赖的package包/类
/**
 * Add an import for {@code owner}, and qualify all on demand imported references to members of
 * owner by owner's simple name.
 */
private static void qualifiedNameFix(
    final SuggestedFix.Builder fix, final Symbol owner, VisitorState state) {
  fix.addImport(owner.getQualifiedName().toString());
  final JCCompilationUnit unit = (JCCompilationUnit) state.getPath().getCompilationUnit();
  new TreePathScanner<Void, Void>() {
    @Override
    public Void visitIdentifier(IdentifierTree tree, Void unused) {
      Symbol sym = ASTHelpers.getSymbol(tree);
      if (sym == null) {
        return null;
      }
      Tree parent = getCurrentPath().getParentPath().getLeaf();
      if (parent.getKind() == Tree.Kind.CASE
          && ((CaseTree) parent).getExpression().equals(tree)
          && sym.owner.getKind() == ElementKind.ENUM) {
        // switch cases can refer to enum constants by simple name without importing them
        return null;
      }
      if (sym.owner.equals(owner) && unit.starImportScope.includes(sym)) {
        fix.prefixWith(tree, owner.getSimpleName() + ".");
      }
      return null;
    }
  }.scan(unit, null);
}
 
开发者ID:google,项目名称:error-prone,代码行数:30,代码来源:WildcardImport.java


示例4: typeProcess

import com.sun.source.util.TreePathScanner; //导入依赖的package包/类
/**
 * Visit the tree path for the type element.
 */
@Override
public void typeProcess(TypeElement e, TreePath p) {
    currentRoot = p.getCompilationUnit();

    TreePathScanner<?, ?> scanner = null;
    try {
        scanner = createTreePathScanner(currentRoot);
        scanner.scan(p, null);
    } catch (Throwable t) {
        System.err.println("BasicTypeProcessor.typeProcess: unexpected Throwable (" +
                t.getClass().getSimpleName() + ")  when processing "
                + currentRoot.getSourceFile().getName() +
                (t.getMessage()!=null ? "; message: " + t.getMessage() : ""));
    }
}
 
开发者ID:reprogrammer,项目名称:checker-framework,代码行数:19,代码来源:BasicTypeProcessor.java


示例5: typeProcess

import com.sun.source.util.TreePathScanner; //导入依赖的package包/类
/** Visit the tree path for the type element. */
@Override
public void typeProcess(TypeElement e, TreePath p) {
    currentRoot = p.getCompilationUnit();

    TreePathScanner<?, ?> scanner = null;
    try {
        scanner = createTreePathScanner(currentRoot);
        scanner.scan(p, null);
    } catch (Throwable t) {
        System.err.println(
                "BasicTypeProcessor.typeProcess: unexpected Throwable ("
                        + t.getClass().getSimpleName()
                        + ")  when processing "
                        + currentRoot.getSourceFile().getName()
                        + (t.getMessage() != null ? "; message: " + t.getMessage() : ""));
    }
}
 
开发者ID:bazelbuild,项目名称:bazel,代码行数:19,代码来源:BasicTypeProcessor.java


示例6: testNETBEANS_228

import com.sun.source.util.TreePathScanner; //导入依赖的package包/类
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);
}
 
开发者ID:apache,项目名称:incubator-netbeans,代码行数:13,代码来源:NBAttrTest.java


示例7: verifyLambdaScopeCorrect

import com.sun.source.util.TreePathScanner; //导入依赖的package包/类
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);
}
 
开发者ID:AdoptOpenJDK,项目名称:openjdk-jdk10,代码行数:35,代码来源:ScopeTest.java


示例8: verifyLambdaScopeCorrect

import com.sun.source.util.TreePathScanner; //导入依赖的package包/类
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);
}
 
开发者ID:ojdkbuild,项目名称:lookaside_java-1.8.0-openjdk,代码行数:35,代码来源:ScopeTest.java


示例9: resolvescope

import com.sun.source.util.TreePathScanner; //导入依赖的package包/类
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;
}
 
开发者ID:vert-x3,项目名称:vertx-codetrans,代码行数:31,代码来源:ModelBuilder.java


示例10: run

import com.sun.source.util.TreePathScanner; //导入依赖的package包/类
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);
        }
    }
}
 
开发者ID:AdoptOpenJDK,项目名称:openjdk-jdk10,代码行数:81,代码来源:CheckErrorsForSource7.java


示例11: run

import com.sun.source.util.TreePathScanner; //导入依赖的package包/类
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);
    }
}
 
开发者ID:ojdkbuild,项目名称:lookaside_java-1.8.0-openjdk,代码行数:80,代码来源:CheckErrorsForSource7.java


示例12: createTreePathScanner

import com.sun.source.util.TreePathScanner; //导入依赖的package包/类
/** Create a TreePathScanner at the given root. */
protected abstract TreePathScanner<?, ?> createTreePathScanner(CompilationUnitTree root);
 
开发者ID:bazelbuild,项目名称:bazel,代码行数:3,代码来源:BasicTypeProcessor.java


示例13: process

import com.sun.source.util.TreePathScanner; //导入依赖的package包/类
@Override
public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {

    if (annotations.isEmpty()) {
        // called with no annotations
        return true;
    }

    for (TypeElement annotation : annotations) {

        TreePathScanner<Void, Trees> scanner = scanners.get(annotation.getQualifiedName().toString());
        if (scanner == null) {
            // annotation is not intended to be used for code checking
            continue;
        }

        // check whether the annotation is used in correct place and perform the verification
        // of target element using appropriate scanner
        Target target = annotation.getAnnotation(Target.class);
        Set<? extends Element> annotatedElements = roundEnv.getElementsAnnotatedWith(annotation);
        for (Element element : annotatedElements) {

            if (target == null) {
                // annotation can be used everywhere
            } else {

                boolean usedInCorrectPlace = false;

                for (ElementType type : target.value()) {
                    if (UtilsCTree.convertToElementType(element.getKind()).equals(type)) {
                        usedInCorrectPlace = true;
                    }
                }

                if (!usedInCorrectPlace) {
                    messager.printMessage(Diagnostic.Kind.ERROR, "The @" + annotation.getSimpleName() +
                        " annotation is declared to be used with " + target.toString());
                    continue;
                }
            }

            scanner.scan(trees.getPath(element), trees);
        }
    }

    return true;
}
 
开发者ID:mnip91,项目名称:proactive-component-monitoring,代码行数:48,代码来源:ProActiveProcessorCTree.java


示例14: createTreePathScanner

import com.sun.source.util.TreePathScanner; //导入依赖的package包/类
/**
 * Create a TreePathScanner at the given root.
 */
protected abstract TreePathScanner<?, ?> createTreePathScanner(CompilationUnitTree root);
 
开发者ID:reprogrammer,项目名称:checker-framework,代码行数:5,代码来源:BasicTypeProcessor.java



注:本文中的com.sun.source.util.TreePathScanner类示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Java ChangeEvent类代码示例发布时间:2022-05-21
下一篇:
Java Route类代码示例发布时间:2022-05-21
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap