com.sun.source.tree.CompilationUnitTree Java Examples

The following examples show how to use com.sun.source.tree.CompilationUnitTree. 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: TestGetElementReference.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 6 votes vote down vote up
private static TreePath pathFor(final Trees trees, final CompilationUnitTree cut, final int pos) {
    final TreePath[] result = new TreePath[1];

    new TreePathScanner<Void, Void>() {
        @Override public Void scan(Tree node, Void p) {
            if (   node != null
                && trees.getSourcePositions().getStartPosition(cut, node) <= pos
                && pos <= trees.getSourcePositions().getEndPosition(cut, node)) {
                result[0] = new TreePath(getCurrentPath(), node);
                return super.scan(node, p);
            }
            return null;
        }
    }.scan(cut, null);

    return result[0];
}
 
Example #2
Source File: ApNavigator.java    From openjdk-8-source 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 #3
Source File: ValidatingTaskListener.java    From buck with Apache License 2.0 6 votes vote down vote up
@Override
public void finished(TaskEvent e) {
  TaskEvent.Kind kind = e.getKind();
  if (kind == TaskEvent.Kind.PARSE) {
    CompilationUnitTree compilationUnit = e.getCompilationUnit();
    compilationUnits.add(compilationUnit);
  } else if (kind == TaskEvent.Kind.ENTER) {
    enterDepth -= 1;
    // We wait until we've received all enter events so that the validation time shows up
    // separately from compiler enter time in the traces. We wait until after annotation
    // processing so we catch all the types.
    if (!annotationProcessing && enterDepth == 0 && !errorsExist.get()) {
      getValidator().validate(compilationUnits);
    }
  } else if (kind == TaskEvent.Kind.ANNOTATION_PROCESSING) {
    annotationProcessing = false;
  }
}
 
Example #4
Source File: JavacParserTest.java    From TencentKona-8 with GNU General Public License v2.0 6 votes vote down vote up
@Test
void testMissingParenthesisError() throws IOException {

    String code = "package test; public class ErrorTest { "
            + "void f() {String s = new String; } }";
    CompilationUnitTree cut = getCompilationUnitTree(code);
    final List<String> values = new ArrayList<>();
    final List<String> expectedValues =
            new ArrayList<>(Arrays.asList("[new String()]"));

    new TreeScanner<Void, Void>() {
        @Override
        public Void visitErroneous(ErroneousTree node, Void p) {
            values.add(getErroneousTreeValues(node).toString());
            return null;
        }
    }.scan(cut, null);

    assertEquals("testSwitchError: The Erroneous tree "
            + "error values: " + values
            + " do not match expected error values: "
            + expectedValues, values, expectedValues);
}
 
Example #5
Source File: JavacParserTest.java    From TencentKona-8 with GNU General Public License v2.0 6 votes vote down vote up
@Test
void testMissingClassError() throws IOException {

    String code = "package Test; clas ErrorTest {  "
            + "void f() {String s = new String(); } }";
    CompilationUnitTree cut = getCompilationUnitTree(code);
    final List<String> values = new ArrayList<>();
    final List<String> expectedValues =
            new ArrayList<>(Arrays.asList("[, clas]", "[]"));

    new TreeScanner<Void, Void>() {
        @Override
        public Void visitErroneous(ErroneousTree node, Void p) {
            values.add(getErroneousTreeValues(node).toString());
            return null;
        }
    }.scan(cut, null);

    assertEquals("testSwitchError: The Erroneous tree "
            + "error values: " + values
            + " do not match expected error values: "
            + expectedValues, values, expectedValues);
}
 
Example #6
Source File: JavacParserTest.java    From jdk8u60 with GNU General Public License v2.0 6 votes vote down vote up
@Test
void testMissingParenthesisError() throws IOException {

    String code = "package test; public class ErrorTest { "
            + "void f() {String s = new String; } }";
    CompilationUnitTree cut = getCompilationUnitTree(code);
    final List<String> values = new ArrayList<>();
    final List<String> expectedValues =
            new ArrayList<>(Arrays.asList("[new String()]"));

    new TreeScanner<Void, Void>() {
        @Override
        public Void visitErroneous(ErroneousTree node, Void p) {
            values.add(getErroneousTreeValues(node).toString());
            return null;
        }
    }.scan(cut, null);

    assertEquals("testSwitchError: The Erroneous tree "
            + "error values: " + values
            + " do not match expected error values: "
            + expectedValues, values, expectedValues);
}
 
Example #7
Source File: T6963934.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 Exception {
    File testSrc = new File(System.getProperty("test.src"));
    File thisSrc = new File(testSrc, T6963934.class.getSimpleName() + ".java");
    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    StandardJavaFileManager fileManager = compiler.getStandardFileManager(null, null, null);
    JavacTask task = (JavacTask) compiler.getTask(null, fileManager, null, null, null,
            fileManager.getJavaFileObjects(thisSrc));
    CompilationUnitTree tree = task.parse().iterator().next();
    int count = 0;
    for (ImportTree importTree : tree.getImports()) {
        System.out.println(importTree);
        count++;
    }
    int expected = 7;
    if (count != expected)
        throw new Exception("unexpected number of imports found: " + count + ", expected: " + expected);
}
 
Example #8
Source File: StaticImport.java    From netbeans with Apache License 2.0 6 votes vote down vote up
@Override
protected void performRewrite(TransformationContext ctx) throws Exception {
    WorkingCopy copy = ctx.getWorkingCopy();
    TreePath treePath = ctx.getPath();
    TreePath mitp = treePath.getParentPath();
    if (mitp == null) {
        return;
    }
    Element e = copy.getTrees().getElement(treePath);
    if (e == null || !e.getModifiers().contains(Modifier.STATIC)) {
        return;
    }
    TreeMaker make = copy.getTreeMaker();
    copy.rewrite(treePath.getLeaf(), make.Identifier(sn));
    if (fqn == null) {
        return;
    }
    CompilationUnitTree cut = (CompilationUnitTree) copy.resolveRewriteTarget(copy.getCompilationUnit());
    CompilationUnitTree nue = GeneratorUtilities.get(copy).addImports(cut, Collections.singleton(e));
    copy.rewrite(cut, nue);
}
 
Example #9
Source File: JavacParserTest.java    From openjdk-8-source 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 #10
Source File: WrappingTest.java    From netbeans with Apache License 2.0 6 votes vote down vote up
public void testWrapMethod2() throws Exception {
    String code = "package hierbas.del.litoral;\n\n" +
        "import java.util.concurrent.atomic.AtomicBoolean;\n\n" +
        "public class Test {\n" +
        "}\n";
    runWrappingTest(code, new Task<WorkingCopy>() {
        public void run(WorkingCopy workingCopy) throws IOException {
            workingCopy.toPhase(Phase.RESOLVED);
            CompilationUnitTree cut = workingCopy.getCompilationUnit();
            TreeMaker make = workingCopy.getTreeMaker();
            ClassTree clazz = (ClassTree) cut.getTypeDecls().get(0);
            ExpressionTree parsed = workingCopy.getTreeUtilities().parseExpression("new Object() { private void test(int a, int b, int c) throws java.io.FileNotFoundException, java.net.MalformedURLException { } }", new SourcePositions[1]);
            parsed = GeneratorUtilities.get(workingCopy).importFQNs(parsed);
            MethodTree method = (MethodTree) ((NewClassTree) parsed).getClassBody().getMembers().get(0);
            workingCopy.rewrite(clazz, make.addClassMember(clazz, method));
        }
    },
    FmtOptions.wrapMethodParams, WrapStyle.WRAP_ALWAYS.name(),
    FmtOptions.wrapThrowsKeyword, WrapStyle.WRAP_ALWAYS.name(),
    FmtOptions.wrapThrowsList, WrapStyle.WRAP_ALWAYS.name());
}
 
Example #11
Source File: ImportFormatTest.java    From netbeans with Apache License 2.0 6 votes vote down vote up
public void testRemoveLastImport() throws IOException, FileStateInvalidException {
    JavaSource src = getJavaSource(testFile);
    Task<WorkingCopy> task = new Task<WorkingCopy>() {

        public void run(WorkingCopy workingCopy) throws IOException {
            workingCopy.toPhase(Phase.RESOLVED);
            TreeMaker make = workingCopy.getTreeMaker();
            CompilationUnitTree cut = workingCopy.getCompilationUnit();
            List<ImportTree> imports = new ArrayList<ImportTree>(cut.getImports());
            imports.remove(1);
            CompilationUnitTree unit = make.CompilationUnit(
                    cut.getPackageName(),
                    imports,
                    cut.getTypeDecls(),
                    cut.getSourceFile()
            );
            workingCopy.rewrite(cut, unit);
        }
    };
    src.runModificationTask(task).commit();
    String res = TestUtilities.copyFileToString(testFile);
    //System.err.println(res);
    assertFiles("testRemoveLastImport_ImportFormatTest.pass");
}
 
Example #12
Source File: ApNavigator.java    From openjdk-jdk8u-backup 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 #13
Source File: CompilationInfo.java    From netbeans with Apache License 2.0 6 votes vote down vote up
/**
 * Returns tree which was reparsed by an incremental reparse.
 * When the source file wasn't parsed yet or the parse was a full parse
 * this method returns null.
 * <p class="nonnormative">
 * Currently the leaf tree is a MethodTree but this may change in the future.
 * Client of this method is responsible to check the corresponding TreeKind
 * to find out if it may perform on the changed subtree or it needs to
 * reprocess the whole tree.
 * </p>
 * @return {@link TreePath} or null
 * @since 0.31
 */
public @CheckForNull @CheckReturnValue TreePath getChangedTree () {
    checkConfinement();
    if (JavaSource.Phase.PARSED.compareTo (impl.getPhase())>0) {
        return null;
    }
    final Pair<DocPositionRegion,MethodTree> changedTree = impl.getChangedTree();
    if (changedTree == null) {
        return null;
    }
    final CompilationUnitTree cu = impl.getCompilationUnit();
    if (cu == null) {
        return null;
    }
    return TreePath.getPath(cu, changedTree.second());
}
 
Example #14
Source File: CopyClassesRefactoringPlugin.java    From netbeans with Apache License 2.0 6 votes vote down vote up
@Override
public void run(WorkingCopy compiler) throws IOException {
    compiler.toPhase(JavaSource.Phase.RESOLVED);
    CompilationUnitTree cu = compiler.getCompilationUnit();
    if (cu == null) {
        ErrorManager.getDefault().log(ErrorManager.ERROR, "compiler.getCompilationUnit() is null " + compiler); // NOI18N
        return;
    }
    FileObject file = compiler.getFileObject();
    FileObject folder = file.getParent();
    
    final String newName;
    if(folder.getFileObject(oldName, file.getExt()) != null) {
        newName = file.getName();
    } else {
        newName = oldName;
    }
    
    CopyTransformer findVisitor = new CopyTransformer(compiler, oldName, newName, insertImport, oldPackage);
    findVisitor.scan(compiler.getCompilationUnit(), null);
}
 
Example #15
Source File: JavaSourceHelper.java    From netbeans with Apache License 2.0 6 votes vote down vote up
public static ClassTree getTopLevelClassTree(CompilationController controller) {
    String className = controller.getFileObject().getName();

    CompilationUnitTree cu = controller.getCompilationUnit();
    if (cu != null) {
        List<? extends Tree> decls = cu.getTypeDecls();
        for (Tree decl : decls) {
            if (!TreeUtilities.CLASS_TREE_KINDS.contains(decl.getKind())) {
                continue;
            }

            ClassTree classTree = (ClassTree) decl;

            if (classTree.getSimpleName().contentEquals(className) && classTree.getModifiers().getFlags().contains(Modifier.PUBLIC)) {
                return classTree;
            }
        }
    }
    return null;
}
 
Example #16
Source File: TypeAnnotationsPretty.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
private void runField(String code) throws IOException {
    String src = prefix +
            code + "; }" +
            postfix;

    try (JavaFileManager fm = tool.getStandardFileManager(null, null, null)) {
        JavacTaskImpl ct = (JavacTaskImpl) tool.getTask(null, fm, null, null,
                null, Arrays.asList(new MyFileObject(src)));

        for (CompilationUnitTree cut : ct.parse()) {
            JCTree.JCVariableDecl var =
                    (JCTree.JCVariableDecl) ((ClassTree) cut.getTypeDecls().get(0)).getMembers().get(0);
            checkMatch(code, var);
        }
    }
}
 
Example #17
Source File: JavacParserTest.java    From openjdk-jdk8u 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 #18
Source File: JavacParserTest.java    From openjdk-8 with GNU General Public License v2.0 5 votes vote down vote up
CompilationUnitTree getCompilationUnitTree(String code) throws IOException {

        JavacTaskImpl ct = (JavacTaskImpl) tool.getTask(null, null, null, null,
                null, Arrays.asList(new MyFileObject(code)));
        CompilationUnitTree cut = ct.parse().iterator().next();
        return cut;
    }
 
Example #19
Source File: TreeDissector.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
static TreeDissector createBySnippet(TaskFactory.BaseTask bt, Snippet si) {
    String name = si.className();

    Pair<CompilationUnitTree, ClassTree> pair = classes(bt.cuTrees())
            .filter(p -> p.second.getSimpleName().contentEquals(name))
            .findFirst().orElseThrow(() ->
                    new IllegalArgumentException("Class " + name + " is not found."));

    return new TreeDissector(bt, pair.first, pair.second);
}
 
Example #20
Source File: JavacParserTest.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
@Test
void testErrorRecoveryForEnhancedForLoop142381() throws IOException {

    String code = "package test; class Test { " +
            "private void method() { " +
            "java.util.Set<String> s = null; for (a : s) {} } }";

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

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

    CompilationUnitTree cut = ct.parse().iterator().next();

    ClassTree clazz = (ClassTree) cut.getTypeDecls().get(0);
    StatementTree forStatement =
            ((MethodTree) clazz.getMembers().get(0)).getBody().getStatements().get(1);

    assertEquals("testErrorRecoveryForEnhancedForLoop142381",
            Kind.ENHANCED_FOR_LOOP, forStatement.getKind());
    assertFalse("testErrorRecoveryForEnhancedForLoop142381", errors.isEmpty());
}
 
Example #21
Source File: JavaSourceHelper.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public static Collection<String> getImports(CompilationController controller) {
    Set<String> imports = new HashSet<String>();
    CompilationUnitTree cu = controller.getCompilationUnit();

    if (cu != null) {
        List<? extends ImportTree> importTrees = cu.getImports();

        for (ImportTree importTree : importTrees) {
            imports.add(importTree.getQualifiedIdentifier().toString());
        }
    }

    return imports;
}
 
Example #22
Source File: DocLint.java    From jdk8u60 with GNU General Public License v2.0 5 votes vote down vote up
@Override
public Void visitCompilationUnit(CompilationUnitTree tree, Void ignore) {
    if (tree.getPackageName() != null) {
        visitDecl(tree, null);
    }
    return super.visitCompilationUnit(tree, ignore);
}
 
Example #23
Source File: JavacTrees.java    From openjdk-8-source with GNU General Public License v2.0 5 votes vote down vote up
public DocCommentTree getDocCommentTree(TreePath path) {
    CompilationUnitTree t = path.getCompilationUnit();
    Tree leaf = path.getLeaf();
    if (t instanceof JCTree.JCCompilationUnit && leaf instanceof JCTree) {
        JCCompilationUnit cu = (JCCompilationUnit) t;
        if (cu.docComments != null) {
            return cu.docComments.getCommentTree((JCTree) leaf);
        }
    }
    return null;
}
 
Example #24
Source File: TypeAnnotationsPretty.java    From hottub with GNU General Public License v2.0 5 votes vote down vote up
private void runField(String code) throws IOException {
    String src = prefix +
            code + "; }" +
            postfix;

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

    for (CompilationUnitTree cut : ct.parse()) {
        JCTree.JCVariableDecl var =
                (JCTree.JCVariableDecl) ((ClassTree) cut.getTypeDecls().get(0)).getMembers().get(0);
        checkMatch(code, var);
    }
}
 
Example #25
Source File: GenStubs.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 5 votes vote down vote up
public boolean run(String sourcepath, File outdir, List<String> classes) {
    //System.err.println("run: sourcepath:" + sourcepath + " outdir:" + outdir + " classes:" + classes);
    if (sourcepath == null)
        throw new IllegalArgumentException("sourcepath not set");
    if (outdir == null)
        throw new IllegalArgumentException("source output dir not set");

    JavacTool tool = JavacTool.create();
    StandardJavaFileManager fm = tool.getStandardFileManager(null, null, null);

    try {
        fm.setLocation(StandardLocation.SOURCE_OUTPUT, Collections.singleton(outdir));
        fm.setLocation(StandardLocation.SOURCE_PATH, splitPath(sourcepath));
        List<JavaFileObject> files = new ArrayList<JavaFileObject>();
        for (String c: classes) {
            JavaFileObject fo = fm.getJavaFileForInput(
                    StandardLocation.SOURCE_PATH, c, JavaFileObject.Kind.SOURCE);
            if (fo == null)
                error("class not found: " + c);
            else
                files.add(fo);
        }

        JavacTask t = tool.getTask(null, fm, null, null, null, files);
        Iterable<? extends CompilationUnitTree> trees = t.parse();
        for (CompilationUnitTree tree: trees) {
            makeStub(fm, tree);
        }
    } catch (IOException e) {
        error("IO error " + e, e);
    }

    return (errors == 0);
}
 
Example #26
Source File: JavacParserTest.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 5 votes vote down vote up
CompilationUnitTree getCompilationUnitTree(String code) throws IOException {

        JavacTaskImpl ct = (JavacTaskImpl) tool.getTask(null, null, null, null,
                null, Arrays.asList(new MyFileObject(code)));
        CompilationUnitTree cut = ct.parse().iterator().next();
        return cut;
    }
 
Example #27
Source File: Hacks.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public static Scope constructScope(CompilationInfo info, String... importedClasses) {
    StringBuilder clazz = new StringBuilder();

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

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

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

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

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

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

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

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

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

        return new ScannerImpl().scan(cut, info);
    } catch (IOException ex) {
        Exceptions.printStackTrace(ex);
        return null;
    } finally {
    }
}
 
Example #28
Source File: CompletenessStressTest.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
private boolean testBlock(StringWriter writer, SourcePositions sp, String text, CompilationUnitTree cut, BlockTree blockTree) {
    boolean success = true;
    for (StatementTree st : blockTree.getStatements()) {
        if (isLegal(st)) {
            success &= testStatement(writer, sp, text, cut, st);
        }
        if (st instanceof IfTree) {
            IfTree ifTree = (IfTree) st;
            success &= testBranch(writer, sp, text, cut, ifTree.getThenStatement());
            success &= testBranch(writer, sp, text, cut, ifTree.getElseStatement());
        } else if (st instanceof WhileLoopTree) {
            WhileLoopTree whileLoopTree = (WhileLoopTree) st;
            success &= testBranch(writer, sp, text, cut, whileLoopTree.getStatement());
        } else if (st instanceof DoWhileLoopTree) {
            DoWhileLoopTree doWhileLoopTree = (DoWhileLoopTree) st;
            success &= testBranch(writer, sp, text, cut, doWhileLoopTree.getStatement());
        } else if (st instanceof ForLoopTree) {
            ForLoopTree forLoopTree = (ForLoopTree) st;
            success &= testBranch(writer, sp, text, cut, forLoopTree.getStatement());
        } else if (st instanceof LabeledStatementTree) {
            LabeledStatementTree labelTree = (LabeledStatementTree) st;
            success &= testBranch(writer, sp, text, cut, labelTree.getStatement());
        } else if (st instanceof SwitchTree) {
            SwitchTree switchTree = (SwitchTree) st;
            for (CaseTree caseTree : switchTree.getCases()) {
                for (StatementTree statementTree : caseTree.getStatements()) {
                    success &= testBranch(writer, sp, text, cut, statementTree);
                }
            }
        }
    }
    return success;
}
 
Example #29
Source File: JavaSourceHelper.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public static long[] getPosition(JavaSource source, final String methodName) {
    final long[] position = {0, 0};

    try {
        source.runUserActionTask(new AbstractTask<CompilationController>() {

            public void run(CompilationController controller) throws IOException {
                controller.toPhase(Phase.RESOLVED);
                TypeElement classElement = getTopLevelClassElement(controller);
                CompilationUnitTree tree = controller.getCompilationUnit();
                Trees trees = controller.getTrees();
                Tree elementTree;
                Element element = null;

                if (methodName == null) {
                    element = classElement;
                } else {
                    List<ExecutableElement> methods = ElementFilter.methodsIn(classElement.getEnclosedElements());

                    for (ExecutableElement method : methods) {
                        if (method.getSimpleName().toString().equals(methodName)) {
                            element = method;
                            break;
                        }
                    }
                }

                if (element != null) {
                    elementTree = trees.getTree(element);
                    long pos = trees.getSourcePositions().getStartPosition(tree, elementTree);
                    position[0] = tree.getLineMap().getLineNumber(pos) - 1;
                    position[1] = tree.getLineMap().getColumnNumber(pos) - 1;
                }
            }
        }, true);
    } catch (IOException ex) {
    }

    return position;
}
 
Example #30
Source File: CodeGenerator.java    From netbeans with Apache License 2.0 5 votes vote down vote up
static CompilationUnitTree generateCode(WorkingCopy wc, Element te) {
    TreeMaker make = wc.getTreeMaker();
    Tree clazz = new TreeBuilder(make, wc).visit(te);
    CompilationUnitTree cut = make.CompilationUnit(
            te.getKind() == ElementKind.MODULE ? null : make.Identifier(((PackageElement) te.getEnclosingElement()).getQualifiedName()),
            Collections.<ImportTree>emptyList(),
            Collections.singletonList(clazz),
            wc.getCompilationUnit().getSourceFile());

    return cut;
}