Java 类com.sun.tools.javac.tree.JCTree.JCBinary 实例源码

项目:incubator-netbeans    文件:CasualDiff.java   
protected int diffBinary(JCBinary oldT, JCBinary newT, int[] bounds) {
    int localPointer = bounds[0];

    int[] lhsBounds = getBounds(oldT.lhs);
    copyTo(localPointer, lhsBounds[0]);
    localPointer = diffTree(oldT.lhs, newT.lhs, lhsBounds);
    if (oldT.getTag() != newT.getTag()) {
        copyTo(localPointer, oldT.pos);
        printer.print(operatorName(newT.getTag()));
        localPointer = oldT.pos + operatorName(oldT.getTag()).toString().length();
    }
    int[] rhsBounds = getCommentCorrectedBounds(oldT.rhs);
    rhsBounds[0] = copyUpTo(localPointer, rhsBounds[0]);
    localPointer = diffTree(oldT.rhs, newT.rhs, rhsBounds);
    return copyUpTo(localPointer, bounds[1]);
}
项目:openjdk-jdk10    文件:TwrAvoidNullCheck.java   
@Override
public List<JCTree> translateTopLevelClass(Env<AttrContext> env, JCTree cdef, TreeMaker make) {
    List<JCTree> result = super.translateTopLevelClass(env, cdef, make);

    new TreeScanner() {
        @Override
        public void visitBinary(JCBinary tree) {
            hasNullCheck |= tree.operator.getSimpleName().contentEquals("!=") &&
                            "resource".equals(String.valueOf(TreeInfo.name(tree.lhs))) &&
                            TreeInfo.isNull(tree.rhs);
            super.visitBinary(tree);
        }
    }.scan(result);

    return result;
}
项目:openjdk9    文件:TwrAvoidNullCheck.java   
@Override
public List<JCTree> translateTopLevelClass(Env<AttrContext> env, JCTree cdef, TreeMaker make) {
    List<JCTree> result = super.translateTopLevelClass(env, cdef, make);

    new TreeScanner() {
        @Override
        public void visitBinary(JCBinary tree) {
            hasNullCheck |= tree.operator.getSimpleName().contentEquals("!=") &&
                            "resource".equals(String.valueOf(TreeInfo.name(tree.lhs))) &&
                            TreeInfo.isNull(tree.rhs);
            super.visitBinary(tree);
        }
    }.scan(result);

    return result;
}
项目:jmlok    文件:Examinator.java   
/**
 * This function walks into a tree with nodes of type JCBinary to search for 
 * a string as one of the elements of the tree.
 * @param toTest The String searched as Element in the tree.
 * @param expression The bifurcation tree searched.
 * @return True if the string was found, or False.
 */
private boolean isThereInMiniTree(String toTest, JCTree expression) {
    if(expression instanceof JCParens){
        if(isThereInMiniTree(toTest, ((JCParens) expression).expr))
            return true;
    } else if(expression instanceof JCIdent){
        if(((JCIdent) expression).name.toString().equals(toTest))
            return true;
    } else if(expression instanceof JCBinary){
        if(isThereInMiniTree(toTest, ((JCBinary) expression).rhs))
            return true;
        if(isThereInMiniTree(toTest, ((JCBinary) expression).lhs))
            return true;
    }
    return false;
}
项目:jmlok    文件:Examinator.java   
/**
 * Verify if the boolean expression have a true value despite of any variable values. 
 * @param expression The boolean expression examined.
 * @return 1 When the expression is always true.
 */
private int hasTrueValue(JCTree expression) {
    if(expression instanceof JCParens){
        if(hasTrueValue(((JCParens)expression).expr) != 0)
            return 1;
    }else if(expression instanceof JCLiteral){
        if(((JCLiteral) expression).value == null)
            return VAR_FALSE_VALUE;
        return (int) ((JCLiteral) expression).value;
    }else if(expression instanceof JmlSingleton){
        return 1;
    }else if(expression instanceof JCBinary){
        return resolveBooleanOperations(expression);
    }
    return VAR_FALSE_VALUE;
}
项目:error-prone    文件:OperatorPrecedence.java   
@Override
public Description matchBinary(BinaryTree tree, VisitorState state) {
  Tree parent = state.getPath().getParentPath().getLeaf();
  if (!(parent instanceof BinaryTree)) {
    return NO_MATCH;
  }
  if (TreeInfo.opPrec(((JCBinary) tree).getTag())
      == TreeInfo.opPrec(((JCBinary) parent).getTag())) {
    return NO_MATCH;
  }
  if (!isConfusing(tree.getKind(), parent.getKind())) {
    return NO_MATCH;
  }
  return describeMatch(
      tree, SuggestedFix.builder().prefixWith(tree, "(").postfixWith(tree, ")").build());
}
项目:lombok-ianchiu    文件:PrettyPrinter.java   
@Override public void visitBinary(JCBinary tree) {
    String op = operator(treeTag(tree));
    print(tree.lhs);
    print(" ");
    print(op);
    print(" ");
    print(tree.rhs);
}
项目:lombok-ianchiu    文件:HandleEqualsAndHashCode.java   
public JCStatement generateCompareFloatOrDouble(JCExpression thisDotField, JCExpression otherDotField,
    JavacTreeMaker maker, JavacNode node, boolean isDouble) {

    /* if (Float.compare(fieldName, other.fieldName) != 0) return false; */
    JCExpression clazz = genJavaLangTypeRef(node, isDouble ? "Double" : "Float");
    List<JCExpression> args = List.of(thisDotField, otherDotField);
    JCBinary compareCallEquals0 = maker.Binary(CTC_NOT_EQUAL, maker.Apply(
        List.<JCExpression>nil(), maker.Select(clazz, node.toName("compare")), args), maker.Literal(0));
    return maker.If(compareCallEquals0, returnBool(maker, false), null);
}
项目:lombok-ianchiu    文件:HandleNonNull.java   
/**
 * Checks if the statement is of the form 'if (x == null) {throw WHATEVER;},
 * where the block braces are optional. If it is of this form, returns "x".
 * If it is not of this form, returns null.
 */
public String returnVarNameIfNullCheck(JCStatement stat) {
    if (!(stat instanceof JCIf)) return null;

    /* Check that the if's statement is a throw statement, possibly in a block. */ {
        JCStatement then = ((JCIf) stat).thenpart;
        if (then instanceof JCBlock) {
            List<JCStatement> stats = ((JCBlock) then).stats;
            if (stats.length() == 0) return null;
            then = stats.get(0);
        }
        if (!(then instanceof JCThrow)) return null;
    }

    /* Check that the if's conditional is like 'x == null'. Return from this method (don't generate
       a nullcheck) if 'x' is equal to our own variable's name: There's already a nullcheck here. */ {
        JCExpression cond = ((JCIf) stat).cond;
        while (cond instanceof JCParens) cond = ((JCParens) cond).expr;
        if (!(cond instanceof JCBinary)) return null;
        JCBinary bin = (JCBinary) cond;
        if (!CTC_EQUAL.equals(treeTag(bin))) return null;
        if (!(bin.lhs instanceof JCIdent)) return null;
        if (!(bin.rhs instanceof JCLiteral)) return null;
        if (!CTC_BOT.equals(typeTag(bin.rhs))) return null;
        return ((JCIdent) bin.lhs).name.toString();
    }
}
项目:javaparser2jctree    文件:PrintAstVisitor.java   
public void visitBinary(JCBinary that) {
    try {
        print("JCBinary:");
    } catch (Exception e) {
    }
    super.visitBinary(that);
}
项目:EasyMPermission    文件:PrettyCommentsPrinter.java   
public void visitBinary(JCBinary tree) {
    try {
        int ownprec = isOwnPrec(tree);
        String opname = operatorName(treeTag(tree));
        open(prec, ownprec);
        printExpr(tree.lhs, ownprec);
        print(" " + opname + " ");
        printExpr(tree.rhs, ownprec + 1);
        close(prec, ownprec);
    } catch (IOException e) {
        throw new UncheckedIOException(e);
    }
}
项目:EasyMPermission    文件:HandleEqualsAndHashCode.java   
public JCStatement generateCompareFloatOrDouble(JCExpression thisDotField, JCExpression otherDotField,
        JavacTreeMaker maker, JavacNode node, boolean isDouble) {
    /* if (Float.compare(fieldName, other.fieldName) != 0) return false; */
    JCExpression clazz = genJavaLangTypeRef(node, isDouble ? "Double" : "Float");
    List<JCExpression> args = List.of(thisDotField, otherDotField);
    JCBinary compareCallEquals0 = maker.Binary(CTC_NOT_EQUAL, maker.Apply(
            List.<JCExpression>nil(), maker.Select(clazz, node.toName("compare")), args), maker.Literal(0));
    return maker.If(compareCallEquals0, returnBool(maker, false), null);
}
项目:EasyMPermission    文件:HandleNonNull.java   
/**
 * Checks if the statement is of the form 'if (x == null) {throw WHATEVER;},
 * where the block braces are optional. If it is of this form, returns "x".
 * If it is not of this form, returns null.
 */
public String returnVarNameIfNullCheck(JCStatement stat) {
    if (!(stat instanceof JCIf)) return null;

    /* Check that the if's statement is a throw statement, possibly in a block. */ {
        JCStatement then = ((JCIf) stat).thenpart;
        if (then instanceof JCBlock) {
            List<JCStatement> stats = ((JCBlock) then).stats;
            if (stats.length() == 0) return null;
            then = stats.get(0);
        }
        if (!(then instanceof JCThrow)) return null;
    }

    /* Check that the if's conditional is like 'x == null'. Return from this method (don't generate
       a nullcheck) if 'x' is equal to our own variable's name: There's already a nullcheck here. */ {
        JCExpression cond = ((JCIf) stat).cond;
        while (cond instanceof JCParens) cond = ((JCParens) cond).expr;
        if (!(cond instanceof JCBinary)) return null;
        JCBinary bin = (JCBinary) cond;
        if (!CTC_EQUAL.equals(treeTag(bin))) return null;
        if (!(bin.lhs instanceof JCIdent)) return null;
        if (!(bin.rhs instanceof JCLiteral)) return null;
        if (!CTC_BOT.equals(typeTag(bin.rhs))) return null;
        return ((JCIdent) bin.lhs).name.toString();
    }
}
项目:refactor-faster    文件:UBinary.java   
@Override
public JCBinary inline(Inliner inliner) throws CouldNotResolveImportException {
  return inliner.maker().Binary(
      OP_CODES.get(getKind()), 
      getLeftOperand().inline(inliner),
      getRightOperand().inline(inliner));
}
项目:android-retrolambda-lombok    文件:JcTreePrinter.java   
@Override public void visitBinary(JCBinary tree) {
    printNode(tree);
    child("lhs", tree.lhs);
    property("(operator)", operatorName(getTag(tree)));
    child("rhs", tree.rhs);
    indent--;
}
项目:android-retrolambda-lombok    文件:JcTreeConverter.java   
@Override public void visitBinary(JCBinary node) {
    BinaryExpression expr = new BinaryExpression();
    expr.rawLeft(toTree(node.getLeftOperand()));
    expr.rawRight(toTree(node.getRightOperand()));
    expr.astOperator(JcTreeBuilder.BINARY_OPERATORS.inverse().get(getTag(node)));
    set(node, expr);
}
项目:error-prone    文件:UBinary.java   
@Override
public JCBinary inline(Inliner inliner) throws CouldNotResolveImportException {
  return inliner
      .maker()
      .Binary(
          OP_CODES.get(getKind()),
          getLeftOperand().inline(inliner),
          getRightOperand().inline(inliner));
}
项目:error-prone    文件:PlaceholderUnificationVisitor.java   
@Override
public Choice<State<JCBinary>> visitBinary(final BinaryTree node, State<?> state) {
  final Tag tag = ((JCBinary) node).getTag();
  return chooseSubtrees(
      state,
      s -> unifyExpression(node.getLeftOperand(), s),
      s -> unifyExpression(node.getRightOperand(), s),
      (l, r) -> maker().Binary(tag, l, r));
}
项目:error-prone    文件:NarrowingCompoundAssignment.java   
/** Desugars a compound assignment, making the cast explicit. */
private static Optional<Fix> rewriteCompoundAssignment(
    CompoundAssignmentTree tree, VisitorState state) {
  CharSequence var = state.getSourceForNode(tree.getVariable());
  CharSequence expr = state.getSourceForNode(tree.getExpression());
  if (var == null || expr == null) {
    return Optional.absent();
  }
  switch (tree.getKind()) {
    case RIGHT_SHIFT_ASSIGNMENT:
      // narrowing the result of a signed right shift does not lose information
      return Optional.absent();
    default:
      break;
  }
  Kind regularAssignmentKind = regularAssignmentFromCompound(tree.getKind());
  String op = assignmentToString(regularAssignmentKind);

  // Add parens to the rhs if necessary to preserve the current precedence
  // e.g. 's -= 1 - 2' -> 's = s - (1 - 2)'
  if (tree.getExpression() instanceof JCBinary) {
    Kind rhsKind = tree.getExpression().getKind();
    if (!OperatorPrecedence.from(rhsKind)
        .isHigher(OperatorPrecedence.from(regularAssignmentKind))) {
      expr = String.format("(%s)", expr);
    }
  }

  // e.g. 's *= 42' -> 's = (short) (s * 42)'
  String castType = getType(tree.getVariable()).toString();
  String replacement = String.format("%s = (%s) (%s %s %s)", var, castType, var, op, expr);
  return Optional.of(SuggestedFix.replace(tree, replacement));
}
项目:s4j    文件:Pretty.java   
public void visitBinary(JCBinary tree) {
    try {
        int ownprec = TreeInfo.opPrec(tree.getTag());
        String opname = operatorName(tree.getTag());
        open(prec, ownprec);
        printExpr(tree.lhs, ownprec);
        print(" " + opname + " ");
        printExpr(tree.rhs, ownprec + 1);
        close(prec, ownprec);
    } catch (IOException e) {
        throw new UncheckedIOException(e);
    }
}
项目:Refaster    文件:UBinary.java   
@Override
public JCBinary inline(Inliner inliner) throws CouldNotResolveImportException {
  return inliner.maker().Binary(
      OP_CODES.get(getKind()), 
      getLeftOperand().inline(inliner),
      getRightOperand().inline(inliner));
}
项目:lombok    文件:PrettyCommentsPrinter.java   
public void visitBinary(JCBinary tree) {
    try {
        int ownprec = TreeInfo.opPrec(getTag(tree));
        String opname = operatorName(getTag(tree));
        open(prec, ownprec);
        printExpr(tree.lhs, ownprec);
        print(" " + opname + " ");
        printExpr(tree.rhs, ownprec + 1);
        close(prec, ownprec);
    } catch (IOException e) {
        throw new UncheckedIOException(e);
    }
}
项目:lombok    文件:HandleEqualsAndHashCode.java   
private JCStatement generateCompareFloatOrDouble(JCExpression thisDotField, JCExpression otherDotField,
        TreeMaker maker, JavacNode node, boolean isDouble) {
    /* if (Float.compare(fieldName, other.fieldName) != 0) return false; */
    JCExpression clazz = chainDots(node, "java", "lang", isDouble ? "Double" : "Float");
    List<JCExpression> args = List.of(thisDotField, otherDotField);
    JCBinary compareCallEquals0 = maker.Binary(CTC_NOT_EQUAL, maker.Apply(
            List.<JCExpression>nil(), maker.Select(clazz, node.toName("compare")), args), maker.Literal(0));
    return maker.If(compareCallEquals0, returnBool(maker, false), null);
}
项目:incubator-netbeans    文件:CasualDiff.java   
private boolean matchBinary(JCBinary t1, JCBinary t2) {
    return t1.operator == t2.operator &&
           treesMatch(t1.lhs, t2.lhs) && treesMatch(t1.rhs, t2.rhs);
}
项目:lombok-ianchiu    文件:JavacTreeMaker.java   
public JCBinary Binary(TreeTag opcode, JCExpression lhs, JCExpression rhs) {
    return invoke(Binary, opcode.value, lhs, rhs);
}
项目:javaparser2jctree    文件:AJCBinary.java   
public AJCBinary(JCBinary ltree) {
    super(ltree.getTag(), ltree.lhs, ltree.rhs, ltree.operator);
}
项目:javaparser2jctree    文件:AJCBinary.java   
public AJCBinary(JCBinary ltree, String lcomment) {
    this(ltree);
    setComment(lcomment);
}
项目:EasyMPermission    文件:JavacTreeMaker.java   
public JCBinary Binary(TreeTag opcode, JCExpression lhs, JCExpression rhs) {
    return invoke(Binary, opcode.value, lhs, rhs);
}
项目:refactor-faster    文件:ExpressionTemplate.java   
/**
 * Returns the precedence level appropriate for unambiguously printing
 * leaf as a subexpression of its parent.
 */
private static int getPrecedence(JCTree leaf, Context context) {
  JCCompilationUnit comp = context.get(JCCompilationUnit.class);
  JCTree parent = TreeInfo.pathFor(leaf, comp).get(1);

  // In general, this should match the logic in com.sun.tools.javac.tree.Pretty.
  //
  // TODO(mdempsky): There are probably cases where we could omit parentheses
  // by tweaking the returned precedence, but they need careful review.
  // For example, consider a template to replace "add(a, b)" with "a + b",
  // which applied to "x + add(y, z)" would result in "x + (y + z)".
  // In most cases, we'd likely prefer "x + y + z" instead, but those aren't
  // always equivalent: "0L + (Integer.MIN_VALUE + Integer.MIN_VALUE)" yields
  // a different value than "0L + Integer.MIN_VALUE + Integer.MIN_VALUE" due
  // to integer promotion rules.

  if (parent instanceof JCConditional) {
    // This intentionally differs from Pretty, because Pretty appears buggy:
    // http://mail.openjdk.java.net/pipermail/compiler-dev/2013-September/007303.html
    JCConditional conditional = (JCConditional) parent;
    return TreeInfo.condPrec + ((conditional.cond == leaf) ? 1 : 0);
  } else if (parent instanceof JCAssign) {
    JCAssign assign = (JCAssign) parent;
    return TreeInfo.assignPrec + ((assign.lhs == leaf) ? 1 : 0);
  } else if (parent instanceof JCAssignOp) {
    JCAssignOp assignOp = (JCAssignOp) parent;
    return TreeInfo.assignopPrec + ((assignOp.lhs == leaf) ? 1 : 0);
  } else if (parent instanceof JCUnary) {
    return TreeInfo.opPrec(parent.getTag());
  } else if (parent instanceof JCBinary) {
    JCBinary binary = (JCBinary) parent;
    return TreeInfo.opPrec(parent.getTag()) + ((binary.rhs == leaf) ? 1 : 0);
  } else if (parent instanceof JCTypeCast) {
    JCTypeCast typeCast = (JCTypeCast) parent;
    return (typeCast.expr == leaf) ? TreeInfo.prefixPrec : TreeInfo.noPrec;
  } else if (parent instanceof JCInstanceOf) {
    JCInstanceOf instanceOf = (JCInstanceOf) parent;
    return TreeInfo.ordPrec + ((instanceOf.clazz == leaf) ? 1 : 0);
  } else if (parent instanceof JCArrayAccess) {
    JCArrayAccess arrayAccess = (JCArrayAccess) parent;
    return (arrayAccess.indexed == leaf) ? TreeInfo.postfixPrec : TreeInfo.noPrec;
  } else if (parent instanceof JCFieldAccess) {
    JCFieldAccess fieldAccess = (JCFieldAccess) parent;
    return (fieldAccess.selected == leaf) ? TreeInfo.postfixPrec : TreeInfo.noPrec;
  } else {
    return TreeInfo.noPrec;
  }
}
项目:jmlok    文件:Examinator.java   
/**
 * Calculate the value from binary expression, always considering variables with false value.
 * @param expression The binary boolean expression examined.
 * @return 1 When the expression has value true. 
 */
private int resolveBooleanOperations(JCTree expression) {
    int rexp = hasTrueValue(((JCBinary) expression).rhs);
    int lexp = hasTrueValue(((JCBinary) expression).lhs);
    switch (((JCBinary) expression).getTag()) {
        case JCTree.OR:
            if((rexp != 0)&&(rexp != VAR_FALSE_VALUE) || (lexp != 0)&&(lexp != VAR_FALSE_VALUE))
                return 1;
            return 0;
        case JCTree.AND:
            if((rexp == 0)||(rexp == VAR_FALSE_VALUE) || (lexp == 0)||(lexp == VAR_FALSE_VALUE))
                return 0;
            return 1;
        case JCTree.EQ:
            if(rexp == VAR_FALSE_VALUE || lexp == VAR_FALSE_VALUE)
                return VAR_FALSE_VALUE;
            return ((rexp != 0) == (lexp != 0)) ? 1 : 0;
        case JCTree.NE:
            if(rexp == VAR_FALSE_VALUE || lexp == VAR_FALSE_VALUE)
                return VAR_FALSE_VALUE;
            return ((rexp != 0) != (lexp != 0)) ? 1 : 0;
        case JCTree.LT:
            if(rexp == VAR_FALSE_VALUE || lexp == VAR_FALSE_VALUE)
                return VAR_FALSE_VALUE;
            return (rexp < lexp) ? 1 : 0;
        case JCTree.GT:
            if(rexp == VAR_FALSE_VALUE || lexp == VAR_FALSE_VALUE)
                return VAR_FALSE_VALUE;
            return (rexp > lexp) ? 1 : 0;
        case JCTree.LE:
            if(rexp == VAR_FALSE_VALUE || lexp == VAR_FALSE_VALUE)
                return VAR_FALSE_VALUE;
            return (rexp <= lexp) ? 1 : 0;
        case JCTree.GE:
            if(rexp == VAR_FALSE_VALUE || lexp == VAR_FALSE_VALUE)
                return VAR_FALSE_VALUE;
            return (rexp >= lexp) ? 1 : 0;
        default:
            return 0;
    }
}
项目:error-prone    文件:ExpressionTemplate.java   
/**
 * Returns the precedence level appropriate for unambiguously printing leaf as a subexpression of
 * its parent.
 */
private static int getPrecedence(JCTree leaf, Context context) {
  JCCompilationUnit comp = context.get(JCCompilationUnit.class);
  JCTree parent = TreeInfo.pathFor(leaf, comp).get(1);

  // In general, this should match the logic in com.sun.tools.javac.tree.Pretty.
  //
  // TODO(mdempsky): There are probably cases where we could omit parentheses
  // by tweaking the returned precedence, but they need careful review.
  // For example, consider a template to replace "add(a, b)" with "a + b",
  // which applied to "x + add(y, z)" would result in "x + (y + z)".
  // In most cases, we'd likely prefer "x + y + z" instead, but those aren't
  // always equivalent: "0L + (Integer.MIN_VALUE + Integer.MIN_VALUE)" yields
  // a different value than "0L + Integer.MIN_VALUE + Integer.MIN_VALUE" due
  // to integer promotion rules.

  if (parent instanceof JCConditional) {
    // This intentionally differs from Pretty, because Pretty appears buggy:
    // http://mail.openjdk.java.net/pipermail/compiler-dev/2013-September/007303.html
    JCConditional conditional = (JCConditional) parent;
    return TreeInfo.condPrec + ((conditional.cond == leaf) ? 1 : 0);
  } else if (parent instanceof JCAssign) {
    JCAssign assign = (JCAssign) parent;
    return TreeInfo.assignPrec + ((assign.lhs == leaf) ? 1 : 0);
  } else if (parent instanceof JCAssignOp) {
    JCAssignOp assignOp = (JCAssignOp) parent;
    return TreeInfo.assignopPrec + ((assignOp.lhs == leaf) ? 1 : 0);
  } else if (parent instanceof JCUnary) {
    return TreeInfo.opPrec(parent.getTag());
  } else if (parent instanceof JCBinary) {
    JCBinary binary = (JCBinary) parent;
    return TreeInfo.opPrec(parent.getTag()) + ((binary.rhs == leaf) ? 1 : 0);
  } else if (parent instanceof JCTypeCast) {
    JCTypeCast typeCast = (JCTypeCast) parent;
    return (typeCast.expr == leaf) ? TreeInfo.prefixPrec : TreeInfo.noPrec;
  } else if (parent instanceof JCInstanceOf) {
    JCInstanceOf instanceOf = (JCInstanceOf) parent;
    return TreeInfo.ordPrec + ((instanceOf.clazz == leaf) ? 1 : 0);
  } else if (parent instanceof JCArrayAccess) {
    JCArrayAccess arrayAccess = (JCArrayAccess) parent;
    return (arrayAccess.indexed == leaf) ? TreeInfo.postfixPrec : TreeInfo.noPrec;
  } else if (parent instanceof JCFieldAccess) {
    JCFieldAccess fieldAccess = (JCFieldAccess) parent;
    return (fieldAccess.selected == leaf) ? TreeInfo.postfixPrec : TreeInfo.noPrec;
  } else {
    return TreeInfo.noPrec;
  }
}
项目:s4j    文件:Attr.java   
public void visitBinary(JCBinary tree) {
    // Attribute arguments.
    // de.so.ma
    SqlQueryNodeTransformer transformer = SqlQueryNodeTransformer.getInstance();
    tree.lhs = transformer.transformPotentialSqlQuery(
            tree.lhs, env, Type.noType, this, enter, memberEnter);
    tree.rhs = transformer.transformPotentialSqlQuery(
            tree.rhs, env, Type.noType, this, enter, memberEnter);

    Type left = chk.checkNonVoid(tree.lhs.pos(), attribExpr(tree.lhs, env));
    Type right = chk.checkNonVoid(tree.lhs.pos(), attribExpr(tree.rhs, env));

    // Find operator.
    Symbol operator = tree.operator =
        rs.resolveBinaryOperator(tree.pos(), tree.getTag(), env, left, right);

    Type owntype = types.createErrorType(tree.type);
    if (operator.kind == MTH &&
            !left.isErroneous() &&
            !right.isErroneous()) {
        owntype = operator.type.getReturnType();
        int opc = chk.checkOperator(tree.lhs.pos(),
                                    (OperatorSymbol)operator,
                                    tree.getTag(),
                                    left,
                                    right);

        // If both arguments are constants, fold them.
        if (left.constValue() != null && right.constValue() != null) {
            Type ctype = cfolder.fold2(opc, left, right);
            if (ctype != null) {
                owntype = cfolder.coerce(ctype, owntype);

                // Remove constant types from arguments to
                // conserve space. The parser will fold concatenations
                // of string literals; the code here also
                // gets rid of intermediate results when some of the
                // operands are constant identifiers.
                if (tree.lhs.type.tsym == syms.stringType.tsym) {
                    tree.lhs.type = syms.stringType;
                }
                if (tree.rhs.type.tsym == syms.stringType.tsym) {
                    tree.rhs.type = syms.stringType;
                }
            }
        }

        // Check that argument types of a reference ==, != are
        // castable to each other, (JLS???).
        if ((opc == ByteCodes.if_acmpeq || opc == ByteCodes.if_acmpne)) {
            if (!types.isCastable(left, right, new Warner(tree.pos()))) {
                log.error(tree.pos(), "incomparable.types", left, right);
            }
        }

        chk.checkDivZero(tree.rhs.pos(), operator, right);
    }
    result = check(tree, owntype, VAL, pkind, pt);
}
项目:s4j    文件:Attr.java   
@Override
public void visitBinary(JCBinary that) {
    if (that.operator == null)
        that.operator = new OperatorSymbol(names.empty, syms.unknownType, -1, syms.noSymbol);
    super.visitBinary(that);
}
项目:error-prone-aspirator    文件:ElementsCountedInLoop.java   
/**
 * @return identifier which is being incremented by constant one. Returns null if no such
 *         identifier is found.
 */
private IdentifierTree getIncrementedIdentifer(JCStatement statement) {
  if (statement == null) {
    return null;
  }
  if (statement.getKind() == Kind.EXPRESSION_STATEMENT) {
    Tree.Kind kind = ((JCExpressionStatement) statement).getExpression().getKind();
    if (kind == Kind.PREFIX_INCREMENT || kind == Kind.POSTFIX_INCREMENT) {
      JCUnary unary = (JCUnary) ((JCExpressionStatement) statement).getExpression();
      if (unary.arg.getKind() == Kind.IDENTIFIER) {
        return (IdentifierTree) unary.arg;
      }
      return null;
    } else if (kind == Kind.PLUS_ASSIGNMENT) {
      JCAssignOp assignOp = (JCAssignOp) ((JCExpressionStatement) statement).getExpression();
      if (assignOp.lhs.getKind() == Kind.IDENTIFIER && (isConstantOne(assignOp.rhs))) {
        return (IdentifierTree) assignOp.lhs;
      }
    } else if (kind == Kind.ASSIGNMENT) {
      JCAssign assign = (JCAssign) ((JCExpressionStatement) statement).getExpression();
      if (assign.lhs.getKind() == Kind.IDENTIFIER && assign.rhs.getKind() == Kind.PLUS) {
        JCBinary binary = (JCBinary) assign.rhs;
        if (binary.lhs.getKind() == Kind.IDENTIFIER) {
          if (((JCIdent) assign.lhs).sym == ((JCIdent) binary.lhs).sym) {
            if (isConstantOne(binary.rhs)) {
              return (IdentifierTree) binary.lhs;
            }
          }
        }
        if (binary.rhs.getKind() == Kind.IDENTIFIER) {
          if (((JCIdent) assign.lhs).sym == ((JCIdent) binary.rhs).sym) {
            if (isConstantOne(binary.lhs)) {
              return (IdentifierTree) binary.rhs;
            }
          }
        }
      }
    }
  }
  return null;
}
项目:Refaster    文件:ExpressionTemplate.java   
/**
 * Returns the precedence level appropriate for unambiguously printing
 * leaf as a subexpression of its parent.
 */
private static int getPrecedence(JCTree leaf, Context context) {
  JCCompilationUnit comp = context.get(JCCompilationUnit.class);
  JCTree parent = TreeInfo.pathFor(leaf, comp).get(1);

  // In general, this should match the logic in com.sun.tools.javac.tree.Pretty.
  //
  // TODO(mdempsky): There are probably cases where we could omit parentheses
  // by tweaking the returned precedence, but they need careful review.
  // For example, consider a template to replace "add(a, b)" with "a + b",
  // which applied to "x + add(y, z)" would result in "x + (y + z)".
  // In most cases, we'd likely prefer "x + y + z" instead, but those aren't
  // always equivalent: "0L + (Integer.MIN_VALUE + Integer.MIN_VALUE)" yields
  // a different value than "0L + Integer.MIN_VALUE + Integer.MIN_VALUE" due
  // to integer promotion rules.

  if (parent instanceof JCConditional) {
    // This intentionally differs from Pretty, because Pretty appears buggy:
    // http://mail.openjdk.java.net/pipermail/compiler-dev/2013-September/007303.html
    JCConditional conditional = (JCConditional) parent;
    return TreeInfo.condPrec + ((conditional.cond == leaf) ? 1 : 0);
  } else if (parent instanceof JCAssign) {
    JCAssign assign = (JCAssign) parent;
    return TreeInfo.assignPrec + ((assign.lhs == leaf) ? 1 : 0);
  } else if (parent instanceof JCAssignOp) {
    JCAssignOp assignOp = (JCAssignOp) parent;
    return TreeInfo.assignopPrec + ((assignOp.lhs == leaf) ? 1 : 0);
  } else if (parent instanceof JCUnary) {
    return TreeInfo.opPrec(parent.getTag());
  } else if (parent instanceof JCBinary) {
    JCBinary binary = (JCBinary) parent;
    return TreeInfo.opPrec(parent.getTag()) + ((binary.rhs == leaf) ? 1 : 0);
  } else if (parent instanceof JCTypeCast) {
    JCTypeCast typeCast = (JCTypeCast) parent;
    return (typeCast.expr == leaf) ? TreeInfo.prefixPrec : TreeInfo.noPrec;
  } else if (parent instanceof JCInstanceOf) {
    JCInstanceOf instanceOf = (JCInstanceOf) parent;
    return TreeInfo.ordPrec + ((instanceOf.clazz == leaf) ? 1 : 0);
  } else if (parent instanceof JCArrayAccess) {
    JCArrayAccess arrayAccess = (JCArrayAccess) parent;
    return (arrayAccess.indexed == leaf) ? TreeInfo.postfixPrec : TreeInfo.noPrec;
  } else if (parent instanceof JCFieldAccess) {
    JCFieldAccess fieldAccess = (JCFieldAccess) parent;
    return (fieldAccess.selected == leaf) ? TreeInfo.postfixPrec : TreeInfo.noPrec;
  } else {
    return TreeInfo.noPrec;
  }
}
项目:lombok    文件:HandleCleanup.java   
@Override public void handle(AnnotationValues<Cleanup> annotation, JCAnnotation ast, JavacNode annotationNode) {
    if (inNetbeansEditor(annotationNode)) return;

    deleteAnnotationIfNeccessary(annotationNode, Cleanup.class);
    String cleanupName = annotation.getInstance().value();
    if (cleanupName.length() == 0) {
        annotationNode.addError("cleanupName cannot be the empty string.");
        return;
    }

    if (annotationNode.up().getKind() != Kind.LOCAL) {
        annotationNode.addError("@Cleanup is legal only on local variable declarations.");
        return;
    }

    JCVariableDecl decl = (JCVariableDecl)annotationNode.up().get();

    if (decl.init == null) {
        annotationNode.addError("@Cleanup variable declarations need to be initialized.");
        return;
    }

    JavacNode ancestor = annotationNode.up().directUp();
    JCTree blockNode = ancestor.get();

    final List<JCStatement> statements;
    if (blockNode instanceof JCBlock) {
        statements = ((JCBlock)blockNode).stats;
    } else if (blockNode instanceof JCCase) {
        statements = ((JCCase)blockNode).stats;
    } else if (blockNode instanceof JCMethodDecl) {
        statements = ((JCMethodDecl)blockNode).body.stats;
    } else {
        annotationNode.addError("@Cleanup is legal only on a local variable declaration inside a block.");
        return;
    }

    boolean seenDeclaration = false;
    ListBuffer<JCStatement> newStatements = ListBuffer.lb();
    ListBuffer<JCStatement> tryBlock = ListBuffer.lb();
    for (JCStatement statement : statements) {
        if (!seenDeclaration) {
            if (statement == decl) seenDeclaration = true;
            newStatements.append(statement);
        } else {
            tryBlock.append(statement);
        }
    }

    if (!seenDeclaration) {
        annotationNode.addError("LOMBOK BUG: Can't find this local variable declaration inside its parent.");
        return;
    }
    doAssignmentCheck(annotationNode, tryBlock.toList(), decl.name);

    TreeMaker maker = annotationNode.getTreeMaker();
    JCFieldAccess cleanupMethod = maker.Select(maker.Ident(decl.name), annotationNode.toName(cleanupName));
    List<JCStatement> cleanupCall = List.<JCStatement>of(maker.Exec(
            maker.Apply(List.<JCExpression>nil(), cleanupMethod, List.<JCExpression>nil())));

    JCMethodInvocation preventNullAnalysis = preventNullAnalysis(maker, annotationNode, maker.Ident(decl.name));
    JCBinary isNull = maker.Binary(CTC_NOT_EQUAL, preventNullAnalysis, maker.Literal(CTC_BOT, null));

    JCIf ifNotNullCleanup = maker.If(isNull, maker.Block(0, cleanupCall), null);

    JCBlock finalizer = recursiveSetGeneratedBy(maker.Block(0, List.<JCStatement>of(ifNotNullCleanup)), ast);

    newStatements.append(setGeneratedBy(maker.Try(setGeneratedBy(maker.Block(0, tryBlock.toList()), ast), List.<JCCatch>nil(), finalizer), ast));

    if (blockNode instanceof JCBlock) {
        ((JCBlock)blockNode).stats = newStatements.toList();
    } else if (blockNode instanceof JCCase) {
        ((JCCase)blockNode).stats = newStatements.toList();
    } else if (blockNode instanceof JCMethodDecl) {
        ((JCMethodDecl)blockNode).body.stats = newStatements.toList();
    } else throw new AssertionError("Should not get here");

    ancestor.rebuild();
}