com.sun.source.tree.ConditionalExpressionTree Java Examples

The following examples show how to use com.sun.source.tree.ConditionalExpressionTree. 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: JavaInputAstVisitor.java    From java-n-IDE-for-Android with Apache License 2.0 6 votes vote down vote up
@Override
public Void visitConditionalExpression(ConditionalExpressionTree node, Void unused) {
    sync(node);
    builder.open(plusFour);
    scan(node.getCondition(), null);
    builder.breakOp(" ");
    token("?");
    builder.space();
    scan(node.getTrueExpression(), null);
    builder.breakOp(" ");
    token(":");
    builder.space();
    scan(node.getFalseExpression(), null);
    builder.close();
    return null;
}
 
Example #2
Source File: CopyFinder.java    From netbeans with Apache License 2.0 6 votes vote down vote up
public Boolean visitConditionalExpression(ConditionalExpressionTree node, TreePath p) {
    if (p == null) {
        super.visitConditionalExpression(node, p);
        return false;
    }

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

    if (!scan(node.getCondition(), t.getCondition(), p))
        return false;

    if (!scan(node.getFalseExpression(), t.getFalseExpression(), p))
        return false;

    return scan(node.getTrueExpression(), t.getTrueExpression(), p);
}
 
Example #3
Source File: CreateElementUtilities.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private static List<? extends TypeMirror> computeConditionalExpression(Set<ElementKind> types, CompilationInfo info, TreePath parent, Tree error, int offset) {
    ConditionalExpressionTree cet = (ConditionalExpressionTree) parent.getLeaf();
    
    if (cet.getCondition() == error) {
        types.add(ElementKind.PARAMETER);
        types.add(ElementKind.LOCAL_VARIABLE);
        types.add(ElementKind.FIELD);
        
        return Collections.singletonList(info.getTypes().getPrimitiveType(TypeKind.BOOLEAN));
    }
    
    if (cet.getTrueExpression() == error || cet.getFalseExpression() == error) {
        types.add(ElementKind.PARAMETER);
        types.add(ElementKind.LOCAL_VARIABLE);
        types.add(ElementKind.FIELD);
        
        return resolveType(types, info, parent.getParentPath(), cet, offset, null, null);
    }
    
    return null;
}
 
Example #4
Source File: AddCastFix.java    From netbeans with Apache License 2.0 6 votes vote down vote up
@Override
protected void performRewrite(TransformationContext ctx) throws Exception {
    TypeMirror resolvedTargetType = targetType.resolve(ctx.getWorkingCopy());
    
    if (resolvedTargetType == null) {
        //cannot resolve anymore:
        return;
    }
    
    TreePath resolvedIdealTypeTree = idealTypeTree != null ? idealTypeTree.resolve(ctx.getWorkingCopy()) : null;
    
    TreeMaker make = ctx.getWorkingCopy().getTreeMaker();
    ExpressionTree toCast = (ExpressionTree) ctx.getPath().getLeaf();

    Class interf = toCast.getKind().asInterface();
    boolean wrapWithBrackets = interf == BinaryTree.class || interf == ConditionalExpressionTree.class;

    if (/*TODO: replace with JavaFixUtilities.requiresparenthesis*/wrapWithBrackets) {
        toCast = make.Parenthesized(toCast);
    }

    ExpressionTree cast = make.TypeCast(resolvedIdealTypeTree != null ? resolvedIdealTypeTree.getLeaf() : make.Type(resolvedTargetType), toCast);

    ctx.getWorkingCopy().rewrite(ctx.getPath().getLeaf(), cast);
}
 
Example #5
Source File: CreateElementUtilities.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private static List<? extends TypeMirror> computeConditionalExpression(Set<ElementKind> types, CompilationInfo info, TreePath parent, Tree error, int offset) {
    ConditionalExpressionTree cet = (ConditionalExpressionTree) parent.getLeaf();
    
    if (cet.getCondition() == error) {
        types.add(ElementKind.PARAMETER);
        types.add(ElementKind.LOCAL_VARIABLE);
        types.add(ElementKind.FIELD);
        
        return Collections.singletonList(info.getTypes().getPrimitiveType(TypeKind.BOOLEAN));
    }
    
    if (cet.getTrueExpression() == error || cet.getFalseExpression() == error) {
        types.add(ElementKind.PARAMETER);
        types.add(ElementKind.LOCAL_VARIABLE);
        types.add(ElementKind.FIELD);
        
        return resolveType(types, info, parent.getParentPath(), cet, offset, null, null);
    }
    
    return null;
}
 
Example #6
Source File: JavaInputAstVisitor.java    From javaide with GNU General Public License v3.0 6 votes vote down vote up
@Override
public Void visitConditionalExpression(ConditionalExpressionTree node, Void unused) {
    sync(node);
    builder.open(plusFour);
    scan(node.getCondition(), null);
    builder.breakOp(" ");
    token("?");
    builder.space();
    scan(node.getTrueExpression(), null);
    builder.breakOp(" ");
    token(":");
    builder.space();
    scan(node.getFalseExpression(), null);
    builder.close();
    return null;
}
 
Example #7
Source File: ArithmeticUtilities.java    From netbeans with Apache License 2.0 6 votes vote down vote up
@Override
public Object visitConditionalExpression(ConditionalExpressionTree node, Void p) {
    Object condition = scan(node.getCondition(), p);
    if (condition == Boolean.TRUE) {
        return scan(node.getTrueExpression(), p);
    } else if (condition == Boolean.FALSE) {
        return scan(node.getFalseExpression(), p);
    }
    if (enhanceProcessing) {
        Object first = scan(node.getTrueExpression(), p);
        Object second = scan(node.getFalseExpression(), p);
        if (first == NULL && second == NULL) {
            return NULL;
        } else if (first != null && second != null) {
            return NOT_NULL;
        }
    }
    // indeterminate
    return null;
}
 
Example #8
Source File: JavaInputAstVisitor.java    From google-java-format with Apache License 2.0 6 votes vote down vote up
@Override
public Void visitConditionalExpression(ConditionalExpressionTree node, Void unused) {
  sync(node);
  builder.open(plusFour);
  scan(node.getCondition(), null);
  builder.breakOp(" ");
  token("?");
  builder.space();
  scan(node.getTrueExpression(), null);
  builder.breakOp(" ");
  token(":");
  builder.space();
  scan(node.getFalseExpression(), null);
  builder.close();
  return null;
}
 
Example #9
Source File: ExpressionScanner.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@Override
public List<Tree> visitConditionalExpression(ConditionalExpressionTree node, ExpressionScanner.ExpressionsInfo p) {
    ExpressionTree condition = node.getCondition();
    List<Tree> cond = scan(condition, p);
    Tree lastCond = null;
    Boolean resolvedCondition = null;
    if (cond != null) {
        lastCond = cond.get(cond.size() - 1);
    } else {
        if (condition.getKind() == Tree.Kind.BOOLEAN_LITERAL) {
            resolvedCondition = Boolean.parseBoolean(condition.toString());
        }
    }
    List<Tree> rT;
    List<Tree> rF;
    if (resolvedCondition != null) {
        if (resolvedCondition) {
            rT = scan(node.getTrueExpression(), p);
            rF = null;
        } else {
            rT = null;
            rF = scan(node.getFalseExpression(), p);
        }
    } else {
        rT = scan(node.getTrueExpression(), p);
        rF = scan(node.getFalseExpression(), p);
    }
    if (lastCond != null) {
        if (rT != null) {
            p.addNextExpression(lastCond, rT.get(0));
        }
        if (rF != null) {
            p.addNextExpression(lastCond, rF.get(0));
        }
    }
    return reduce(reduce(cond, rT), rF);
}
 
Example #10
Source File: TreeDiffer.java    From compile-testing with Apache License 2.0 5 votes vote down vote up
@Override
public Void visitConditionalExpression(ConditionalExpressionTree expected, Tree actual) {
  Optional<ConditionalExpressionTree> other = checkTypeAndCast(expected, actual);
  if (!other.isPresent()) {
    addTypeMismatch(expected, actual);
    return null;
  }

  scan(expected.getCondition(), other.get().getCondition());
  scan(expected.getTrueExpression(), other.get().getTrueExpression());
  scan(expected.getFalseExpression(), other.get().getFalseExpression());
  return null;
}
 
Example #11
Source File: NullAway.java    From NullAway with MIT License 5 votes vote down vote up
@Override
public Description matchConditionalExpression(
    ConditionalExpressionTree tree, VisitorState state) {
  if (!matchWithinClass) {
    return Description.NO_MATCH;
  }
  return doUnboxingCheck(state, tree.getCondition());
}
 
Example #12
Source File: ExpressionToTypeInfo.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
private Type pathToType(TreePath tp, Tree tree) {
    if (tree instanceof ConditionalExpressionTree) {
        // Conditionals always wind up as Object -- this corrects
        ConditionalExpressionTree cet = (ConditionalExpressionTree) tree;
        Type tmt = pathToType(new TreePath(tp, cet.getTrueExpression()));
        Type tmf = pathToType(new TreePath(tp, cet.getFalseExpression()));
        if (!tmt.isPrimitive() && !tmf.isPrimitive()) {
            Type lub = types.lub(tmt, tmf);
            // System.err.printf("cond ? %s : %s  --  lub = %s\n",
            //             varTypeName(tmt), varTypeName(tmf), varTypeName(lub));
            return lub;
        }
    }
    return pathToType(tp);
}
 
Example #13
Source File: TreeConverter.java    From j2objc with Apache License 2.0 5 votes vote down vote up
private TreeNode convertConditionalExpression(ConditionalExpressionTree node, TreePath parent) {
  TreePath path = getTreePath(parent, node);
  return new ConditionalExpression()
      .setTypeMirror(getTypeMirror(path))
      .setExpression((Expression) convert(node.getCondition(), path))
      .setThenExpression((Expression) convert(node.getTrueExpression(), path))
      .setElseExpression((Expression) convert(node.getFalseExpression(), path));
}
 
Example #14
Source File: UTemplater.java    From Refaster with Apache License 2.0 5 votes vote down vote up
@Override
public UExpression visitConditionalExpression(ConditionalExpressionTree tree, Void v) {
  UConditional result = UConditional.create(template(tree.getCondition()),
      template(tree.getTrueExpression()), template(tree.getFalseExpression()));
  if (context.get(AlsoReverseTernary.class) != null) {
    return UAnyOf.create(result, result.reverse());
  } else {
    return result;
  }
}
 
Example #15
Source File: UConditional.java    From Refaster with Apache License 2.0 5 votes vote down vote up
@Override
@Nullable
public Unifier visitConditionalExpression(
    ConditionalExpressionTree conditional, Unifier unifier) {
  unifier = getCondition().unify(conditional.getCondition(), unifier);
  unifier = getTrueExpression().unify(conditional.getTrueExpression(), unifier);
  return getFalseExpression().unify(conditional.getFalseExpression(), unifier);
}
 
Example #16
Source File: ModelBuilder.java    From vertx-codetrans with Apache License 2.0 5 votes vote down vote up
@Override
public CodeModel visitConditionalExpression(ConditionalExpressionTree node, VisitContext context) {
  ExpressionModel condition = scan(node.getCondition(), context);
  ExpressionModel trueExpression = scan(node.getTrueExpression(), context);
  ExpressionModel falseExpression = scan(node.getFalseExpression(), context);
  return context.builder.forConditionalExpression(condition, trueExpression, falseExpression);
}
 
Example #17
Source File: TreePruner.java    From bazel with Apache License 2.0 5 votes vote down vote up
@Override
public Boolean visitConditionalExpression(ConditionalExpressionTree node, Void p) {
  return reduce(
      node.getCondition().accept(this, null),
      node.getTrueExpression().accept(this, null),
      node.getFalseExpression().accept(this, null));
}
 
Example #18
Source File: Flow.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@Override
public Boolean visitConditionalExpression(ConditionalExpressionTree node, ConstructorData p) {
    Boolean result = scan(node.getCondition(), p);

    if (result != null) {
        if (result) {
            scan(node.getTrueExpression(), null);
        } else {
            scan(node.getFalseExpression(), null);
        }

        return null;
    }

    Map<Element, State> oldVariable2State = variable2State;

    variable2State = new HashMap<Element, Flow.State>(oldVariable2State);

    scan(node.getTrueExpression(), null);

    if (node.getFalseExpression() != null) {
        Map<Element, State> variableStatesAfterThen = new HashMap<Element, Flow.State>(variable2State);

        variable2State = new HashMap<Element, Flow.State>(oldVariable2State);

        scan(node.getFalseExpression(), null);

        variable2State = mergeOr(variable2State, variableStatesAfterThen);
    } else {
        variable2State = mergeOr(variable2State, oldVariable2State);
    }

    return null;
}
 
Example #19
Source File: ReplaceBufferByString.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private ExpressionTree makeParenthesis(ExpressionTree arg) {
    Class c =  arg.getKind().asInterface();
    // if the original append argument was an expression, surround it in parenthesis, to get the same toString effect
    if (c == BinaryTree.class || c == UnaryTree.class || c == CompoundAssignmentTree.class || c == AssignmentTree.class ||
        c == ConditionalExpressionTree.class) {
        return mk.Parenthesized(arg);
    } else {
        return arg;
    }
}
 
Example #20
Source File: TreeNode.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@Override
public Void visitConditionalExpression(ConditionalExpressionTree tree, List<Node> d) {
    List<Node> below = new ArrayList<Node>();
    
    addCorrespondingType(below);
    addCorrespondingComments(below);
    super.visitConditionalExpression(tree, below);
    
    d.add(new TreeNode(info, getCurrentPath(), below));
    return null;
}
 
Example #21
Source File: DepthVisitor.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@Override
public Object visitConditionalExpression(ConditionalExpressionTree node, Object p) {
    depth++;
    Object o = super.visitConditionalExpression(node, p); 
    depth--;
    return o;
}
 
Example #22
Source File: TreeDuplicator.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@Override
public Tree visitConditionalExpression(ConditionalExpressionTree tree, Void p) {
    ConditionalExpressionTree n = make.ConditionalExpression(tree.getCondition(), tree.getTrueExpression(), tree.getFalseExpression());
    model.setType(n, model.getType(tree));
    comments.copyComments(tree, n);
    model.setPos(n, model.getPos(tree));
    return n;
}
 
Example #23
Source File: XPFlagCleaner.java    From piranha with Apache License 2.0 5 votes vote down vote up
@Override
public Description matchConditionalExpression(
    ConditionalExpressionTree tree, VisitorState state) {
  if (overLaps(tree, state)) {
    return Description.NO_MATCH;
  }
  ExpressionTree et = tree.getCondition();
  Value x = evalExpr(et, state);
  String replacementString = EMPTY;

  boolean update = false;
  ExpressionTree removedBranch = null;
  if (x.equals(Value.TRUE)) {
    update = true;
    replacementString = state.getSourceForNode(tree.getTrueExpression());
    removedBranch = tree.getFalseExpression();
  } else if (x.equals(Value.FALSE)) {
    update = true;
    replacementString = state.getSourceForNode(tree.getFalseExpression());
    removedBranch = tree.getTrueExpression();
  }

  if (update) {
    Preconditions.checkNotNull(removedBranch, "update => removedBranch != null here.");
    Description.Builder builder = buildDescription(tree);
    SuggestedFix.Builder fixBuilder = SuggestedFix.builder();
    fixBuilder.replace(tree, stripBraces(replacementString));
    decrementAllSymbolUsages(et, state, fixBuilder);
    decrementAllSymbolUsages(removedBranch, state, fixBuilder);
    builder.addFix(fixBuilder.build());
    endPos = state.getEndPosition(tree);
    return builder.build();
  }
  return Description.NO_MATCH;
}
 
Example #24
Source File: ExpectedTypeResolver.java    From netbeans with Apache License 2.0 4 votes vote down vote up
/**
 * Handles subexpression in conditional expr. If the expression is the condition, the expected
 * type is boolean. Otherwise the parent expression is evaluated for expected types. It is expected
 * that the 'expression' will be eventually casted to the desired type, while the other branch' 
 * expression should remain as it is. Types, that theExpression cannot be casted to, or the other
 * branch' expression can't be assigned to (must be casted as well) are rejected.
 * 
 * @param node the conditional node
 * @param p dummy
 * @return list of possible types for the expression
 */
@Override
public List<? extends TypeMirror> visitConditionalExpression(ConditionalExpressionTree node, Object p) {
    if (theExpression == null) {
        // cannot determine
        return null;
    }
    if (theExpression.getLeaf() == node.getCondition()) {
        return booleanType();
    }
    Tree otherExpression;
    if (theExpression.getLeaf() == node.getFalseExpression()) {
        otherExpression = node.getTrueExpression();
    } else {
        otherExpression = node.getFalseExpression();
    }
    TypeMirror otherType = info.getTrees().getTypeMirror(new TreePath(getCurrentPath(), otherExpression));
    TypeMirror thisType = info.getTrees().getTypeMirror(getExpressionWithoutCasts());
    if (!(Utilities.isValidType(otherType) && Utilities.isValidType(thisType))) {
        return null;
    }

    ExpectedTypeResolver subResolver = new ExpectedTypeResolver(getCurrentPath(), getCurrentPath(), info);
    subResolver.typeCastDepth++;
    List<? extends TypeMirror> pp = subResolver.scan(getCurrentPath().getParentPath(), null);
    
    if (pp == null) {
        return null;
    }
    List<? extends TypeMirror> parentTypes = new ArrayList<TypeMirror>(pp);

    for (Iterator<? extends TypeMirror> it = parentTypes.iterator(); it.hasNext(); ) {
        TypeMirror m = it.next();
        if (!info.getTypeUtilities().isCastable(thisType, m)) {
            Scope s = info.getTrees().getScope(getCurrentPath());
            SourcePositions pos = info.getTrees().getSourcePositions();
            StringBuilder sb = new StringBuilder();
            int posFirst = (int)pos.getStartPosition(info.getCompilationUnit(), theExpression.getLeaf());
            int posSecond = (int)pos.getStartPosition(info.getCompilationUnit(), otherExpression);
            
            if (posFirst < 0 || posSecond < 0) {
                // LOMBOK
                return null;
            }
            String first = info.getText().substring(posFirst, 
                    (int)pos.getEndPosition(info.getCompilationUnit(), theExpression.getLeaf()));
            String second = info.getText().substring(posSecond, 
                    (int)pos.getEndPosition(info.getCompilationUnit(), otherExpression));
            sb.append(first).append("+").append(second);
            ExpressionTree expr = info.getTreeUtilities().parseExpression(sb.toString(), new SourcePositions[1]);
            TypeMirror targetType = purify(info, info.getTreeUtilities().attributeTree(expr, s));
            if (targetType == null || !info.getTypes().isAssignable(targetType, m)) {
                it.remove();
            }
        }
    }
    return parentTypes.isEmpty() ? Collections.singletonList(otherType) : parentTypes;
}
 
Example #25
Source File: JPDAMethodChooserUtils.java    From netbeans with Apache License 2.0 4 votes vote down vote up
private static void detectUnreachableOps(String url, final EditorContext.Operation[] operations,
                                         final int[] flags, final EditorContext.Operation currOp) {
    FileObject fileObj = null;
    try {
        fileObj = URLMapper.findFileObject(new URL(url));
    } catch (MalformedURLException e) {
    }
    if (fileObj == null) return;
    JavaSource js = JavaSource.forFileObject(fileObj);
    if (js == null) return;

    try {
        js.runUserActionTask(new CancellableTask<CompilationController>() {
            @Override
            public void cancel() {
            }
            @Override
            public void run(CompilationController ci) throws Exception {
                if (ci.toPhase(JavaSource.Phase.RESOLVED).compareTo(JavaSource.Phase.RESOLVED) < 0) {
                    Logger.getLogger(JPDAMethodChooserUtils.class.getName()).warning(
                            "Unable to resolve "+ci.getFileObject()+" to phase "+JavaSource.Phase.RESOLVED+", current phase = "+ci.getPhase()+
                            "\nDiagnostics = "+ci.getDiagnostics()+
                            "\nFree memory = "+Runtime.getRuntime().freeMemory());
                    return;
                }
                SourcePositions positions = ci.getTrees().getSourcePositions();
                CompilationUnitTree compUnit = ci.getCompilationUnit();
                TreeUtilities treeUtils = ci.getTreeUtilities();
                int pcOffset = currOp == null ? 0 : currOp.getMethodStartPosition().getOffset() + 1;
                for (int i = 0; i < operations.length; i++) {
                    int offset = operations[i].getMethodStartPosition().getOffset() + 1;
                    TreePath path = treeUtils.pathFor(offset);
                    while (path != null) {
                        Tree tree = path.getLeaf();
                        if (tree instanceof ConditionalExpressionTree) {
                            ConditionalExpressionTree ternaryOpTree = (ConditionalExpressionTree)tree;
                            //Tree condTree = ternaryOpTree.getCondition();
                            Tree trueTree = ternaryOpTree.getTrueExpression();
                            Tree falseTree = ternaryOpTree.getFalseExpression();
                            //long condStart = positions.getStartPosition(compUnit, condTree);
                            //long condEnd = positions.getEndPosition(compUnit, condTree);
                            long trueStart = positions.getStartPosition(compUnit, trueTree);
                            long trueEnd = positions.getEndPosition(compUnit, trueTree);
                            long falseStart = positions.getStartPosition(compUnit, falseTree);
                            long falseEnd = positions.getEndPosition(compUnit, falseTree);

                            if (trueStart <= offset && offset <= trueEnd) {
                                if (pcOffset < trueStart) {
                                    markSegment(i, false);
                                }
                            } else if (falseStart <= offset && offset <= falseEnd) {
                                if (pcOffset < trueStart) {
                                    markSegment(i, false);
                                } else if (trueStart <= pcOffset && pcOffset <= trueEnd) {
                                    markSegment(i, true);
                                }
                            }
                        } else if (tree.getKind() == Tree.Kind.CONDITIONAL_AND ||
                                tree.getKind() == Tree.Kind.CONDITIONAL_OR) {
                            BinaryTree binaryTree = (BinaryTree)tree;
                            Tree rightTree = binaryTree.getRightOperand();
                            long rightStart = positions.getStartPosition(compUnit, rightTree);
                            long rightEnd = positions.getEndPosition(compUnit, rightTree);

                            if (rightStart <= offset && offset <= rightEnd) {
                                if (pcOffset < rightStart) {
                                    markSegment(i, false);
                                }
                            }
                        }
                        path = path.getParentPath();
                    } // while
                } // for
            }

            public void markSegment(int index, boolean excludeSegment) {
                if (flags[index] == 2) return;
                flags[index] = excludeSegment ? 2 : 1;
            }

        }, true);
    } catch (IOException ioex) {
        Exceptions.printStackTrace(ioex);
    }
}
 
Example #26
Source File: InfiniteRecursion.java    From netbeans with Apache License 2.0 4 votes vote down vote up
@Override
public State visitConditionalExpression(ConditionalExpressionTree node, Void p) {
    return visitConditional(node.getCondition(), node.getTrueExpression(), node.getFalseExpression(), p);
}
 
Example #27
Source File: UnnecessaryBoxing.java    From netbeans with Apache License 2.0 4 votes vote down vote up
/**
 * Checks whether the other branch of the conditional has a matching type. If the prev expression
 * is the conditional's expression, it's OK.
 * 
 * @param ci context
 * @param expr the conditional expression
 * @param prev the parameter containing the boxing
 * @return true, if it is OK to leave out the boxing
 */
private static boolean checkConditional(CompilationInfo ci, TreePath expr, Tree prev) {
    ConditionalExpressionTree ct = (ConditionalExpressionTree)expr.getLeaf();
    if (ct.getCondition() == prev) {
        return true;
    }
    TreePath prevPath = new TreePath(expr, prev);
    TypeMirror boxedPrev = ci.getTrees().getTypeMirror(prevPath);
    TypeMirror pt = Utilities.unboxIfNecessary(ci, boxedPrev); // assume boxed
    if (!Utilities.isValidType(pt)) {
        return false;
    }
    ExpectedTypeResolver res = new ExpectedTypeResolver(expr, prevPath, ci);
    List<? extends TypeMirror> types = res.scan(expr, null);
    if (types == null) {
        // cannot determine the type -> no hint, probably an error
        return false;
    }
    for (TypeMirror m : types) {
        if (!m.getKind().isPrimitive() && !Utilities.isPrimitiveWrapperType(m)) {
            return false;
        }
        m = Utilities.unboxIfNecessary(ci, m);
        if (ci.getTypes().isAssignable(pt, m)) {
            // special case, see issue #269269; if the OTHER argument of the conditional
            // is a primitive wrapper AND it is _not_ known to contain non-null, do not produce unboxing warning
            // as both boxed types prevent cond.op. to unbox.
            TreePath other = new TreePath(expr, 
                    prev == ct.getTrueExpression() ? ct.getFalseExpression() : ct.getTrueExpression());
            TypeMirror m2 = ci.getTrees().getTypeMirror(other);
            if (!Utilities.isValidType(m2)) {
                continue;
            }
            if (NPECheck.isSafeToDereference(ci, other)) {
                return true;
            }
            if (!Utilities.isPrimitiveWrapperType(m2) ||
                    ci.getTypes().isSameType(boxedPrev, m2)) {
                return true;
            }
        }
    }
    return false;
}
 
Example #28
Source File: RemoveUnnecessary.java    From netbeans with Apache License 2.0 4 votes vote down vote up
/**
 * Conditional expression can be turned into an if-statement
 */
@Override
public Object visitConditionalExpression(ConditionalExpressionTree node, Object p) {
    List<StatementTree> saveStat = this.statements;
    boolean saveRemove = this.remove;
    statements = new ArrayList<>();
    
    scan(node.getTrueExpression(), p);
    
    List<StatementTree> trueStat = statements;
    statements = new ArrayList<>();
    
    scan(node.getFalseExpression(), p);
    List<StatementTree> falseStat = statements;
    
    this.statements = saveStat;
    this.remove = saveRemove && remove;
    
    if (trueStat.isEmpty()) {
        if (falseStat.isEmpty()) {
            return null;
        }
        statements.add(mk.If(
                mk.Unary(Tree.Kind.LOGICAL_COMPLEMENT, node.getCondition()),
                falseStat.size() == 1 ? 
                        falseStat.get(0) :
                        mk.Block(falseStat, false),
                null
        ));
    } else {
        statements.add(mk.If(node.getCondition(),
                trueStat.size() == 1 ? 
                        trueStat.get(0) :
                        mk.Block(trueStat, false),
                falseStat.isEmpty() ? null :
                    falseStat.size() == 1 ? 
                            falseStat.get(0) :
                            mk.Block(falseStat, false)
                        
        ));
    }
    return null;
}
 
Example #29
Source File: CyclomaticComplexityVisitor.java    From netbeans with Apache License 2.0 4 votes vote down vote up
@Override
public Object visitConditionalExpression(ConditionalExpressionTree node, Object p) {
    complexity++;
    return super.visitConditionalExpression(node, p);
}