Java Code Examples for com.sun.source.tree.VariableTree#getInitializer()

The following examples show how to use com.sun.source.tree.VariableTree#getInitializer() . 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: JavacParserTest.java    From jdk8u60 with GNU General Public License v2.0 6 votes vote down vote up
@Test
void testPreferredPositionForBinaryOp() throws IOException {

    String code = "package test; public class Test {"
            + "private void test() {"
            + "Object o = null; boolean b = o != null && o instanceof String;"
            + "} private Test() {}}";

    CompilationUnitTree cut = getCompilationUnitTree(code);
    ClassTree clazz = (ClassTree) cut.getTypeDecls().get(0);
    MethodTree method = (MethodTree) clazz.getMembers().get(0);
    VariableTree condSt = (VariableTree) method.getBody().getStatements().get(1);
    BinaryTree cond = (BinaryTree) condSt.getInitializer();

    JCTree condJC = (JCTree) cond;
    int condStartPos = code.indexOf("&&");
    assertEquals("testPreferredPositionForBinaryOp",
            condStartPos, condJC.pos);
}
 
Example 2
Source File: ConstantNameHint.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private static boolean checkZeroSizeArray(CompilationInfo info, TreePath val) {
    if (val.getLeaf().getKind() != Tree.Kind.VARIABLE) {
        return false;
    }
    VariableTree vt = (VariableTree)val.getLeaf();
    ExpressionTree xpr = vt.getInitializer();
    if (xpr == null) {
        return false;
    }
    if (xpr.getKind() == Tree.Kind.NEW_ARRAY) {
        NewArrayTree nat = (NewArrayTree)xpr;
        List<? extends ExpressionTree> dims = nat.getDimensions();
        if (dims != null && !dims.isEmpty()) {
            Object size = ArithmeticUtilities.compute(info, 
                    new TreePath(
                        new TreePath(val, xpr),
                        dims.get(dims.size() -1)), 
                    true);
            return ArithmeticUtilities.isRealValue(size) && Integer.valueOf(0).equals(size);
        } else {
            return nat.getInitializers() != null && nat.getInitializers().isEmpty();
        }
    }
    return false;
}
 
Example 3
Source File: JavacParserTest.java    From openjdk-8 with GNU General Public License v2.0 6 votes vote down vote up
@Test
void testPreferredPositionForBinaryOp() throws IOException {

    String code = "package test; public class Test {"
            + "private void test() {"
            + "Object o = null; boolean b = o != null && o instanceof String;"
            + "} private Test() {}}";

    CompilationUnitTree cut = getCompilationUnitTree(code);
    ClassTree clazz = (ClassTree) cut.getTypeDecls().get(0);
    MethodTree method = (MethodTree) clazz.getMembers().get(0);
    VariableTree condSt = (VariableTree) method.getBody().getStatements().get(1);
    BinaryTree cond = (BinaryTree) condSt.getInitializer();

    JCTree condJC = (JCTree) cond;
    int condStartPos = code.indexOf("&&");
    assertEquals("testPreferredPositionForBinaryOp",
            condStartPos, condJC.pos);
}
 
Example 4
Source File: JavaFixUtilitiesTest.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private void performArithmeticTest(String orig, String nue) throws Exception {
    String code = replace("0");

    prepareTest("Test.java", code);
    ClassTree clazz = (ClassTree) info.getCompilationUnit().getTypeDecls().get(0);
    VariableTree variable = (VariableTree) clazz.getMembers().get(1);
    ExpressionTree init = variable.getInitializer();
    TreePath tp = new TreePath(new TreePath(new TreePath(new TreePath(info.getCompilationUnit()), clazz), variable), init);
    Fix fix = JavaFixUtilities.rewriteFix(info, "A", tp, orig, Collections.<String, TreePath>emptyMap(), Collections.<String, Collection<? extends TreePath>>emptyMap(), Collections.<String, String>emptyMap(), Collections.<String, TypeMirror>emptyMap(), Collections.<String, String>emptyMap());
    fix.implement();

    String golden = replace(nue);
    String out = doc.getText(0, doc.getLength());

    assertEquals(golden, out);

    LifecycleManager.getDefault().saveAll();
}
 
Example 5
Source File: ImplementAllAbstractMethods.java    From netbeans with Apache License 2.0 6 votes vote down vote up
protected boolean generateClassBody(TreePath p) throws Exception {
    Element e = copy.getTrees().getElement(p);
    boolean isUsableElement = e != null && (e.getKind().isClass() || e.getKind().isInterface());
    if (isUsableElement) {
        return true;
    }
    if (e.getKind() == ElementKind.ENUM_CONSTANT) {
        VariableTree var = (VariableTree) p.getLeaf();
        if (var.getInitializer() != null && var.getInitializer().getKind() == Kind.NEW_CLASS) {
            NewClassTree nct = (NewClassTree) var.getInitializer();
            if (nct.getClassBody() != null) {
                return true;
            }
        }
    }
    return !generateClassBody2(copy, p);
}
 
Example 6
Source File: JavacParserTest.java    From openjdk-jdk8u with GNU General Public License v2.0 6 votes vote down vote up
@Test
void testPreferredPositionForBinaryOp() throws IOException {

    String code = "package test; public class Test {"
            + "private void test() {"
            + "Object o = null; boolean b = o != null && o instanceof String;"
            + "} private Test() {}}";

    CompilationUnitTree cut = getCompilationUnitTree(code);
    ClassTree clazz = (ClassTree) cut.getTypeDecls().get(0);
    MethodTree method = (MethodTree) clazz.getMembers().get(0);
    VariableTree condSt = (VariableTree) method.getBody().getStatements().get(1);
    BinaryTree cond = (BinaryTree) condSt.getInitializer();

    JCTree condJC = (JCTree) cond;
    int condStartPos = code.indexOf("&&");
    assertEquals("testPreferredPositionForBinaryOp",
            condStartPos, condJC.pos);
}
 
Example 7
Source File: ToggleBreakpointActionProvider.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private static boolean isBreakable(TreePath path) {
    Tree tree = path.getLeaf();
    switch (tree.getKind()) {
        case BLOCK:
        case ANNOTATION_TYPE:
        case CLASS:
        case ENUM:
        case INTERFACE:
        case COMPILATION_UNIT:
        case IMPORT:
        case MODIFIERS:
        case EMPTY_STATEMENT:
            return false;
    }
    while (path != null) {
        tree = path.getLeaf();
        Tree.Kind kind = tree.getKind();
        if (kind == Tree.Kind.IMPORT) return false;
        if (kind == Tree.Kind.VARIABLE) {
            VariableTree varTree = (VariableTree)tree;
            if (varTree.getInitializer() == null) {
                return false;
            }
        }
        path = path.getParentPath();
    }
    return true;
}
 
Example 8
Source File: JavacParserTest.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
@Test
void testVoidLambdaParameter() throws IOException {
    String code = "package t; class Test { " +
            "Runnable r = (void v) -> { };" +
            "}";
    DiagnosticCollector<JavaFileObject> coll =
            new DiagnosticCollector<>();
    JavacTaskImpl ct = (JavacTaskImpl) tool.getTask(null, fm, coll, null,
            null, Arrays.asList(new MyFileObject(code)));

    CompilationUnitTree cut = ct.parse().iterator().next();
    ClassTree clazz = (ClassTree) cut.getTypeDecls().get(0);
    VariableTree field = (VariableTree) clazz.getMembers().get(0);

    assertEquals("actual kind: " + field.getInitializer().getKind(),
                 field.getInitializer().getKind(),
                 Kind.LAMBDA_EXPRESSION);

    LambdaExpressionTree lambda = (LambdaExpressionTree) field.getInitializer();

    assertEquals("actual parameters: " + lambda.getParameters().size(),
                 lambda.getParameters().size(),
                 1);

    Tree paramType = lambda.getParameters().get(0).getType();

    assertEquals("actual parameter type: " + paramType.getKind(),
                 paramType.getKind(),
                 Kind.PRIMITIVE_TYPE);

    TypeKind primitiveTypeKind = ((PrimitiveTypeTree) paramType).getPrimitiveTypeKind();

    assertEquals("actual parameter type: " + primitiveTypeKind,
                 primitiveTypeKind,
                 TypeKind.VOID);
}
 
Example 9
Source File: ArraysTest.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public void test162485a() throws Exception {
    testFile = new File(getWorkDir(), "Test.java");
    TestUtilities.copyStringToFile(testFile, 
        "package hierbas.del.litoral;\n" +
        "\n" +
        "public class Test {\n" +
        "    Object test = new int[2];\n" +
        "}\n"
        );
    String golden =
        "package hierbas.del.litoral;\n" +
        "\n" +
        "public class Test {\n" +
        "    Object test = {{1}};\n" +
        "}\n";
    JavaSource src = getJavaSource(testFile);
    Task<WorkingCopy> task = 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);
            VariableTree var = (VariableTree) clazz.getMembers().get(1);
            NewArrayTree nat = (NewArrayTree) var.getInitializer();
            NewArrayTree dim2 = make.NewArray(null, Collections.<ExpressionTree>emptyList(), Collections.singletonList(make.Literal(Integer.valueOf(1))));
            NewArrayTree newTree = make.NewArray(null, Collections.<ExpressionTree>emptyList(), Collections.<ExpressionTree>singletonList(dim2));
            workingCopy.rewrite(nat, newTree);
        }

    };
    src.runModificationTask(task).commit();
    String res = TestUtilities.copyFileToString(testFile);
    //System.err.println(res);
    assertEquals(golden, res);
}
 
Example 10
Source File: CreateElementUtilities.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private static List<? extends TypeMirror> computeVariableDeclaration(Set<ElementKind> types, CompilationInfo info, TreePath parent, Tree error, int offset) {
    VariableTree vt = (VariableTree) parent.getLeaf();
    
    if (vt.getInitializer() == error) {
        types.add(ElementKind.PARAMETER);
        types.add(ElementKind.LOCAL_VARIABLE);
        types.add(ElementKind.FIELD);
        
        return Collections.singletonList(info.getTrees().getTypeMirror(new TreePath(parent, vt.getType())));
    }
    
    TreePath context = parent.getParentPath();
    if (vt.getType() != error || context == null) {
        return null;
    }

    switch (context.getLeaf().getKind()) {
        case ENHANCED_FOR_LOOP:
            ExpressionTree iterableTree = ((EnhancedForLoopTree) context.getLeaf()).getExpression();
            TreePath iterablePath = new TreePath(context, iterableTree);
            TypeMirror type = getIterableGenericType(info, iterablePath);
            types.add(ElementKind.LOCAL_VARIABLE);
            return Collections.singletonList(type);
        default:
            types.add(ElementKind.CLASS);
            return Collections.<TypeMirror>emptyList();
    }
}
 
Example 11
Source File: NullAway.java    From NullAway with MIT License 5 votes vote down vote up
@Override
public Description matchVariable(VariableTree tree, VisitorState state) {
  if (!matchWithinClass) {
    return Description.NO_MATCH;
  }
  VarSymbol symbol = ASTHelpers.getSymbol(tree);
  if (symbol.type.isPrimitive() && tree.getInitializer() != null) {
    return doUnboxingCheck(state, tree.getInitializer());
  }
  if (!symbol.getKind().equals(ElementKind.FIELD)) {
    return Description.NO_MATCH;
  }
  ExpressionTree initializer = tree.getInitializer();
  if (initializer != null) {
    if (!symbol.type.isPrimitive() && !skipDueToFieldAnnotation(symbol)) {
      if (mayBeNullExpr(state, initializer)) {
        final ErrorMessage errorMessage =
            new ErrorMessage(
                MessageTypes.ASSIGN_FIELD_NULLABLE,
                "assigning @Nullable expression to @NonNull field");
        return errorBuilder.createErrorDescriptionForNullAssignment(
            errorMessage, initializer, buildDescription(tree), state);
      }
    }
  }
  return Description.NO_MATCH;
}
 
Example 12
Source File: ExpectedTypeResolver.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@Override
public List<? extends TypeMirror> visitVariable(VariableTree node, Object p) {
    if (theExpression == null) {
        if (node.getInitializer() == null) {
            return null;
        }
        initExpression(node.getInitializer());
    }
    if (theExpression.getLeaf() == node.getInitializer()) {
        // the expression must be assiganble to the variable.
        this.expectedTree = new TreePath(getCurrentPath(), node.getType());
        return Collections.singletonList(info.getTrees().getTypeMirror(getCurrentPath()));
    }
    return null;
}
 
Example 13
Source File: CreateElementUtilities.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private static List<? extends TypeMirror> computeVariableDeclaration(Set<ElementKind> types, CompilationInfo info, TreePath parent, Tree error, int offset) {
    VariableTree vt = (VariableTree) parent.getLeaf();
    
    if (vt.getInitializer() == error) {
        types.add(ElementKind.PARAMETER);
        types.add(ElementKind.LOCAL_VARIABLE);
        types.add(ElementKind.FIELD);
        
        return Collections.singletonList(info.getTrees().getTypeMirror(new TreePath(parent, vt.getType())));
    }
    
    TreePath context = parent.getParentPath();
    if (vt.getType() != error || context == null) {
        return null;
    }

    switch (context.getLeaf().getKind()) {
        case ENHANCED_FOR_LOOP:
            ExpressionTree iterableTree = ((EnhancedForLoopTree) context.getLeaf()).getExpression();
            TreePath iterablePath = new TreePath(context, iterableTree);
            TypeMirror type = getIterableGenericType(info, iterablePath);
            types.add(ElementKind.LOCAL_VARIABLE);
            return Collections.singletonList(type);
        default:
            types.add(ElementKind.CLASS);
            return Collections.<TypeMirror>emptyList();
    }
}
 
Example 14
Source File: SyntetickejTest.java    From netbeans with Apache License 2.0 4 votes vote down vote up
public void testEmptyStaticBlockSemicolon() throws Exception{
    testFile = new File(getWorkDir(), "Test.java");
    TestUtilities.copyStringToFile(testFile, 
        "package tohle;\n" +
        "\n" +
        "public class Main {\n" +
        "\n" +
        "    static enum Whorehouse {\n" +
        "        /** first prostitute */\n" +
        "        PrvniDevka,\n" +
        "        /** second prostitue */\n" +
        "        DruhaDevka,\n" +
        "        /** third prostitute */\n" +
        "        TretiDevka;\n" +
        "    };\n" + // the semicolon is strange here -- shouldn't be there, 
        "    \n" + // but it is correct and we have to handle such a situation
        "    void method() {\n" +
        "        Object o = null;\n" +
        "        String s = o;\n" +
        "    }\n" +
        "}\n");
    String golden =
        "package tohle;\n" +
        "\n" +
        "public class Main {\n" +
        "\n" +
        "    static enum Whorehouse {\n" +
        "        /** first prostitute */\n" +
        "        PrvniDevka,\n" +
        "        /** second prostitue */\n" +
        "        DruhaDevka,\n" +
        "        /** third prostitute */\n" +
        "        TretiDevka;\n" +
        "    };\n" +
        "    \n" +
        "    void method() {\n" +
        "        Object o = null;\n" +
        "        String s = (String) o;\n" +
        "    }\n" +
        "}\n";
    
    JavaSource src = getJavaSource(testFile);
    Task task = new Task<WorkingCopy>() {

        public void run(WorkingCopy workingCopy) throws IOException{
            workingCopy.toPhase(Phase.RESOLVED);
            TreeMaker make = workingCopy.getTreeMaker();
            CompilationUnitTree cut = workingCopy.getCompilationUnit();
            ClassTree clazz = (ClassTree) cut.getTypeDecls().get(0);
            MethodTree method = (MethodTree) clazz.getMembers().get(2);
            VariableTree var = (VariableTree) method.getBody().getStatements().get(1);
            ExpressionTree init = var.getInitializer();
            ExpressionTree cast = make.TypeCast(make.Identifier("String"), init);
            workingCopy.rewrite(init, cast);
        }

    };
    src.runModificationTask(task).commit();
    String res = TestUtilities.copyFileToString(testFile);
    //System.err.println(res);
    assertEquals(golden, res);
}
 
Example 15
Source File: AddCastTest.java    From netbeans with Apache License 2.0 4 votes vote down vote up
public void testAddCastInForWithoutSteps() throws Exception {
    testFile = new File(getWorkDir(), "Test.java");
    TestUtilities.copyStringToFile(testFile, 
        "package hierbas.del.litoral;\n\n" +
        "import java.util.*;\n\n" +
        "public class Test<E> {\n" +
        "    public void cast() {\n" +
        "        Object o = null;\n" +
        "        for (int i = 0; i < 5; ) {\n" +
        "            String s = o;\n" +
        "        }\n" +
        "    }\n" +
        "}\n"
        );
    String golden =
        "package hierbas.del.litoral;\n\n" +
        "import java.util.*;\n\n" +
        "public class Test<E> {\n" +
        "    public void cast() {\n" +
        "        Object o = null;\n" +
        "        for (int i = 0; i < 5; ) {\n" +
        "            String s = (String) o;\n" +
        "        }\n" +
        "    }\n" +
        "}\n";
    JavaSource src = getJavaSource(testFile);
    
    Task<WorkingCopy> task = 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);
            MethodTree method = (MethodTree) clazz.getMembers().get(1);
            ForLoopTree forLoop = (ForLoopTree) method.getBody().getStatements().get(1);
            BlockTree block = (BlockTree) forLoop.getStatement();
            VariableTree vt = (VariableTree) block.getStatements().get(0);
            ExpressionTree init = vt.getInitializer();
            ExpressionTree cast = make.TypeCast(make.Identifier("String"), init);
            workingCopy.rewrite(init, cast);
        }

    };
    src.runModificationTask(task).commit();
    String res = TestUtilities.copyFileToString(testFile);
    //System.err.println(res);
    assertEquals(golden, res);
}
 
Example 16
Source File: SwitchExpressionTest.java    From netbeans with Apache License 2.0 4 votes vote down vote up
/**
 * Rewrite Switch Expression cases.
 *
 * @throws IOException
 */
private void rewriteSwitchExpression() throws IOException {

    JavaSource js = getJavaSource();
    assertNotNull(js);

    Task<WorkingCopy> task = new Task<WorkingCopy>() {

        public void run(WorkingCopy workingCopy) throws IOException {
            workingCopy.toPhase(JavaSource.Phase.RESOLVED);
            CompilationUnitTree cut = workingCopy.getCompilationUnit();
            TreeMaker make = workingCopy.getTreeMaker();
            ClassTree clazz = (ClassTree) cut.getTypeDecls().get(0);
            MethodTree method = (MethodTree) clazz.getMembers().get(1);
            List<CaseTree> newCases = new ArrayList<>();
            VariableTree switcExpression = (VariableTree) ((BlockTree) method.getBody()).getStatements().get(0);
            Tree switchBlock = switcExpression.getInitializer();
            List<? extends CaseTree> cases;
            List<ExpressionTree> patterns = new ArrayList<>();
            boolean switchExpressionFlag = switchBlock.getKind().toString().equals(TreeShims.SWITCH_EXPRESSION);
            if (switchExpressionFlag) {
                cases = TreeShims.getCases(switchBlock);
            } else {
                cases = ((SwitchTree) switchBlock).getCases();
            }
            for (Iterator<? extends CaseTree> it = cases.iterator(); it.hasNext();) {
                CaseTree ct = it.next();
                patterns.addAll(TreeShims.getExpressions(ct));
                List<StatementTree> statements;
                if (ct.getStatements() == null) {
                    statements = new ArrayList<>(((JCTree.JCCase) ct).stats);
                } else {
                    statements = new ArrayList<>(ct.getStatements());
                }
                if (statements.isEmpty()) {
                    if (it.hasNext()) {
                        continue;
                    }
                }
                Set<Element> seenVariables = new HashSet<>();
                int idx = 0;
                for (StatementTree statement : new ArrayList<>(statements)) {
                    Tree body = make.Block(statements, false);
                    if (statements.size() == 1) {
                        if (statements.get(0).getKind() == Tree.Kind.EXPRESSION_STATEMENT
                                || statements.get(0).getKind() == Tree.Kind.THROW
                                || statements.get(0).getKind() == Tree.Kind.BLOCK) {
                            body = statements.get(0);
                        }
                    }
                    newCases.add(make.Case(patterns, body));
                    patterns = new ArrayList<>();
                }
            }
            workingCopy.rewrite(switchBlock, make.SwitchExpression(TreeShims.getExpressions(switchBlock).get(0), newCases));
        }

    };

    js.runModificationTask(task).commit();
}
 
Example 17
Source File: IntroduceHint.java    From netbeans with Apache License 2.0 4 votes vote down vote up
public static TreePath validateSelection(CompilationInfo ci, int start, int end, Set<TypeKind> ignoredTypes) {
    int[] span = TreeUtils.ignoreWhitespaces(ci, Math.min(start, end), Math.max(start, end));

    start = span[0];
    end   = span[1];
    
    TreePath tp = ci.getTreeUtilities().pathFor((start + end) / 2 + 1);

    for ( ; tp != null; tp = tp.getParentPath()) {
        Tree leaf = tp.getLeaf();

        if (   !ExpressionTree.class.isAssignableFrom(leaf.getKind().asInterface())
            && (leaf.getKind() != Kind.VARIABLE || ((VariableTree) leaf).getInitializer() == null))
           continue;

        long treeStart = ci.getTrees().getSourcePositions().getStartPosition(ci.getCompilationUnit(), leaf);
        long treeEnd   = ci.getTrees().getSourcePositions().getEndPosition(ci.getCompilationUnit(), leaf);

        if (treeStart != start || treeEnd != end) {
            continue;
        }

        TypeMirror type = ci.getTrees().getTypeMirror(tp);

        if (type != null && type.getKind() == TypeKind.ERROR) {
            type = ci.getTrees().getOriginalType((ErrorType) type);
        }

        if (type == null || ignoredTypes.contains(type.getKind()))
            continue;

        if(tp.getLeaf().getKind() == Kind.ASSIGNMENT)
            continue;

        if (tp.getLeaf().getKind() == Kind.ANNOTATION)
            continue;

        if (!TreeUtils.isInsideClass(tp))
            return null;

        TreePath candidate = tp;

        tp = tp.getParentPath();

        while (tp != null) {
            switch (tp.getLeaf().getKind()) {
                case VARIABLE:
                    VariableTree vt = (VariableTree) tp.getLeaf();
                    if (vt.getInitializer() == leaf) {
                        return candidate;
                    } else {
                        return null;
                    }
                case NEW_CLASS:
                    NewClassTree nct = (NewClassTree) tp.getLeaf();
                    
                    if (nct.getIdentifier().equals(candidate.getLeaf())) { //avoid disabling hint ie inside of anonymous class higher in treepath
                        for (Tree p : nct.getArguments()) {
                            if (p == leaf) {
                                return candidate;
                            }
                        }

                        return null;
                    }
            }

            leaf = tp.getLeaf();
            tp = tp.getParentPath();
        }

        return candidate;
    }

    return null;
}
 
Example 18
Source File: ContextAnalyzer.java    From netbeans with Apache License 2.0 4 votes vote down vote up
public static TreePath validateSelection(CompilationInfo ci, int start, int end, Set<TypeKind> ignoredTypes) {
    if(start == end) {
        TokenSequence<JavaTokenId> cts = ci.getTokenHierarchy().tokenSequence(JavaTokenId.language());

        if (cts != null) {
            cts.move(start);

            if (cts.moveNext() && cts.token().id() != JavaTokenId.WHITESPACE && cts.offset() == start) {
                start = end += 1;
            }
        }
    }
    
    TreePath tp = ci.getTreeUtilities().pathFor(start == end? start : (start + end) / 2 + 1);

    for ( ; tp != null; tp = tp.getParentPath()) {
        Tree leaf = tp.getLeaf();

        if (   !ExpressionTree.class.isAssignableFrom(leaf.getKind().asInterface())
            && (leaf.getKind() != Tree.Kind.VARIABLE || ((VariableTree) leaf).getInitializer() == null)) {
            continue;
        }

        long treeStart = ci.getTrees().getSourcePositions().getStartPosition(ci.getCompilationUnit(), leaf);
        long treeEnd   = ci.getTrees().getSourcePositions().getEndPosition(ci.getCompilationUnit(), leaf);

        if (start != end) {
            if (treeStart != start || treeEnd != end) {
                continue;
            }
        } else {
            if (treeStart != start && treeEnd != end) {
                continue;
            } 
        }

        TypeMirror type = ci.getTrees().getTypeMirror(tp);

        if (type != null && type.getKind() == TypeKind.ERROR) {
            type = ci.getTrees().getOriginalType((ErrorType) type);
        }

        if (type == null || ignoredTypes.contains(type.getKind()))
            continue;

        if(tp.getLeaf().getKind() == Tree.Kind.ASSIGNMENT)
            continue;

        if (tp.getLeaf().getKind() == Tree.Kind.ANNOTATION)
            continue;

        if (!isInsideClass(tp))
            return null;

        TreePath candidate = tp;

        tp = tp.getParentPath();

        while (tp != null) {
            switch (tp.getLeaf().getKind()) {
                case VARIABLE:
                    VariableTree vt = (VariableTree) tp.getLeaf();
                    if (vt.getInitializer() == leaf) {
                        return candidate;
                    } else {
                        return null;
                    }
                case NEW_CLASS:
                    NewClassTree nct = (NewClassTree) tp.getLeaf();
                    
                    if (nct.getIdentifier().equals(candidate.getLeaf())) { //avoid disabling hint ie inside of anonymous class higher in treepath
                        for (Tree p : nct.getArguments()) {
                            if (p == leaf) {
                                return candidate;
                            }
                        }

                        return null;
                    }
            }

            leaf = tp.getLeaf();
            tp = tp.getParentPath();
        }

        return candidate;
    }

    return null;
}
 
Example 19
Source File: JavaInputAstVisitor.java    From google-java-format with Apache License 2.0 4 votes vote down vote up
private void declareMany(List<VariableTree> fragments, Direction annotationDirection) {
  builder.open(ZERO);

  ModifiersTree modifiers = fragments.get(0).getModifiers();
  Tree type = fragments.get(0).getType();

  visitAndBreakModifiers(
      modifiers, annotationDirection, /* declarationAnnotationBreak= */ Optional.empty());
  builder.open(plusFour);
  builder.open(ZERO);
  TypeWithDims extractedDims = DimensionHelpers.extractDims(type, SortedDims.YES);
  Deque<List<? extends AnnotationTree>> dims = new ArrayDeque<>(extractedDims.dims);
  scan(extractedDims.node, null);
  int baseDims = dims.size();
  maybeAddDims(dims);
  baseDims = baseDims - dims.size();
  boolean first = true;
  for (VariableTree fragment : fragments) {
    if (!first) {
      token(",");
    }
    TypeWithDims fragmentDims = variableFragmentDims(first, baseDims, fragment.getType());
    dims = new ArrayDeque<>(fragmentDims.dims);
    builder.breakOp(" ");
    builder.open(ZERO);
    maybeAddDims(dims);
    visit(fragment.getName());
    maybeAddDims(dims);
    ExpressionTree initializer = fragment.getInitializer();
    if (initializer != null) {
      builder.space();
      token("=");
      builder.open(plusFour);
      builder.breakOp(" ");
      scan(initializer, null);
      builder.close();
    }
    builder.close();
    if (first) {
      builder.close();
    }
    first = false;
  }
  builder.close();
  token(";");
  builder.close();
}
 
Example 20
Source File: JavaInputAstVisitor.java    From javaide with GNU General Public License v3.0 4 votes vote down vote up
private void declareMany(List<VariableTree> fragments, Direction annotationDirection) {
    builder.open(ZERO);

    ModifiersTree modifiers = fragments.get(0).getModifiers();
    Tree type = fragments.get(0).getType();

    visitAndBreakModifiers(modifiers, annotationDirection, Optional.<BreakTag>absent());
    builder.open(plusFour);
    builder.open(ZERO);
    TypeWithDims extractedDims = DimensionHelpers.extractDims(type, SortedDims.YES);
    Deque<List<AnnotationTree>> dims = new ArrayDeque<>(extractedDims.dims);
    scan(extractedDims.node, null);
    int baseDims = dims.size();
    maybeAddDims(dims);
    baseDims = baseDims - dims.size();
    boolean first = true;
    for (VariableTree fragment : fragments) {
        if (!first) {
            token(",");
        }
        TypeWithDims fragmentDims = variableFragmentDims(first, baseDims, fragment.getType());
        dims = new ArrayDeque<>(fragmentDims.dims);
        builder.breakOp(" ");
        builder.open(ZERO);
        maybeAddDims(dims);
        visit(fragment.getName());
        maybeAddDims(dims);
        ExpressionTree initializer = fragment.getInitializer();
        if (initializer != null) {
            builder.space();
            token("=");
            builder.open(plusFour);
            builder.breakOp(" ");
            scan(initializer, null);
            builder.close();
        }
        builder.close();
        if (first) {
            builder.close();
        }
        first = false;
    }
    builder.close();
    token(";");
    builder.close();
}