com.sun.source.util.SourcePositions Java Examples

The following examples show how to use com.sun.source.util.SourcePositions. 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: RemoveSurroundingCodeAction.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private int[] getBounds(TreeUtilities tu, SourcePositions sp, CompilationUnitTree cut, Tree tree) {
    int[] bounds = {-1, -1};
    if (tree != null) {
        if (tree.getKind() == Tree.Kind.BLOCK) {
            List<? extends StatementTree> stats = ((BlockTree) tree).getStatements();
            if (stats != null && !stats.isEmpty()) {
                bounds[0] = getStart(tu, sp, cut, stats.get(0));
                bounds[1] = getEnd(tu, sp, cut, stats.get(stats.size() - 1));
            }
        } else {
            bounds[0] = getStart(tu, sp, cut, tree);
            bounds[1] = getEnd(tu, sp, cut, tree);
        }
    }
    return bounds;
}
 
Example #2
Source File: UtilitiesTest.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private void assertPositions(Tree t, final SourcePositions sp, final String code, String... golden) {
    final List<String> actual = new ArrayList<String>(golden.length);

    new ErrorAwareTreeScanner<Void, Void>() {
        @Override
        public Void scan(Tree node, Void p) {
            if (node != null) {
                int start = (int) sp.getStartPosition(null, node);
                int end = (int) sp.getEndPosition(null, node);

                if (start >= 0 && end >= 0) {
                    actual.add(code.substring(start, end));
                }
            }
            return super.scan(node, p);
        }
    }.scan(t, null);

    Collections.sort(actual);

    List<String> goldenList = new ArrayList<String>(Arrays.asList(golden));

    Collections.sort(goldenList);

    assertEquals(goldenList, actual);
}
 
Example #3
Source File: AssignResultToVariable.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private StatementTree findExactStatement(CompilationInfo info, BlockTree block, int offset, boolean start) {
    if (offset == (-1)) return null;
    
    SourcePositions sp = info.getTrees().getSourcePositions();
    CompilationUnitTree cut = info.getCompilationUnit();
    
    for (StatementTree t : block.getStatements()) {
        long pos = start ? sp.getStartPosition(info.getCompilationUnit(), t) : sp.getEndPosition( cut, t);

        if (offset == pos) {
            return t;
        }
    }

    return null;
}
 
Example #4
Source File: JavacParserTest.java    From jdk8u60 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 #5
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 #6
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 #7
Source File: JavacParserTest.java    From openjdk-jdk8u-backup 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 #8
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 #9
Source File: WrappingTest.java    From netbeans with Apache License 2.0 6 votes vote down vote up
public void testWrapMethod1() 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.FileNotFound, 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_IF_LONG.name(),
    FmtOptions.wrapThrowsKeyword, WrapStyle.WRAP_IF_LONG.name(),
    FmtOptions.wrapThrowsList, WrapStyle.WRAP_IF_LONG.name());
}
 
Example #10
Source File: VeryPretty.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private void adjustSpans(Iterable<? extends Tree> original, String code) {
    if (tree2Tag == null) {
        return; //nothing to  copy
    }
    
    java.util.List<Tree> linearized = new LinkedList<Tree>();
    if (!new Linearize().scan(original, linearized) != Boolean.TRUE) {
        return; //nothing to  copy
    }
    
        ClassPath empty = ClassPathSupport.createClassPath(new URL[0]);
        ClasspathInfo cpInfo = ClasspathInfo.create(JavaPlatformManager.getDefault().getDefaultPlatform().getBootstrapLibraries(), empty, empty);
        JavacTaskImpl javacTask = JavacParser.createJavacTask(cpInfo, null, null, null, null, null, null, null, Arrays.asList(FileObjects.memoryFileObject("", "Scratch.java", code)));
        com.sun.tools.javac.util.Context ctx = javacTask.getContext();
        JavaCompiler.instance(ctx).genEndPos = true;
        CompilationUnitTree tree = javacTask.parse().iterator().next(); //NOI18N
        SourcePositions sp = JavacTrees.instance(ctx).getSourcePositions();
        ClassTree clazz = (ClassTree) tree.getTypeDecls().get(0);

        new CopyTags(tree, sp).scan(clazz.getModifiers().getAnnotations(), linearized);
}
 
Example #11
Source File: ChangeParamsTransformer.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private List<ExpressionTree> getNewCompatibleArguments(List<? extends VariableTree> parameters) {
    List<ExpressionTree> arguments = new ArrayList();
    ParameterInfo[] pi = paramInfos;
    for (int i = 0; i < pi.length; i++) {
        int originalIndex = pi[i].getOriginalIndex();
        ExpressionTree vt;
        String value;
        if (originalIndex < 0) {
            value = pi[i].getDefaultValue();
        } else {
            value = parameters.get(originalIndex).getName().toString();
        }
        SourcePositions pos[] = new SourcePositions[1];
        vt = workingCopy.getTreeUtilities().parseExpression(value, pos);
        arguments.add(vt);
    }
    return arguments;
}
 
Example #12
Source File: ReplaceConstructorWithBuilderPlugin.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private boolean treeEquals(WorkingCopy copy, Collection<? extends TreePath> value, String defaultValue) {
    if (defaultValue == null) {
        return false;
    }
    String[] values = defaultValue.split(",");
    if(values.length != value.size()) {
        return false;
    }
    for (String defValue : values) {
        defValue = defValue.trim();
        boolean parsed = false;
        if (value instanceof LiteralTree) {
            ExpressionTree parseExpression = copy.getTreeUtilities().parseExpression(defValue, new SourcePositions[1]);
            parsed = parseExpression instanceof LiteralTree;
            if (parsed && !((LiteralTree) value).getValue().equals(((LiteralTree) parseExpression).getValue())) {
                return false;
            }
        }
        if(!parsed && !defValue.equals(value.toString())) {
            return false;
        }
    }
    return true;
}
 
Example #13
Source File: TreeUtilitiesTest.java    From netbeans with Apache License 2.0 6 votes vote down vote up
public void testAttributingVar() throws Exception {
    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("public class Test { private static int I; }");
    }
    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 clazzPath = new TreePath(new TreePath(new TreePath(parameter.getCompilationUnit()),
                                              parameter.getCompilationUnit().getTypeDecls().get(0)),
                    ((ClassTree) parameter.getCompilationUnit().getTypeDecls().get(0)).getMembers().get(1));
            Scope scope = parameter.getTrees().getScope(clazzPath);
            StatementTree st = parameter.getTreeUtilities().parseStatement("{ String s; }", new SourcePositions[1]);
            assertEquals(Kind.BLOCK, st.getKind());
            StatementTree var = st.getKind() == Kind.BLOCK ? ((BlockTree) st).getStatements().get(0) : st;
            parameter.getTreeUtilities().attributeTree(st, scope);
            checkType(parameter, clazzPath, var);
        }
    }, true);
}
 
Example #14
Source File: CopyFinder.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private Iterable<? extends TreePath> fullPrepareThis(TreePath tp) {
    //XXX: is there a faster way to do this?
    Collection<TreePath> result = new LinkedList<TreePath>();
    Scope scope = info.getTrees().getScope(tp);
    TypeElement lastClass = null;

    while (scope != null && scope.getEnclosingClass() != null) {
        if (lastClass != scope.getEnclosingClass()) {
            ExpressionTree thisTree = info.getTreeUtilities().parseExpression("this", new SourcePositions[1]);

            info.getTreeUtilities().attributeTree(thisTree, scope);

            result.add(new TreePath(tp, thisTree));
        }
        
        scope = scope.getEnclosingScope();
    }

    return result;
}
 
Example #15
Source File: JavacParserTest.java    From openjdk-jdk9 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, 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);
    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 #16
Source File: TutorialTest.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public void testNullLiteral() throws Exception {
        testFile = new File(getWorkDir(), "Test.java");
        TestUtilities.copyStringToFile(testFile, 
            "package hierbas.del.litoral;\n\n" +
            "import java.io.*;\n\n" +
            "public class Test {\n" +
            "    public void taragui() {\n" +
            "    }\n" +
            "}\n"
            );
        JavaSource tutorialSource = JavaSource.forFileObject(FileUtil.toFileObject(testFile));
//        final String statementText = "new Runnable() { };";
//        final String statementText = "System.err.println(\"Not interested in.\");";
        final String statementText = "System.err.println(null);";
        
        Task task = new Task<WorkingCopy>() {

            public void run(WorkingCopy workingCopy) throws java.io.IOException {
                workingCopy.toPhase(Phase.RESOLVED);
                TreeMaker make = workingCopy.getTreeMaker();
                
                SourcePositions[] positions = new SourcePositions[1];
                final TreeUtilities treeUtils = workingCopy.getTreeUtilities();
                StatementTree body = treeUtils.parseStatement(statementText, positions);
                System.err.println(TreeMakerDemo.reverse(body));
            }
            
        };

        tutorialSource.runModificationTask(task).commit();
        
        // print the result to the System.err to see the changes in console.
        BufferedReader in = new BufferedReader(new FileReader(testFile));
        PrintStream out = System.out;
        String str;
        while ((str = in.readLine()) != null) {
            out.println(str);
        }
        in.close();
    }
 
Example #17
Source File: JavaSourceTest.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public FindMethodRegionsVisitor (final Document doc, final SourcePositions pos, String methodName) {
    assert doc != null;
    assert pos != null;
    assert methodName != null;
    this.doc = doc;
    this.pos = pos;
    this.methodName = methodName;
}
 
Example #18
Source File: ElementVisitor.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private long[] getPosition( Element e ) {
    Trees trees = cc.getTrees();
    CompilationUnitTree cut = cc.getCompilationUnit();
    Tree t = trees.getTree(e);        
    if ( t == null ) {            
        return new long[]{-1,-1};
    }        
    SourcePositions sourcePositions = trees.getSourcePositions();        
    return new long[] {sourcePositions.getStartPosition(cut, t),sourcePositions.getEndPosition(cut, t)};
}
 
Example #19
Source File: Tiny.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private static boolean tryResolveIdentifier(CompilationInfo info, TreePath place, 
        TypeMirror expectedType, Set<Element> resolved, String ident) {
    SourcePositions[] positions = new SourcePositions[1];
    ExpressionTree et = info.getTreeUtilities().parseExpression(ident, positions);
    TypeMirror unqType = info.getTreeUtilities().attributeTree(et, info.getTrees().getScope(place));
    Element e = info.getTrees().getElement(new TreePath(place, et));
    if (!Utilities.isValidType(unqType) || e == null || 
            (e.getKind() != ElementKind.FIELD && e.getKind() != ElementKind.ENUM_CONSTANT)) {
        return false;
    }
    if (!resolved.add(e)) {
        return false;
    }
    return info.getTypes().isAssignable(unqType, expectedType);
}
 
Example #20
Source File: Ifs.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private static boolean caretInsideToLevelElseKeyword(HintContext ctx) {
    IfTree it = (IfTree) ctx.getPath().getLeaf();
    SourcePositions sp = ctx.getInfo().getTrees().getSourcePositions();
    CompilationUnitTree cut = ctx.getInfo().getCompilationUnit();
    int elsePos = (int) sp.getStartPosition(cut, it.getElseStatement());
    
    
    return caretInsidePreviousToken(ctx, elsePos, JavaTokenId.ELSE);
}
 
Example #21
Source File: UtilitiesTest.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public void testPositionsForCorrectStatement() throws Exception {
    prepareTest("test/Test.java", "package test; public class Test{}");

    SourcePositions[] positions = new SourcePositions[1];
    Collection<Diagnostic<? extends JavaFileObject>> errors = new LinkedList<Diagnostic<? extends JavaFileObject>>();
    String code = "assert true;";
    Tree result = Utilities.parseAndAttribute(info, code, null, positions, errors);

    assertTrue(errors.isEmpty());
    assertPositions(result, positions[0], code, "assert true;", "true");
}
 
Example #22
Source File: AnnotationTest.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public void testParameterAnnotations() throws Exception {
    testFile = new File(getWorkDir(), "Test.java");
    String code = "package hierbas.del.litoral;\n" +
                  "\n" +
                  "public class Test {\n\n" +
                  "    public Test() {\n" +
                  "    }\n\n" +
                  "    public void test() {\n" +
                  "    }\n" +
                  "}\n";

    code = Reformatter.reformat(code, CodeStyle.getDefault(FileUtil.toFileObject(testFile)));
    TestUtilities.copyStringToFile(testFile, code);

    JavaSource src = getJavaSource(testFile);
    Task task = new Task<WorkingCopy>() {

        public void run(final WorkingCopy workingCopy) throws IOException {
            workingCopy.toPhase(Phase.RESOLVED);

            NewClassTree nct = (NewClassTree) workingCopy.getTreeUtilities().parseExpression("new Object() { public int a(@Test1(a=1) @Test2(b=2) int i, @Test1 @Test2 int j) { return 0; }", new SourcePositions[1]);
            ClassTree clazz = (ClassTree) workingCopy.getCompilationUnit().getTypeDecls().get(0);
            workingCopy.rewrite(clazz, workingCopy.getTreeMaker().addClassMember(clazz, nct.getClassBody().getMembers().get(0)));
        }

    };
    src.runModificationTask(task).commit();
    String res = TestUtilities.copyFileToString(testFile);
    String formattedRes = Reformatter.reformat(res, CodeStyle.getDefault(FileUtil.toFileObject(testFile)));
    //System.err.println(res);
    res = res.replaceAll("\n[ ]*\n", "\n");
    //System.err.println(formattedRes);
    formattedRes = formattedRes.replaceAll("\n[ ]*\n", "\n"); //XXX: workaround for a bug in reformatter
    assertEquals(formattedRes, res);
}
 
Example #23
Source File: Ifs.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@Hint(displayName="#DN_ToOrIf", description="#DESC_ToOrIf", category="suggestions", hintKind=Hint.Kind.ACTION)
@TriggerPattern("if ($cond1) $then; else if ($cond2) $then; else $else$;")
@Messages({"ERR_ToOrIf=",
           "FIX_ToOrIf=Join ifs using ||"})
public static ErrorDescription toOrIf(HintContext ctx) {
    SourcePositions sp = ctx.getInfo().getTrees().getSourcePositions();
    CompilationUnitTree cut = ctx.getInfo().getCompilationUnit();
    boolean caretAccepted = ctx.getCaretLocation() <= sp.getStartPosition(cut, ctx.getPath().getLeaf()) + 2 || caretInsideToLevelElseKeyword(ctx);
    if (!caretAccepted) return null;
    return ErrorDescriptionFactory.forSpan(ctx, ctx.getCaretLocation(), ctx.getCaretLocation(), Bundle.ERR_ToOrIf(), JavaFixUtilities.rewriteFix(ctx, Bundle.FIX_ToOrIf(), ctx.getPath(), "if ($cond1 || $cond2) $then; else $else$;"));
}
 
Example #24
Source File: ClassMetrics.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@Hint(
    displayName = "#DN_ClassAnonymousTooComplex",
    description = "#DESC_ClassAnonymousTooComplex",
    category = "metrics",
    options = { Hint.Options.HEAVY, Hint.Options.QUERY },
    enabled = false
)
@UseOptions(OPTION_ANONYMOUS_COMPLEXITY_LIMIT)
@TriggerPatterns({
    @TriggerPattern("new $classname<$tparams$>($params$) { $members$; }"),
    @TriggerPattern("$expr.new $classname<$tparams$>($params$) { $members$; }"),
    @TriggerPattern("new $classname($params$) { $members$; }"),
    @TriggerPattern("$expr.new $classname($params$) { $members$; }"),
})
public static ErrorDescription tooComplexAnonymousClass(HintContext ctx) {
    CyclomaticComplexityVisitor v = new CyclomaticComplexityVisitor();
    v.scan(ctx.getPath(), null);
    
    int complexity = v.getComplexity();
    int limit = ctx.getPreferences().getInt(OPTION_ANONYMOUS_COMPLEXITY_LIMIT, 
            DEFAULT_ANONYMOUS_COMPLEXITY_LIMIT);
    if (complexity > limit) {
        CompilationInfo info = ctx.getInfo();
        SourcePositions pos = info.getTrees().getSourcePositions();
        NewClassTree nct = (NewClassTree)ctx.getPath().getLeaf();
        long start = pos.getStartPosition(info.getCompilationUnit(), nct);
        long mstart = pos.getStartPosition(info.getCompilationUnit(), nct.getClassBody());
        return ErrorDescriptionFactory.forSpan(ctx, 
                (int)start, (int)mstart,
                TEXT_ClassAnonymousTooComplex(complexity));
    } else {
        return null;
    }
}
 
Example #25
Source File: WrongStringComparison.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private static boolean checkInsideGeneratedEquals(HintContext ctx, TreePath treePath, Tree left, Tree right) {
    CompilationInfo info = ctx.getInfo();
    TreePath sourcePathParent = treePath.getParentPath();

    if (sourcePathParent.getLeaf().getKind() != Kind.CONDITIONAL_AND) { //performance
        return false;
    }
    
    SourcePositions sp = info.getTrees().getSourcePositions();
    Scope s = info.getTrees().getScope(sourcePathParent);
    
    String leftText = info.getText().substring((int) sp.getStartPosition(info.getCompilationUnit(), left), (int) sp.getEndPosition(info.getCompilationUnit(), left) + 1);
    String rightText = info.getText().substring((int) sp.getStartPosition(info.getCompilationUnit(), right), (int) sp.getEndPosition(info.getCompilationUnit(), right) + 1);
    String code = leftText + " != " + rightText + " && (" + leftText + "== null || !" + leftText + ".equals(" + rightText + "))"; // NOI18N
    ExpressionTree correct = info.getTreeUtilities().parseExpression(code, new SourcePositions[1]);

    info.getTreeUtilities().attributeTree(correct, s);

    TreePath correctPath = new TreePath(sourcePathParent.getParentPath(), correct);
    
    String originalCode = info.getText().substring((int) sp.getStartPosition(info.getCompilationUnit(), sourcePathParent.getLeaf()), (int) sp.getEndPosition(info.getCompilationUnit(), sourcePathParent.getLeaf()) + 1);
    ExpressionTree original = info.getTreeUtilities().parseExpression(originalCode, new SourcePositions[1]);
    
    info.getTreeUtilities().attributeTree(original, s);

    TreePath originalPath = new TreePath(sourcePathParent.getParentPath(), original);

    return Matcher.create(info)./*XXX: setCancel(cancel).*/setSearchRoot(originalPath).setTreeTopSearch().match(Pattern.createSimplePattern(correctPath)).iterator().hasNext();
}
 
Example #26
Source File: TreeUtilities.java    From netbeans with Apache License 2.0 5 votes vote down vote up
/**Parses given static block.
 * 
 * @param block block code
 * @param sourcePositions return value - new SourcePositions for the new tree
 * @return parsed {@link BlockTree} or null?
 */
public BlockTree parseStaticBlock(String block, SourcePositions[] sourcePositions) {
    return doParse("{ class C { " + block + " }", sourcePositions, "{ class C { ".length(), p -> {
        JCClassDecl decl = (JCClassDecl) ((BlockTree) p.parseStatement()).getStatements().get(0);
        return decl.defs.head.getKind() == Kind.BLOCK ? (BlockTree) decl.defs.head : null; //check result
    });
}
 
Example #27
Source File: MethodArgumentsScanner.java    From netbeans with Apache License 2.0 5 votes vote down vote up
/** Creates a new instance of MethodArgumentsScanner */
public MethodArgumentsScanner(int offset, CompilationUnitTree tree,
                              SourcePositions positions, boolean methodInvocation,
                              ASTOperationCreationDelegate positionDelegate) {
    this.offset = offset;
    this.tree = tree;
    this.positions = positions;
    this.lineMap = tree.getLineMap();
    this.methodInvocation = methodInvocation;
    this.positionDelegate = positionDelegate;
}
 
Example #28
Source File: JavaParser.java    From manifold with Apache License 2.0 5 votes vote down vote up
public boolean parseText( String src, List<CompilationUnitTree> trees, Consumer<SourcePositions> sourcePositions,
                          Consumer<DocTrees> docTrees, DiagnosticCollector<JavaFileObject> errorHandler )
{
  init();

  ArrayList<JavaFileObject> javaStringObjects = new ArrayList<>();
  javaStringObjects.add( new StringJavaFileObject( "sample", src ) );
  StringWriter errors = new StringWriter();
  BasicJavacTask javacTask = (BasicJavacTask)_javac.getTask(
    errors, _mfm, errorHandler, Collections.singletonList( "-proc:none" ), null, javaStringObjects );
  try
  {
    initTypeProcessing( javacTask, Collections.singleton( "sample" ) );
    Iterable<? extends CompilationUnitTree> iterable = javacTask.parse();
    if( errors.getBuffer().length() > 0 )
    {
      System.err.println( errors.getBuffer() );
    }
    for( CompilationUnitTree x : iterable )
    {
      trees.add( x );
    }
    if( sourcePositions != null )
    {
      sourcePositions.accept( Trees.instance( javacTask ).getSourcePositions() );
    }
    if( docTrees != null )
    {
      docTrees.accept( DocTrees.instance( javacTask ) );
    }
    return true;
  }
  catch( Exception e )
  {
    return false;
  }
}
 
Example #29
Source File: JavadocUtilities.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private static boolean isInHeader(CompilationInfo info, MethodTree tree, int offset) {
    CompilationUnitTree cut = info.getCompilationUnit();
    SourcePositions sp = info.getTrees().getSourcePositions();
    long lastKnownOffsetInHeader = sp.getStartPosition(cut, tree);
    
    List<? extends ExpressionTree> throwz;
    List<? extends VariableTree> params;
    List<? extends TypeParameterTree> typeparams;
    
    if ((throwz = tree.getThrows()) != null && !throwz.isEmpty()) {
        lastKnownOffsetInHeader = sp.getEndPosition(cut, throwz.get(throwz.size() - 1));
    } else if ((params = tree.getParameters()) != null && !params.isEmpty()) {
        lastKnownOffsetInHeader = sp.getEndPosition(cut, params.get(params.size() - 1));
    } else if ((typeparams = tree.getTypeParameters()) != null && !typeparams.isEmpty()) {
        lastKnownOffsetInHeader = sp.getEndPosition(cut, typeparams.get(typeparams.size() - 1));
    } else if (tree.getReturnType() != null) {
        lastKnownOffsetInHeader = sp.getEndPosition(cut, tree.getReturnType());
    } else if (tree.getModifiers() != null) {
        lastKnownOffsetInHeader = sp.getEndPosition(cut, tree.getModifiers());
    }
    
    TokenSequence<JavaTokenId> ts = info.getTreeUtilities().tokensFor(tree);
    
    ts.move((int) lastKnownOffsetInHeader);
    
    while (ts.moveNext()) {
        if (ts.token().id() == JavaTokenId.LBRACE || ts.token().id() == JavaTokenId.SEMICOLON) {
            return offset < ts.offset();
        }
    }
    
    return false;
}
 
Example #30
Source File: BaseTask.java    From netbeans with Apache License 2.0 5 votes vote down vote up
List<Tree> getArgumentsUpToPos(Env env, Iterable<? extends ExpressionTree> args, int startPos, int position, boolean strict) {
    List<Tree> ret = new ArrayList<>();
    CompilationUnitTree root = env.getRoot();
    SourcePositions sourcePositions = env.getSourcePositions();
    if (args == null) {
        return null; //TODO: member reference???
    }
    for (ExpressionTree e : args) {
        int pos = (int) sourcePositions.getEndPosition(root, e);
        if (pos != Diagnostic.NOPOS && (position > pos || !strict && position == pos)) {
            startPos = pos;
            ret.add(e);
        } else {
            break;
        }
    }
    if (startPos < 0) {
        return ret;
    }
    if (position >= startPos) {
        TokenSequence<JavaTokenId> last = findLastNonWhitespaceToken(env, startPos, position);
        if (last == null) {
            if (!strict && !ret.isEmpty()) {
                ret.remove(ret.size() - 1);
                return ret;
            }
        } else if (last.token().id() == JavaTokenId.LPAREN || last.token().id() == JavaTokenId.COMMA) {
            return ret;
        }
    }
    return null;
}