com.sun.source.tree.ParenthesizedTree Java Examples

The following examples show how to use com.sun.source.tree.ParenthesizedTree. 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: NullAway.java    From NullAway with MIT License 6 votes vote down vote up
/**
 * strip out enclosing parentheses, type casts and Nullchk operators.
 *
 * @param expr a potentially parenthesised expression.
 * @return the same expression without parentheses.
 */
private static ExpressionTree stripParensAndCasts(ExpressionTree expr) {
  boolean someChange = true;
  while (someChange) {
    someChange = false;
    if (expr.getKind().equals(PARENTHESIZED)) {
      expr = ((ParenthesizedTree) expr).getExpression();
      someChange = true;
    }
    if (expr.getKind().equals(TYPE_CAST)) {
      expr = ((TypeCastTree) expr).getExpression();
      someChange = true;
    }

    // Strips Nullchk operator
    if (expr.getKind().equals(OTHER) && expr instanceof JCTree.JCUnary) {
      expr = ((JCTree.JCUnary) expr).getExpression();
      someChange = true;
    }
  }
  return expr;
}
 
Example #2
Source File: NullAway.java    From NullAway with MIT License 6 votes vote down vote up
@Override
public Description matchSwitch(SwitchTree tree, VisitorState state) {
  if (!matchWithinClass) {
    return Description.NO_MATCH;
  }

  ExpressionTree switchExpression = tree.getExpression();
  if (switchExpression instanceof ParenthesizedTree) {
    switchExpression = ((ParenthesizedTree) switchExpression).getExpression();
  }

  if (mayBeNullExpr(state, switchExpression)) {
    final String message =
        "switch expression " + state.getSourceForNode(switchExpression) + " is @Nullable";
    ErrorMessage errorMessage =
        new ErrorMessage(MessageTypes.SWITCH_EXPRESSION_NULLABLE, message);

    return errorBuilder.createErrorDescription(
        errorMessage, switchExpression, buildDescription(switchExpression), state);
  }

  return Description.NO_MATCH;
}
 
Example #3
Source File: Ifs.java    From netbeans with Apache License 2.0 6 votes vote down vote up
@Override
protected void performRewrite(final TransformationContext ctx) throws Exception {
    IfTree toRewrite = (IfTree) ctx.getPath().getLeaf();
    StatementTree elseStatement = toRewrite.getElseStatement();
    if (toRewrite.getCondition() == null ||
        toRewrite.getCondition().getKind() != Tree.Kind.PARENTHESIZED) {
        return;
    }
    ParenthesizedTree ptt = (ParenthesizedTree)toRewrite.getCondition();
    if (ptt.getExpression() == null) {
        return;
    }
    if (elseStatement == null) elseStatement = ctx.getWorkingCopy().getTreeMaker().Block(Collections.<StatementTree>emptyList(), false);
    
    ctx.getWorkingCopy().rewrite(toRewrite, ctx.getWorkingCopy().getTreeMaker().If(toRewrite.getCondition(), elseStatement, toRewrite.getThenStatement()));
    ExpressionTree negated = Utilities.negate(
            ctx.getWorkingCopy().getTreeMaker(), ptt.getExpression(), ptt);
    ctx.getWorkingCopy().rewrite(ptt.getExpression(), negated);
}
 
Example #4
Source File: CreateElementUtilities.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private static List<? extends TypeMirror> computeParenthesis(Set<ElementKind> types, CompilationInfo info, TreePath parent, Tree error, int offset) {
    ParenthesizedTree pt = (ParenthesizedTree) parent.getLeaf();
    
    if (pt.getExpression() != error) {
        return null;
    }
    
    TreePath parentParent = parent.getParentPath();
    List<? extends TypeMirror> upperTypes = resolveType(types, info, parentParent, pt, offset, null, null);
    
    if (upperTypes == null) {
        return null;
    }
    
    return upperTypes;
}
 
Example #5
Source File: RemoveUselessCast.java    From netbeans with Apache License 2.0 6 votes vote down vote up
@Override
protected void performRewrite(TransformationContext ctx) {
    WorkingCopy wc = ctx.getWorkingCopy();
    TreePath path = ctx.getPath();
    TypeCastTree tct = (TypeCastTree) path.getLeaf();
    ExpressionTree expression = tct.getExpression();

    while (expression.getKind() == Kind.PARENTHESIZED
           && !JavaFixUtilities.requiresParenthesis(((ParenthesizedTree) expression).getExpression(), tct, path.getParentPath().getLeaf())) {
        expression = ((ParenthesizedTree) expression).getExpression();
    }

    while (path.getParentPath().getLeaf().getKind() == Kind.PARENTHESIZED
           && !JavaFixUtilities.requiresParenthesis(expression, path.getLeaf(), path.getParentPath().getParentPath().getLeaf())) {
        path = path.getParentPath();
    }

    wc.rewrite(path.getLeaf(), expression);
}
 
Example #6
Source File: ConvertToPatternInstanceOf.java    From netbeans with Apache License 2.0 6 votes vote down vote up
@Override
        protected void performRewrite(JavaFix.TransformationContext ctx) {
            WorkingCopy wc = ctx.getWorkingCopy();
            TreePath main = ctx.getPath();
            IfTree it = (IfTree) main.getLeaf();
            InstanceOfTree iot = (InstanceOfTree) ((ParenthesizedTree) it.getCondition()).getExpression();
            StatementTree bt = it.getThenStatement();
//            wc.rewrite(iot.getType(), wc.getTreeMaker().BindingPattern(var.getName(), iot.getType()));
//            wc.rewrite(bt, wc.getTreeMaker().removeBlockStatement(bt, 0));
            InstanceOfTree cond = wc.getTreeMaker().InstanceOf(iot.getExpression(), wc.getTreeMaker().BindingPattern(varName, iot.getType()));
            StatementTree thenBlock = removeFirst ? wc.getTreeMaker().removeBlockStatement((BlockTree) bt, 0) : bt;
            wc.rewrite(it, wc.getTreeMaker().If(wc.getTreeMaker().Parenthesized(cond), thenBlock, it.getElseStatement()));
            replaceOccurrences.stream().map(tph -> tph.resolve(wc)).forEach(tp -> {
                if (!removeFirst && tp.getParentPath().getLeaf().getKind() == Kind.PARENTHESIZED) {
                    tp = tp.getParentPath();
                }
                wc.rewrite(tp.getLeaf(), wc.getTreeMaker().Identifier(varName));
            });
        }
 
Example #7
Source File: CreateElementUtilities.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private static List<? extends TypeMirror> computeParenthesis(Set<ElementKind> types, CompilationInfo info, TreePath parent, Tree error, int offset) {
    ParenthesizedTree pt = (ParenthesizedTree) parent.getLeaf();
    
    if (pt.getExpression() != error) {
        return null;
    }
    
    TreePath parentParent = parent.getParentPath();
    List<? extends TypeMirror> upperTypes = resolveType(types, info, parentParent, pt, offset, null, null);
    
    if (upperTypes == null) {
        return null;
    }
    
    return upperTypes;
}
 
Example #8
Source File: JavaInputAstVisitor.java    From java-n-IDE-for-Android with Apache License 2.0 5 votes vote down vote up
@Override
public Void visitParenthesized(ParenthesizedTree node, Void unused) {
    token("(");
    scan(node.getExpression(), null);
    token(")");
    return null;
}
 
Example #9
Source File: TreeDiffer.java    From compile-testing with Apache License 2.0 5 votes vote down vote up
@Override
public Void visitParenthesized(ParenthesizedTree expected, Tree actual) {
  Optional<ParenthesizedTree> other = checkTypeAndCast(expected, actual);
  if (!other.isPresent()) {
    addTypeMismatch(expected, actual);
    return null;
  }

  scan(expected.getExpression(), other.get().getExpression());
  return null;
}
 
Example #10
Source File: JavaInputAstVisitor.java    From google-java-format with Apache License 2.0 5 votes vote down vote up
@Override
public Void visitParenthesized(ParenthesizedTree node, Void unused) {
  token("(");
  scan(node.getExpression(), null);
  token(")");
  return null;
}
 
Example #11
Source File: JavaInputAstVisitor.java    From javaide with GNU General Public License v3.0 5 votes vote down vote up
@Override
public Void visitParenthesized(ParenthesizedTree node, Void unused) {
    token("(");
    scan(node.getExpression(), null);
    token(")");
    return null;
}
 
Example #12
Source File: JDIWrappersTest.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private Element getElement(Tree tree) {
    TreePath expPath = TreePath.getPath(cut, tree);
    Element e = trees.getElement(expPath);
    if (e == null) {
        if (tree instanceof ParenthesizedTree) {
            e = getElement(((ParenthesizedTree) tree).getExpression());
            //if (e == null) {
            //    System.err.println("Have null element for "+tree);
            //}
            //System.err.println("\nHAVE "+e.asType().toString()+" for ParenthesizedTree "+tree);
        }
        else if (tree instanceof TypeCastTree) {
            e = getElement(((TypeCastTree) tree).getType());
            //if (e == null) {
            //    System.err.println("Have null element for "+tree);
            //}
            //System.err.println("\nHAVE "+e.asType().toString()+" for TypeCastTree "+tree);
        }
        else if (tree instanceof AssignmentTree) {
            e = getElement(((AssignmentTree) tree).getVariable());
        }
        else if (tree instanceof ArrayAccessTree) {
            e = getElement(((ArrayAccessTree) tree).getExpression());
            if (e != null) {
                TypeMirror tm = e.asType();
                if (tm.getKind() == TypeKind.ARRAY) {
                    tm = ((ArrayType) tm).getComponentType();
                    e = types.asElement(tm);
                }
            }
            //System.err.println("ArrayAccessTree = "+((ArrayAccessTree) tree).getExpression()+", element = "+getElement(((ArrayAccessTree) tree).getExpression())+", type = "+getElement(((ArrayAccessTree) tree).getExpression()).asType());
        }
    }
    return e;
}
 
Example #13
Source File: LeakingThisInConstructor.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@TriggerPattern(value="$v=$this") // NOI18N
public static ErrorDescription hintOnAssignment(HintContext ctx) {
    Map<String,TreePath> variables = ctx.getVariables ();
    TreePath thisPath = variables.get ("$this"); // NOI18N
    if (   thisPath.getLeaf().getKind() != Kind.IDENTIFIER
        || !((IdentifierTree) thisPath.getLeaf()).getName().contentEquals(THIS_KEYWORD)) {
        return null;
    }
    if (!Utilities.isInConstructor(ctx)) {
        return null;
    }
    TreePath storePath = variables.get("$v");
    Tree t = storePath.getLeaf();
    if (t.getKind() == Tree.Kind.MEMBER_SELECT) {
        t = ((MemberSelectTree)t).getExpression();
        while (t != null && t.getKind() == Tree.Kind.PARENTHESIZED) {
            t = ((ParenthesizedTree)t).getExpression();
        }
        if (t == null) {
            return null;
        } else if (t.getKind() == Tree.Kind.IDENTIFIER) {
            IdentifierTree it = (IdentifierTree)t;
            if (it.getName().contentEquals(THIS_KEYWORD) ||
                it.getName().contentEquals(SUPER_KEYWORD)) {
                return null;
            }
        }
    } else {
        return null;
    }
    return ErrorDescriptionFactory.forName(ctx, ctx.getPath(),
            NbBundle.getMessage(
                LeakingThisInConstructor.class,
                "MSG_org.netbeans.modules.java.hints.LeakingThisInConstructor"));
}
 
Example #14
Source File: TreeNode.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@Override
public Void visitParenthesized(ParenthesizedTree tree, List<Node> d) {
    List<Node> below = new ArrayList<Node>();
    
    addCorrespondingType(below);
    addCorrespondingComments(below);
    super.visitParenthesized(tree, below);
    
    d.add(new TreeNode(info, getCurrentPath(), below));
    return null;
}
 
Example #15
Source File: TreeDuplicator.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@Override
public Tree visitParenthesized(ParenthesizedTree tree, Void p) {
    ParenthesizedTree n = make.Parenthesized(tree.getExpression());
    model.setType(n, model.getType(tree));
    comments.copyComments(tree, n);
    model.setPos(n, model.getPos(tree));
    return n;
}
 
Example #16
Source File: CopyFinder.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public Boolean visitParenthesized(ParenthesizedTree node, TreePath p) {
    if (p == null)
        return super.visitParenthesized(node, p);

    ParenthesizedTree t = (ParenthesizedTree) p.getLeaf();

    return scan(node.getExpression(), t.getExpression(), p);
}
 
Example #17
Source File: ExpressionVisitor.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@Override
public Object visitParenthesized(ParenthesizedTree node, Object p) {
    boolean b = isCorrectType(node);
    currentMatches = b;
    Object o = super.visitParenthesized(node, p);
    increment(node, b);
    return o;
}
 
Example #18
Source File: InstanceOfTest.java    From netbeans with Apache License 2.0 4 votes vote down vote up
public void testAddVariableName() throws Exception {
    if (!typeTestPatternAvailable())
        return ;

    testFile = new File(getWorkDir(), "Test.java");
    TestUtilities.copyStringToFile(testFile, 
        "package hierbas.del.litoral;\n\n" +
        "public class Test {\n" +
        "    public void taragui(Object o) {\n" +
        "        if (o instanceof String) {\n" + 
        "        }\n" + 
        "    }\n" +
        "}\n"
        );
    String golden =
        "package hierbas.del.litoral;\n\n" +
        "public class Test {\n" +
        "    public void taragui(Object o) {\n" +
        "        if (o instanceof String t) {\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);
            IfTree ift = (IfTree) method.getBody().getStatements().get(0);
            InstanceOfTree it = (InstanceOfTree) ((ParenthesizedTree) ift.getCondition()).getExpression();
            InstanceOfTree nue = make.InstanceOf(it.getExpression(), make.BindingPattern("t", it.getType()));
            workingCopy.rewrite(it, nue);
        }

    };
    src.runModificationTask(task).commit();
    String res = TestUtilities.copyFileToString(testFile);
    System.err.println(res);
    assertEquals(golden, res);
}
 
Example #19
Source File: Trees.java    From java-n-IDE-for-Android with Apache License 2.0 4 votes vote down vote up
/**
 * Skips a single parenthesized tree.
 */
static ExpressionTree skipParen(ExpressionTree node) {
    return ((ParenthesizedTree) node).getExpression();
}
 
Example #20
Source File: TreePruner.java    From bazel with Apache License 2.0 4 votes vote down vote up
@Override
public Boolean visitParenthesized(ParenthesizedTree node, Void p) {
  return node.getExpression().accept(this, null);
}
 
Example #21
Source File: ModelBuilder.java    From vertx-codetrans with Apache License 2.0 4 votes vote down vote up
@Override
public CodeModel visitParenthesized(ParenthesizedTree node, VisitContext context) {
  ExpressionModel expression = scan(node.getExpression(), context);
  return new ParenthesizedModel(context.builder, expression);
}
 
Example #22
Source File: UParens.java    From Refaster with Apache License 2.0 4 votes vote down vote up
@Override
public Tree visitParenthesized(ParenthesizedTree node, Void v) {
  return node.getExpression().accept(this, null);
}
 
Example #23
Source File: RefasterScanner.java    From Refaster with Apache License 2.0 4 votes vote down vote up
@Override
public Tree visitParenthesized(ParenthesizedTree node, Void v) {
  return node.getExpression().accept(this, null);
}
 
Example #24
Source File: UTemplater.java    From Refaster with Apache License 2.0 4 votes vote down vote up
@Override
public UParens visitParenthesized(ParenthesizedTree tree, Void v) {
  return UParens.create(template(tree.getExpression()));
}
 
Example #25
Source File: TreeConverter.java    From j2objc with Apache License 2.0 4 votes vote down vote up
private TreeNode convertParens(ParenthesizedTree node, TreePath parent) {
  return new ParenthesizedExpression()
      .setExpression((Expression) convert(node.getExpression(), getTreePath(parent, node)));
}
 
Example #26
Source File: XPFlagCleaner.java    From piranha with Apache License 2.0 4 votes vote down vote up
private Value evalExpr(ExpressionTree tree, VisitorState state) {
  if (tree == null) {
    return Value.BOT;
  }

  Kind k = tree.getKind();

  if (k.equals(Kind.PARENTHESIZED)) {
    ParenthesizedTree pt = (ParenthesizedTree) tree;
    Value v = evalExpr(pt.getExpression(), state);
    return v;
  }

  if (k.equals(Kind.BOOLEAN_LITERAL)) {
    LiteralTree lt = (LiteralTree) tree;
    if (lt.getValue().equals(Boolean.TRUE)) {
      return Value.TRUE;
    }
    if (lt.getValue().equals(Boolean.FALSE)) {
      return Value.FALSE;
    }
  }

  if (k.equals(Kind.LOGICAL_COMPLEMENT)) {
    UnaryTree ut = (UnaryTree) tree;
    Value e = evalExpr(ut.getExpression(), state);
    if (e.equals(Value.FALSE)) {
      return Value.TRUE;
    }
    if (e.equals(Value.TRUE)) {
      return Value.FALSE;
    }
  }

  if (k.equals(Kind.METHOD_INVOCATION)) {
    API api = getXPAPI(tree);
    if (api.equals(API.IS_TREATED)) {
      return isTreated ? Value.TRUE : Value.FALSE;
    } else if (api.equals(API.IS_CONTROL)) {
      return isTreated ? Value.FALSE : Value.TRUE;
    } else if (api.equals(API.IS_TREATMENT_GROUP_CHECK)) {
      return evalTreatmentGroupCheck((MethodInvocationTree) tree) ? Value.TRUE : Value.FALSE;
    }
  }

  if (k.equals(Kind.CONDITIONAL_AND) || k.equals(Kind.CONDITIONAL_OR)) {
    BinaryTree bt = (BinaryTree) tree;

    Value l = evalExpr(bt.getLeftOperand(), state);
    Value r = evalExpr(bt.getRightOperand(), state);

    if (k.equals(Kind.CONDITIONAL_OR)) {
      if (l.equals(Value.TRUE) || r.equals(Value.TRUE)) {
        return Value.TRUE;
      }

      if (l.equals(Value.FALSE) && r.equals(Value.FALSE)) {
        return Value.FALSE;
      }

    } else if (k.equals(Kind.CONDITIONAL_AND)) {
      if (l.equals(Value.TRUE) && r.equals(Value.TRUE)) {
        return Value.TRUE;
      }

      if (l.equals(Value.FALSE) || r.equals(Value.FALSE)) {
        return Value.FALSE;
      }
    }
  }

  return Value.BOT;
}
 
Example #27
Source File: Trees.java    From google-java-format with Apache License 2.0 4 votes vote down vote up
/** Skips a single parenthesized tree. */
static ExpressionTree skipParen(ExpressionTree node) {
  return ((ParenthesizedTree) node).getExpression();
}
 
Example #28
Source File: Trees.java    From javaide with GNU General Public License v3.0 4 votes vote down vote up
/**
 * Skips a single parenthesized tree.
 */
static ExpressionTree skipParen(ExpressionTree node) {
    return ((ParenthesizedTree) node).getExpression();
}
 
Example #29
Source File: InstanceOfTest.java    From netbeans with Apache License 2.0 4 votes vote down vote up
public void testRemoveVariableName() throws Exception {
    if (!typeTestPatternAvailable())
        return ;

    testFile = new File(getWorkDir(), "Test.java");
    TestUtilities.copyStringToFile(testFile, 
        "package hierbas.del.litoral;\n\n" +
        "public class Test {\n" +
        "    public void taragui(Object o) {\n" +
        "        if (o instanceof String t) {\n" + 
        "        }\n" + 
        "    }\n" +
        "}\n"
        );
    String golden =
        "package hierbas.del.litoral;\n\n" +
        "public class Test {\n" +
        "    public void taragui(Object o) {\n" +
        "        if (o instanceof String) {\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);
            IfTree ift = (IfTree) method.getBody().getStatements().get(0);
            InstanceOfTree it = (InstanceOfTree) ((ParenthesizedTree) ift.getCondition()).getExpression();
            InstanceOfTree nue = make.InstanceOf(it.getExpression(), it.getType());
            workingCopy.rewrite(it, nue);
        }

    };
    src.runModificationTask(task).commit();
    String res = TestUtilities.copyFileToString(testFile);
    System.err.println(res);
    assertEquals(golden, res);
}
 
Example #30
Source File: Tiny.java    From netbeans with Apache License 2.0 4 votes vote down vote up
@Override
protected void performRewrite(final TransformationContext ctx) {
    WorkingCopy wc = ctx.getWorkingCopy();
    final TreeMaker make = wc.getTreeMaker();
    final TreePath tp = ctx.getPath();
    SwitchTree st = (SwitchTree) tp.getLeaf();
    int insertIndex = 0;
    boolean hadDefault = false;

    for (CaseTree ct : st.getCases()) {
        if (ct.getExpression() == null) {
            hadDefault = true;
            break;
        }
        insertIndex++;
    }

    for (String name : names) {
        st = make.insertSwitchCase(st, insertIndex++, make.Case(make.Identifier(name), Collections.singletonList(make.Break(null))));
    }

    if (!hadDefault && defaultTemplate != null) {
        StatementTree stmt = ctx.getWorkingCopy().getTreeUtilities().parseStatement(defaultTemplate, new SourcePositions[1]);
        Scope s = ctx.getWorkingCopy().getTrees().getScope(tp);
        ctx.getWorkingCopy().getTreeUtilities().attributeTree(stmt, s);
        st = GeneratorUtilities.get(ctx.getWorkingCopy()).importFQNs(make.addSwitchCase(st, make.Case(null, Collections.singletonList(stmt))));
        new ErrorAwareTreePathScanner<Void, Void>() {
            @Override public Void visitIdentifier(IdentifierTree node, Void p) {
                if (node.getName().contentEquals("$expression")) {
                    ExpressionTree expression = ((SwitchTree) tp.getLeaf()).getExpression();
                    if (expression.getKind() == Tree.Kind.PARENTHESIZED) {
                        expression = ((ParenthesizedTree) expression).getExpression();
                    }
                    if (JavaFixUtilities.requiresParenthesis(expression, node, getCurrentPath().getParentPath().getLeaf())) {
                        expression = make.Parenthesized(expression);
                    }
                    ctx.getWorkingCopy().rewrite(node, expression);
                }
                return super.visitIdentifier(node, p);
            }
        }.scan(new TreePath(ctx.getPath(), st), null);
    }

    wc.rewrite(tp.getLeaf(), st);
}