com.sun.source.util.Trees Java Examples

The following examples show how to use com.sun.source.util.Trees. 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: Processor.java    From EasyMPermission with MIT License 6 votes vote down vote up
/** {@inheritDoc} */
@Override public void init(ProcessingEnvironment procEnv) {
	super.init(procEnv);
	if (System.getProperty("lombok.disable") != null) {
		lombokDisabled = true;
		return;
	}
	
	this.processingEnv = (JavacProcessingEnvironment) procEnv;
	placePostCompileAndDontMakeForceRoundDummiesHook();
	transformer = new JavacTransformer(procEnv.getMessager());
	trees = Trees.instance(procEnv);
	SortedSet<Long> p = transformer.getPriorities();
	if (p.isEmpty()) {
		this.priorityLevels = new long[] {0L};
		this.priorityLevelsRequiringResolutionReset = new HashSet<Long>();
	} else {
		this.priorityLevels = new long[p.size()];
		int i = 0;
		for (Long prio : p) this.priorityLevels[i++] = prio;
		this.priorityLevelsRequiringResolutionReset = transformer.getPrioritiesRequiringResolutionReset();
	}
}
 
Example #2
Source File: T6852595.java    From openjdk-jdk8u with GNU General Public License v2.0 6 votes vote down vote up
public static void main(String[] args) throws IOException {
    JavaFileObject sfo = new SimpleJavaFileObject(URI.create("myfo:/Test.java"),Kind.SOURCE) {
        public CharSequence getCharContent(boolean ignoreEncodingErrors) {
            return "class BadName { Object o = j; }";
        }
    };
    List<? extends JavaFileObject> files = Arrays.asList(sfo);
    JavaCompiler tool = ToolProvider.getSystemJavaCompiler();
    JavacTask ct = (JavacTask)tool.getTask(null, null, null, null, null, files);
    Iterable<? extends CompilationUnitTree> compUnits = ct.parse();
    CompilationUnitTree cu = compUnits.iterator().next();
    ClassTree cdef = (ClassTree)cu.getTypeDecls().get(0);
    JCVariableDecl vdef = (JCVariableDecl)cdef.getMembers().get(0);
    TreePath path = TreePath.getPath(cu, vdef.init);
    Trees.instance(ct).getScope(path);
}
 
Example #3
Source File: JavacParserTest.java    From openjdk-jdk8u with GNU General Public License v2.0 6 votes vote down vote up
@Test
void testPositionForEnumModifiers() throws IOException {
    final String theString = "public";
    String code = "package test; " + theString + " enum Test {A;}";

    JavacTaskImpl ct = (JavacTaskImpl) tool.getTask(null, null, null, null,
            null, Arrays.asList(new MyFileObject(code)));
    CompilationUnitTree cut = ct.parse().iterator().next();
    SourcePositions pos = Trees.instance(ct).getSourcePositions();

    ClassTree clazz = (ClassTree) cut.getTypeDecls().get(0);
    ModifiersTree mt = clazz.getModifiers();
    int spos = code.indexOf(theString);
    int epos = spos + theString.length();
    assertEquals("testPositionForEnumModifiers",
            spos, pos.getStartPosition(cut, mt));
    assertEquals("testPositionForEnumModifiers",
            epos, pos.getEndPosition(cut, mt));
}
 
Example #4
Source File: JavacParserTest.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
@Test
void testPositionForEnumModifiers() throws IOException {
    final String theString = "public";
    String code = "package test; " + theString + " enum Test {A;}";

    JavacTaskImpl ct = (JavacTaskImpl) tool.getTask(null, fm, null, null,
            null, Arrays.asList(new MyFileObject(code)));
    CompilationUnitTree cut = ct.parse().iterator().next();
    SourcePositions pos = Trees.instance(ct).getSourcePositions();

    ClassTree clazz = (ClassTree) cut.getTypeDecls().get(0);
    ModifiersTree mt = clazz.getModifiers();
    int spos = code.indexOf(theString);
    int epos = spos + theString.length();
    assertEquals("testPositionForEnumModifiers",
            spos, pos.getStartPosition(cut, mt));
    assertEquals("testPositionForEnumModifiers",
            epos, pos.getEndPosition(cut, mt));
}
 
Example #5
Source File: JavacParserTest.java    From hottub with GNU General Public License v2.0 6 votes vote down vote up
@Test
void testNewClassWithEnclosing() throws IOException {

    final String theString = "Test.this.new d()";
    String code = "package test; class Test { " +
            "class d {} private void method() { " +
            "Object o = " + theString + "; } }";

    JavacTaskImpl ct = (JavacTaskImpl) tool.getTask(null, null, null, null,
            null, Arrays.asList(new MyFileObject(code)));
    CompilationUnitTree cut = ct.parse().iterator().next();
    SourcePositions pos = Trees.instance(ct).getSourcePositions();

    ClassTree clazz = (ClassTree) cut.getTypeDecls().get(0);
    ExpressionTree est =
            ((VariableTree) ((MethodTree) clazz.getMembers().get(1)).getBody().getStatements().get(0)).getInitializer();

    final int spos = code.indexOf(theString);
    final int epos = spos + theString.length();
    assertEquals("testNewClassWithEnclosing",
            spos, pos.getStartPosition(cut, est));
    assertEquals("testNewClassWithEnclosing",
            epos, pos.getEndPosition(cut, est));
}
 
Example #6
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 #7
Source File: JavadocCompletionQuery.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private void addPackageContent(PackageElement pe, EnumSet<ElementKind> kinds, DeclaredType baseType, Set<? extends Element> toExclude, String prefix, int substitutionOffset, JavadocContext jdctx) {
    CompilationInfo controller = jdctx.javac;
    Element srcEl = jdctx.handle.resolve(controller);
    Elements elements = controller.getElements();
    Types types = controller.getTypes();
    Trees trees = controller.getTrees();
    TreeUtilities tu = controller.getTreeUtilities();
    ElementUtilities eu = controller.getElementUtilities();
    TreePath docpath = srcEl != null ? trees.getPath(srcEl) : null;
    Scope scope = docpath != null ? trees.getScope(docpath) : tu.scopeFor(caretOffset);
    for(Element e : pe.getEnclosedElements()) {
        if ((e.getKind().isClass() || e.getKind().isInterface()) && (toExclude == null || !toExclude.contains(e))) {
            String name = e.getSimpleName().toString();
                if (Utilities.startsWith(name, prefix) && (Utilities.isShowDeprecatedMembers() || !elements.isDeprecated(e))
                    && trees.isAccessible(scope, (TypeElement)e)
                    && isOfKindAndType(e.asType(), e, kinds, baseType, scope, trees, types)
                    && !Utilities.isExcluded(eu.getElementName(e, true))) {
                    items.add(JavadocCompletionItem.createTypeItem(jdctx.javac, (TypeElement) e, substitutionOffset, null, elements.isDeprecated(e)/*, isOfSmartType(env, e.asType(), smartTypes)*/));
            }
        }
    }
}
 
Example #8
Source File: InnerToOuterTransformer.java    From netbeans with Apache License 2.0 6 votes vote down vote up
@Override
public Tree visitCompilationUnit(CompilationUnitTree node, Element p) {
    this.referencedPrivateElement = new HashSet<Element>();

    Tree result = super.visitCompilationUnit(node, p);

    for (Element privEl : this.referencedPrivateElement) {
        problem = MoveTransformer.createProblem(problem, false, NbBundle.getMessage(InnerToOuterRefactoringPlugin.class, "WRN_InnerToOuterRefToPrivate", privEl));
    }
    
    Trees trees = workingCopy.getTrees();
    CompilationUnitTree newNode = node;
    for (ImportTree imp : node.getImports()) {
        if(imp.isStatic()) {
            Tree qualIdent = imp.getQualifiedIdentifier();
            TypeElement el = workingCopy.getElements().getTypeElement(qualIdent.toString());
            if(inner.equals(el)) {
                newNode = make.removeCompUnitImport(newNode, imp);
            }
        }
    }
    if(newNode != node) {
        rewrite(node, newNode);
    }
    return result;
}
 
Example #9
Source File: JavacParserTest.java    From hottub with GNU General Public License v2.0 6 votes vote down vote up
@Test
void testPositionForEnumModifiers() throws IOException {
    final String theString = "public";
    String code = "package test; " + theString + " enum Test {A;}";

    JavacTaskImpl ct = (JavacTaskImpl) tool.getTask(null, null, null, null,
            null, Arrays.asList(new MyFileObject(code)));
    CompilationUnitTree cut = ct.parse().iterator().next();
    SourcePositions pos = Trees.instance(ct).getSourcePositions();

    ClassTree clazz = (ClassTree) cut.getTypeDecls().get(0);
    ModifiersTree mt = clazz.getModifiers();
    int spos = code.indexOf(theString);
    int epos = spos + theString.length();
    assertEquals("testPositionForEnumModifiers",
            spos, pos.getStartPosition(cut, mt));
    assertEquals("testPositionForEnumModifiers",
            epos, pos.getEndPosition(cut, mt));
}
 
Example #10
Source File: ApNavigator.java    From openjdk-jdk8u with GNU General Public License v2.0 6 votes vote down vote up
private Location getLocation(final String name, final TreePath treePath) {
    return new Location() {
        public String toString() {
            if (treePath == null)
                return name + " (Unknown Source)";
            // just like stack trace, we just print the file name and
            // not the whole path. The idea is that the package name should
            // provide enough clue on which directory it lives.
            CompilationUnitTree compilationUnit = treePath.getCompilationUnit();
            Trees trees = Trees.instance(env);
            long startPosition = trees.getSourcePositions().getStartPosition(compilationUnit, treePath.getLeaf());
            return name + "(" +
                    compilationUnit.getSourceFile().getName() + ":" + compilationUnit.getLineMap().getLineNumber(startPosition) +
                    ")";
        }
    };
}
 
Example #11
Source File: AccessPathNullnessPropagation.java    From NullAway with MIT License 6 votes vote down vote up
@Nullable
private ClassTree findEnclosingLocalOrAnonymousClass(ClassTree classTree) {
  Symbol.ClassSymbol symbol = ASTHelpers.getSymbol(classTree);
  // we need this while loop since we can have a NestingKind.NESTED class (i.e., a nested
  // class declared at the top-level within its enclosing class) nested (possibly deeply)
  // within a NestingKind.ANONYMOUS or NestingKind.LOCAL class
  while (symbol.getNestingKind().isNested()) {
    if (symbol.getNestingKind().equals(NestingKind.ANONYMOUS)
        || symbol.getNestingKind().equals(NestingKind.LOCAL)) {
      return Trees.instance(JavacProcessingEnvironment.instance(context)).getTree(symbol);
    } else {
      // symbol.owner is the enclosing element, which could be a class or a method.
      // if it's a class, the enclClass() method will (surprisingly) return the class itself,
      // so this works
      symbol = symbol.owner.enclClass();
    }
  }
  return null;
}
 
Example #12
Source File: T6852595.java    From openjdk-8-source with GNU General Public License v2.0 6 votes vote down vote up
public static void main(String[] args) throws IOException {
    JavaFileObject sfo = new SimpleJavaFileObject(URI.create("myfo:/Test.java"),Kind.SOURCE) {
        public CharSequence getCharContent(boolean ignoreEncodingErrors) {
            return "class BadName { Object o = j; }";
        }
    };
    List<? extends JavaFileObject> files = Arrays.asList(sfo);
    JavaCompiler tool = ToolProvider.getSystemJavaCompiler();
    JavacTask ct = (JavacTask)tool.getTask(null, null, null, null, null, files);
    Iterable<? extends CompilationUnitTree> compUnits = ct.parse();
    CompilationUnitTree cu = compUnits.iterator().next();
    ClassTree cdef = (ClassTree)cu.getTypeDecls().get(0);
    JCVariableDecl vdef = (JCVariableDecl)cdef.getMembers().get(0);
    TreePath path = TreePath.getPath(cu, vdef.init);
    Trees.instance(ct).getScope(path);
}
 
Example #13
Source File: JavacParserTest.java    From jdk8u60 with GNU General Public License v2.0 6 votes vote down vote up
@Test
void testNewClassWithEnclosing() throws IOException {

    final String theString = "Test.this.new d()";
    String code = "package test; class Test { " +
            "class d {} private void method() { " +
            "Object o = " + theString + "; } }";

    JavacTaskImpl ct = (JavacTaskImpl) tool.getTask(null, null, null, null,
            null, Arrays.asList(new MyFileObject(code)));
    CompilationUnitTree cut = ct.parse().iterator().next();
    SourcePositions pos = Trees.instance(ct).getSourcePositions();

    ClassTree clazz = (ClassTree) cut.getTypeDecls().get(0);
    ExpressionTree est =
            ((VariableTree) ((MethodTree) clazz.getMembers().get(1)).getBody().getStatements().get(0)).getInitializer();

    final int spos = code.indexOf(theString);
    final int epos = spos + theString.length();
    assertEquals("testNewClassWithEnclosing",
            spos, pos.getStartPosition(cut, est));
    assertEquals("testNewClassWithEnclosing",
            epos, pos.getEndPosition(cut, est));
}
 
Example #14
Source File: JavacParserTest.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
void testPositionBrokenSource126732a() throws IOException {
    String[] commands = new String[]{
        "return Runnable()",
        "do { } while (true)",
        "throw UnsupportedOperationException()",
        "assert true",
        "1 + 1",};

    for (String command : commands) {

        String code = "package test;\n"
                + "public class Test {\n"
                + "    public static void test() {\n"
                + "        " + command + " {\n"
                + "                new Runnable() {\n"
                + "        };\n"
                + "    }\n"
                + "}";
        JavacTaskImpl ct = (JavacTaskImpl) tool.getTask(null, fm, null,
                null, null, Arrays.asList(new MyFileObject(code)));
        CompilationUnitTree cut = ct.parse().iterator().next();

        ClassTree clazz = (ClassTree) cut.getTypeDecls().get(0);
        MethodTree method = (MethodTree) clazz.getMembers().get(0);
        List<? extends StatementTree> statements =
                method.getBody().getStatements();

        StatementTree ret = statements.get(0);
        StatementTree block = statements.get(1);

        Trees t = Trees.instance(ct);
        int len = code.indexOf(command + " {") + (command + " ").length();
        assertEquals(command, len,
                t.getSourcePositions().getEndPosition(cut, ret));
        assertEquals(command, len,
                t.getSourcePositions().getStartPosition(cut, block));
    }
}
 
Example #15
Source File: LocationOpener.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private int getMethodLine(final FileObject fo, final String methodName) {
    final int[] line = new int[1];
    JavaSource javaSource = JavaSource.forFileObject(fo);
    if (javaSource != null) {
        try {
            javaSource.runUserActionTask((CompilationController compilationController) -> {
                compilationController.toPhase(JavaSource.Phase.ELEMENTS_RESOLVED);
                Trees trees = compilationController.getTrees();
                CompilationUnitTree compilationUnitTree = compilationController.getCompilationUnit();
                List<? extends Tree> typeDecls = compilationUnitTree.getTypeDecls();
                for (Tree tree : typeDecls) {
                    Element element = trees.getElement(trees.getPath(compilationUnitTree, tree));
                    if (element != null && element.getKind() == ElementKind.CLASS && element.getSimpleName().contentEquals(fo.getName())) {
                        List<? extends ExecutableElement> methodElements = ElementFilter.methodsIn(element.getEnclosedElements());
                        for (Element child : methodElements) {
                            if (child.getSimpleName().contentEquals(methodName)) {
                                long pos = trees.getSourcePositions().getStartPosition(compilationUnitTree, trees.getTree(child));
                                line[0] = (int) compilationUnitTree.getLineMap().getLineNumber(pos);
                                break;
                            }
                        }
                    }
                }
            }, true);
            return line[0];
        } catch (IOException ioe) {
            //TODO: Do nothing?
        }
    }
    return 1;
}
 
Example #16
Source File: JavacParserTest.java    From hottub with GNU General Public License v2.0 5 votes vote down vote up
void performWildcardPositionsTest(final String code,
        List<String> golden) throws IOException {

    final List<Diagnostic<? extends JavaFileObject>> errors =
            new LinkedList<Diagnostic<? extends JavaFileObject>>();

    JavacTaskImpl ct = (JavacTaskImpl) tool.getTask(null, null,
            new DiagnosticListener<JavaFileObject>() {
                public void report(Diagnostic<? extends JavaFileObject> diagnostic) {
                    errors.add(diagnostic);
                }
            }, null, null, Arrays.asList(new MyFileObject(code)));

    final CompilationUnitTree cut = ct.parse().iterator().next();
    final List<String> content = new LinkedList<String>();
    final Trees trees = Trees.instance(ct);

    new TreeScanner<Void, Void>() {
        @Override
        public Void scan(Tree node, Void p) {
            if (node == null) {
                return null;
            }
            long start = trees.getSourcePositions().getStartPosition(cut, node);

            if (start == (-1)) {
                return null; // synthetic tree
            }
            long end = trees.getSourcePositions().getEndPosition(cut, node);
            String s = code.substring((int) start, (int) end);
            content.add(s);

            return super.scan(node, p);
        }
    }.scan(((MethodTree) ((ClassTree) cut.getTypeDecls().get(0)).getMembers().get(0)).getBody().getStatements().get(0), null);

    assertEquals("performWildcardPositionsTest",golden.toString(),
            content.toString());
}
 
Example #17
Source File: SrcFinder.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private static TypeElement findClass(CompilationController ctrl, String className) {
    CompilationUnitTree cunit = ctrl.getCompilationUnit();
    for (Tree declTree : cunit.getTypeDecls()) {
        ClassTree classTree = (ClassTree) declTree;
        if (className.equals(classTree.getSimpleName().toString())) {
            Trees trees = ctrl.getTrees();
            TypeElement classElm = (TypeElement) trees.getElement(trees.getPath(cunit, classTree));
            return classElm;
        }
    }
    return null;
}
 
Example #18
Source File: ModelBuilder.java    From vertx-codetrans with Apache License 2.0 5 votes vote down vote up
public ModelBuilder(Trees trees, TypeElement typeElt, DeclaredType systemType, DeclaredType throwableType, TypeMirrorFactory factory, Types typeUtils, Lang lang) {
  this.path = trees.getPath(typeElt);
  this.trees = trees;
  this.systemType = systemType;
  this.throwableType = throwableType;
  this.factory = factory;
  this.typeUtils = typeUtils;
  this.typeElt = typeElt;
}
 
Example #19
Source File: ModelChecker.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 5 votes vote down vote up
@Override
public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
    if (roundEnv.processingOver())
        return true;

    Trees trees = Trees.instance(processingEnv);

    TypeElement testAnno = elements.getTypeElement("Check");
    for (Element elem: roundEnv.getElementsAnnotatedWith(testAnno)) {
        TreePath p = trees.getPath(elem);
        new IntersectionCastTester(trees).scan(p, null);
    }
    return true;
}
 
Example #20
Source File: T6993305.java    From jdk8u60 with GNU General Public License v2.0 5 votes vote down vote up
@Override public Void visitCompilationUnit(CompilationUnitTree tree, JavacTask task) {
    cu = tree;
    Trees trees = Trees.instance(task);
    sourcePositions = trees.getSourcePositions();
    try {
        source = String.valueOf(tree.getSourceFile().getCharContent(true));
    } catch (IOException e) {
        throw new Error(e);
    }
    return super.visitCompilationUnit(tree, task);
}
 
Example #21
Source File: JavacParserTest.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 5 votes vote down vote up
@Test
void testPositionAnnotationNoPackage187551() throws IOException {

    String code = "\n@interface Test {}";

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

    CompilationUnitTree cut = ct.parse().iterator().next();
    ClassTree clazz = (ClassTree) cut.getTypeDecls().get(0);
    Trees t = Trees.instance(ct);

    assertEquals("testPositionAnnotationNoPackage187551",
            1, t.getSourcePositions().getStartPosition(cut, clazz));
}
 
Example #22
Source File: DependenciesTest.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
public SearchAnnotations(Trees trees, Elements elements) {
    this.trees = trees;
    this.elements = elements;
    this.triggersCompleteAnnotation =
            elements.getTypeElement(TriggersComplete.class.getName());
    this.triggersCompleteRepeatAnnotation =
            elements.getTypeElement(TriggersCompleteRepeat.class.getName());
}
 
Example #23
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 #24
Source File: ConvertToLambdaConverter.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@Override
public Tree visitIdentifier(IdentifierTree identifierTree, Trees trees) {
    //rename shadowed variable
    TreePath currentPath = getCurrentPath();
    CharSequence newName = originalToNewName.get(trees.getElement(currentPath));
    if (newName != null) {
        IdentifierTree newTree = copy.getTreeMaker().Identifier(newName);
        copy.rewrite(identifierTree, newTree);
    }

    return super.visitIdentifier(identifierTree, trees);
}
 
Example #25
Source File: JavacParserTest.java    From openjdk-8-source with GNU General Public License v2.0 5 votes vote down vote up
void testPositionBrokenSource126732b() throws IOException {
    String[] commands = new String[]{
        "break",
        "break A",
        "continue ",
        "continue A",};

    for (String command : commands) {

        String code = "package test;\n"
                + "public class Test {\n"
                + "    public static void test() {\n"
                + "        while (true) {\n"
                + "            " + command + " {\n"
                + "                new Runnable() {\n"
                + "        };\n"
                + "        }\n"
                + "    }\n"
                + "}";

        JavacTaskImpl ct = (JavacTaskImpl) tool.getTask(null, null, null,
                null, null, Arrays.asList(new MyFileObject(code)));
        CompilationUnitTree cut = ct.parse().iterator().next();

        ClassTree clazz = (ClassTree) cut.getTypeDecls().get(0);
        MethodTree method = (MethodTree) clazz.getMembers().get(0);
        List<? extends StatementTree> statements =
                ((BlockTree) ((WhileLoopTree) method.getBody().getStatements().get(0)).getStatement()).getStatements();

        StatementTree ret = statements.get(0);
        StatementTree block = statements.get(1);

        Trees t = Trees.instance(ct);
        int len = code.indexOf(command + " {") + (command + " ").length();
        assertEquals(command, len,
                t.getSourcePositions().getEndPosition(cut, ret));
        assertEquals(command, len,
                t.getSourcePositions().getStartPosition(cut, block));
    }
}
 
Example #26
Source File: MavenJUnitNodeOpener.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public void openTestsuite(TestsuiteNode node) {
    Children childrens = node.getChildren();
    if (childrens != null) {
        Node child = childrens.getNodeAt(0);
        if ((child != null) && (child instanceof MavenJUnitTestMethodNode)) {
            final FileObject fo = ((MavenJUnitTestMethodNode) child).getTestcaseFileObject();
            if (fo != null) {
                final long[] line = new long[]{0};
                JavaSource javaSource = JavaSource.forFileObject(fo);
                if (javaSource != null) {
                    try {
                        javaSource.runUserActionTask(new Task<CompilationController>() {
                            @Override
                            public void run(CompilationController compilationController) throws Exception {
                                compilationController.toPhase(Phase.ELEMENTS_RESOLVED);
                                Trees trees = compilationController.getTrees();
                                CompilationUnitTree compilationUnitTree = compilationController.getCompilationUnit();
                                List<? extends Tree> typeDecls = compilationUnitTree.getTypeDecls();
                                for (Tree tree : typeDecls) {
                                    Element element = trees.getElement(trees.getPath(compilationUnitTree, tree));
                                    if (element != null && element.getKind() == ElementKind.CLASS && element.getSimpleName().contentEquals(fo.getName())) {
                                        long pos = trees.getSourcePositions().getStartPosition(compilationUnitTree, tree);
                                        line[0] = compilationUnitTree.getLineMap().getLineNumber(pos);
                                        break;
                                    }
                                }
                            }
                        }, true);
                    } catch (IOException ioe) {
                        ErrorManager.getDefault().notify(ioe);
                    }
                }
                UIJavaUtils.openFile(fo, (int) line[0]);
            }
        }
    }
}
 
Example #27
Source File: AbstractCodingRulesAnalyzer.java    From hottub with GNU General Public License v2.0 5 votes vote down vote up
public void init(JavacTask task, String... args) {
    BasicJavacTask impl = (BasicJavacTask)task;
    Context context = impl.getContext();
    log = Log.instance(context);
    trees = Trees.instance(task);
    messages = new Messages();
    task.addTaskListener(new PostAnalyzeTaskListener());
}
 
Example #28
Source File: DeptectiveTreeVisitor.java    From deptective with Apache License 2.0 5 votes vote down vote up
public DeptectiveTreeVisitor(JavacTask task, Log log, PackageReferenceHandler packageReferenceHandler) {
    elements = task.getElements();
    types = task.getTypes();
    trees = Trees.instance(task);
    this.log = log;
    this.packageReferenceHandler = packageReferenceHandler;
}
 
Example #29
Source File: JavacParserTest.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 5 votes vote down vote up
void testPositionBrokenSource126732b() throws IOException {
    String[] commands = new String[]{
        "break",
        "break A",
        "continue ",
        "continue A",};

    for (String command : commands) {

        String code = "package test;\n"
                + "public class Test {\n"
                + "    public static void test() {\n"
                + "        while (true) {\n"
                + "            " + command + " {\n"
                + "                new Runnable() {\n"
                + "        };\n"
                + "        }\n"
                + "    }\n"
                + "}";

        JavacTaskImpl ct = (JavacTaskImpl) tool.getTask(null, null, null,
                null, null, Arrays.asList(new MyFileObject(code)));
        CompilationUnitTree cut = ct.parse().iterator().next();

        ClassTree clazz = (ClassTree) cut.getTypeDecls().get(0);
        MethodTree method = (MethodTree) clazz.getMembers().get(0);
        List<? extends StatementTree> statements =
                ((BlockTree) ((WhileLoopTree) method.getBody().getStatements().get(0)).getStatement()).getStatements();

        StatementTree ret = statements.get(0);
        StatementTree block = statements.get(1);

        Trees t = Trees.instance(ct);
        int len = code.indexOf(command + " {") + (command + " ").length();
        assertEquals(command, len,
                t.getSourcePositions().getEndPosition(cut, ret));
        assertEquals(command, len,
                t.getSourcePositions().getStartPosition(cut, block));
    }
}
 
Example #30
Source File: BIGuardedBlockHandlerFactory.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private boolean checkChange(CompilationController javac, PositionBounds span) throws IOException, BadLocationException {
    final int begin = span.getBegin().getOffset();
    final Trees trees = javac.getTrees();
    TreePath path = javac.getTreeUtilities().pathFor(begin + 1);
    if (path == null) {
        return false;
    }
    
    Element element = trees.getElement(path);
    if (element == null) {
        return false;
    }

    TreePath decl = trees.getPath(element);
    if (decl != null) {
        SourcePositions sourcePositions = trees.getSourcePositions();
        long declBegin = sourcePositions.getStartPosition(decl.getCompilationUnit(), decl.getLeaf());
        FileObject fo = SourceUtils.getFile(element, javac.getClasspathInfo());
        Document doc = javac.getDocument();
        GuardedSectionManager guards = GuardedSectionManager.getInstance((StyledDocument) doc);
        
        if (fo != javac.getFileObject() || guards != null && !isGuarded(guards, doc.createPosition((int) declBegin))) {
            // tree being refactored is declared outside of this file
            // or out of guarded sections. It should be safe to make change
            return true;
        }
    } else {
        // e.g. package; change is OK
            return true;
    }
    return false;
}