下面列出了怎么用org.eclipse.jdt.core.dom.InfixExpression的API类实例代码及写法,或者点击链接到github查看源代码。
/**
* Tests whether a given expression is a String contant.
* */
boolean isStringContant(Expression arg) {
if(arg instanceof StringLiteral) {
return true;
} else
if(arg instanceof InfixExpression) {
InfixExpression infixExpr = (InfixExpression) arg;
if(!isStringContant(infixExpr.getLeftOperand())) return false;
if(!isStringContant(infixExpr.getRightOperand())) return false;
for(Iterator iter2 = infixExpr.extendedOperands().iterator(); iter2.hasNext(); ) {
if(!isStringContant((Expression) iter2.next())) {
return false;
}
}
return true;
}
return false;
}
public Expression getLongAddress(MethodInvocation mi) {
Expression indexExpr = getLongAddressBase(mi);
NumberLiteral lit = (NumberLiteral)mi.arguments().get(2);
if(offset != Integer.parseInt(lit.getToken()))
throw new IllegalArgumentException("offset != " + lit);
Expression args;
if(offset == 0) args = indexExpr;
else {
InfixExpression add = ast.newInfixExpression();
add.setOperator(InfixExpression.Operator.PLUS);
add.setLeftOperand(indexExpr);
add.setRightOperand(returnInt(offset));
args = add;
}
return args;
}
public static IExpressionFragment createSubPartFragmentBySourceRange(InfixExpression node, ISourceRange range, ICompilationUnit cu) throws JavaModelException {
Assert.isNotNull(node);
Assert.isNotNull(range);
Assert.isTrue(!Util.covers(range, node));
Assert.isTrue(Util.covers(SourceRangeFactory.create(node), range));
if (!isAssociativeInfix(node)) {
return null;
}
InfixExpression groupRoot = findGroupRoot(node);
Assert.isTrue(isAGroupRoot(groupRoot));
List<Expression> groupMembers = AssociativeInfixExpressionFragment.findGroupMembersInOrderFor(groupRoot);
List<Expression> subGroup = findSubGroupForSourceRange(groupMembers, range);
if (subGroup.isEmpty() || rangeIncludesExtraNonWhitespace(range, subGroup, cu)) {
return null;
}
return new AssociativeInfixExpressionFragment(groupRoot, subGroup);
}
private Statement createAddQualifiedHashCode(IVariableBinding binding) {
MethodInvocation invoc= fAst.newMethodInvocation();
invoc.setExpression(getThisAccessForHashCode(binding.getName()));
invoc.setName(fAst.newSimpleName(METHODNAME_HASH_CODE));
InfixExpression expr= fAst.newInfixExpression();
expr.setOperator(Operator.EQUALS);
expr.setLeftOperand(getThisAccessForHashCode(binding.getName()));
expr.setRightOperand(fAst.newNullLiteral());
ConditionalExpression cexpr= fAst.newConditionalExpression();
cexpr.setThenExpression(fAst.newNumberLiteral("0")); //$NON-NLS-1$
cexpr.setElseExpression(invoc);
cexpr.setExpression(parenthesize(expr));
return prepareAssignment(parenthesize(cexpr));
}
private Statement prepareAssignment(Expression rightHand) {
// result = PRIME*result + (...)
InfixExpression mul= fAst.newInfixExpression();
mul.setLeftOperand(fAst.newSimpleName(VARIABLE_NAME_PRIME));
mul.setRightOperand(fAst.newSimpleName(VARIABLE_NAME_RESULT));
mul.setOperator(Operator.TIMES);
Assignment ass= fAst.newAssignment();
ass.setLeftHandSide(fAst.newSimpleName(VARIABLE_NAME_RESULT));
InfixExpression plus= fAst.newInfixExpression();
plus.setLeftOperand(mul);
plus.setOperator(Operator.PLUS);
plus.setRightOperand(rightHand);
ass.setRightHandSide(plus);
return fAst.newExpressionStatement(ass);
}
/**
* Helper to generate an index based <code>for</code> loop to iterate over a {@link List}
* implementation.
*
* @param ast the current {@link AST} instance to generate the {@link ASTRewrite} for
* @return an applicable {@link ASTRewrite} instance
*/
private ASTRewrite generateIndexBasedForRewrite(AST ast) {
ASTRewrite rewrite= ASTRewrite.create(ast);
ForStatement loopStatement= ast.newForStatement();
SimpleName loopVariableName= resolveLinkedVariableNameWithProposals(rewrite, "int", null, true); //$NON-NLS-1$
loopStatement.initializers().add(getForInitializer(ast, loopVariableName));
MethodInvocation listSizeExpression= ast.newMethodInvocation();
listSizeExpression.setName(ast.newSimpleName("size")); //$NON-NLS-1$
Expression listExpression= (Expression) rewrite.createCopyTarget(fCurrentExpression);
listSizeExpression.setExpression(listExpression);
loopStatement.setExpression(getLinkedInfixExpression(rewrite, loopVariableName.getIdentifier(), listSizeExpression, InfixExpression.Operator.LESS));
loopStatement.updaters().add(getLinkedIncrementExpression(rewrite, loopVariableName.getIdentifier()));
Block forLoopBody= ast.newBlock();
forLoopBody.statements().add(ast.newExpressionStatement(getIndexBasedForBodyAssignment(rewrite, loopVariableName)));
forLoopBody.statements().add(createBlankLineStatementWithCursorPosition(rewrite));
loopStatement.setBody(forLoopBody);
rewrite.replace(fCurrentNode, loopStatement, null);
return rewrite;
}
/**
* Creates the new <CODE>InfixExpression</CODE> <CODE>(x & 1) == 1</CODE>.
*/
@Override
protected InfixExpression createCorrectOddnessCheck(ASTRewrite rewrite, Expression numberExpression) {
Assert.isNotNull(rewrite);
Assert.isNotNull(numberExpression);
final AST ast = rewrite.getAST();
InfixExpression andOddnessCheck = ast.newInfixExpression();
ParenthesizedExpression parenthesizedExpression = ast.newParenthesizedExpression();
InfixExpression andExpression = ast.newInfixExpression();
andExpression.setLeftOperand((Expression) rewrite.createMoveTarget(numberExpression));
andExpression.setOperator(AND);
andExpression.setRightOperand(ast.newNumberLiteral("1"));
parenthesizedExpression.setExpression(andExpression);
andOddnessCheck.setLeftOperand(parenthesizedExpression);
andOddnessCheck.setOperator(EQUALS);
andOddnessCheck.setRightOperand(ast.newNumberLiteral("1"));
return andOddnessCheck;
}
private boolean needsParentesis(ASTNode node) {
if (!(node.getParent() instanceof InfixExpression))
return false;
if (node instanceof InstanceofExpression)
return true;
if (node instanceof InfixExpression) {
InfixExpression expression = (InfixExpression) node;
InfixExpression.Operator operator = expression.getOperator();
InfixExpression parentExpression = (InfixExpression) node.getParent();
InfixExpression.Operator parentOperator = parentExpression.getOperator();
if (parentOperator == operator)
return false;
return true;
}
return false;
}
@Override
protected void repairBug(ASTRewrite rewrite, CompilationUnit workingUnit, BugInstance bug) throws BugResolutionException {
Assert.isNotNull(rewrite);
Assert.isNotNull(workingUnit);
Assert.isNotNull(bug);
InfixExpression oddnessCheck = findOddnessCheck(getASTNode(workingUnit, bug.getPrimarySourceLineAnnotation()));
if (oddnessCheck == null) {
throw new BugResolutionException("No matching oddness check found at the specified source line.");
}
Expression numberExpression = findNumberExpression(oddnessCheck);
if (numberExpression == null) {
throw new BugResolutionException();
}
InfixExpression correctOddnessCheck = createCorrectOddnessCheck(rewrite, numberExpression);
rewrite.replace(oddnessCheck, correctOddnessCheck, null);
}
private static boolean isAllOperandsHaveSameType(InfixExpression expression, ITypeBinding leftOperandType, ITypeBinding rightOperandType) {
ITypeBinding binding= leftOperandType;
if (binding == null)
return false;
ITypeBinding current= rightOperandType;
if (binding != current)
return false;
for (Iterator<Expression> iterator= expression.extendedOperands().iterator(); iterator.hasNext();) {
Expression operand= iterator.next();
current= operand.resolveTypeBinding();
if (binding != current)
return false;
}
return true;
}
public boolean visit(InfixExpression expr) {
/*
* InfixExpression: Expression InfixOperator Expression { InfixOperator Expression }
*/
activateDiffStyle(expr);
StyledStringStyler styler = determineDiffStyle(expr, new StyledStringStyler(ordinaryStyle));
Expression leftExpression = expr.getLeftOperand();
handleExpression(leftExpression);
appendSpace();
styledString.append(expr.getOperator().toString(), styler);
appendSpace();
Expression rightExpression = expr.getRightOperand();
handleExpression(rightExpression);
for (int i = 0; i < expr.extendedOperands().size(); i++){
appendSpace();
styledString.append(expr.getOperator().toString(), styler);
appendSpace();
handleExpression((Expression) expr.extendedOperands().get(i));
}
deactivateDiffStyle(expr);
return false;
}
protected Expression constructExpression(AST ast, DefaultMutableTreeNode node) {
Object object = node.getUserObject();
if(object instanceof InfixExpression.Operator) {
InfixExpression.Operator operator = (InfixExpression.Operator)object;
InfixExpression infixExpression = ast.newInfixExpression();
infixExpression.setOperator(operator);
DefaultMutableTreeNode leftChild = (DefaultMutableTreeNode)node.getChildAt(0);
DefaultMutableTreeNode rightChild = (DefaultMutableTreeNode)node.getChildAt(1);
infixExpression.setLeftOperand(constructExpression(ast, leftChild));
infixExpression.setRightOperand(constructExpression(ast, rightChild));
return infixExpression;
}
else if(object instanceof Expression) {
Expression expression = (Expression)object;
return expression;
}
return null;
}
public static ExpressionsFix createAddParanoidalParenthesisFix(CompilationUnit compilationUnit, ASTNode[] coveredNodes) {
if (coveredNodes == null)
return null;
if (coveredNodes.length == 0)
return null;
// check sub-expressions in fully covered nodes
final ArrayList<ASTNode> changedNodes = new ArrayList<ASTNode>();
for (int i= 0; i < coveredNodes.length; i++) {
ASTNode covered = coveredNodes[i];
if (covered instanceof InfixExpression)
covered.accept(new MissingParenthesisVisitor(changedNodes));
}
if (changedNodes.isEmpty() || (changedNodes.size() == 1 && changedNodes.get(0).equals(coveredNodes[0])))
return null;
CompilationUnitRewriteOperation op= new AddParenthesisOperation(changedNodes.toArray(new Expression[changedNodes.size()]));
return new ExpressionsFix(FixMessages.ExpressionsFix_addParanoiacParentheses_description, compilationUnit, new CompilationUnitRewriteOperation[] {op});
}
public Expression addLongAddressOffset(Expression e) {
Expression args;
if(offset == 0) args = e;
else {
InfixExpression add = ast.newInfixExpression();
add.setOperator(InfixExpression.Operator.PLUS);
add.setLeftOperand(e);
add.setRightOperand(returnInt(offset));
args = add;
}
return args;
}
public Expression addOffset(Expression e, int offset) {
if(offset == 0) return e;
InfixExpression add = ast.newInfixExpression();
add.setOperator(InfixExpression.Operator.PLUS);
add.setLeftOperand(e);
add.setRightOperand(returnInt(offset));
return add;
}
public boolean allParentNodesAreConditionalOrOperators() {
Enumeration<DefaultMutableTreeNode> enumeration = root.breadthFirstEnumeration();
while(enumeration.hasMoreElements()) {
DefaultMutableTreeNode node = enumeration.nextElement();
if(!node.isLeaf()) {
InfixExpression.Operator operator = (InfixExpression.Operator)node.getUserObject();
if(!operator.equals(InfixExpression.Operator.CONDITIONAL_OR))
return false;
}
}
return true;
}
private static Expression getBooleanExpression(ASTNode node) {
if (!(node instanceof Expression)) {
return null;
}
// check if the node is a location where it can be negated
StructuralPropertyDescriptor locationInParent= node.getLocationInParent();
if (locationInParent == QualifiedName.NAME_PROPERTY) {
node= node.getParent();
locationInParent= node.getLocationInParent();
}
while (locationInParent == ParenthesizedExpression.EXPRESSION_PROPERTY) {
node= node.getParent();
locationInParent= node.getLocationInParent();
}
Expression expression= (Expression) node;
if (!isBoolean(expression)) {
return null;
}
if (expression.getParent() instanceof InfixExpression) {
return expression;
}
if (locationInParent == Assignment.RIGHT_HAND_SIDE_PROPERTY || locationInParent == IfStatement.EXPRESSION_PROPERTY
|| locationInParent == WhileStatement.EXPRESSION_PROPERTY || locationInParent == DoStatement.EXPRESSION_PROPERTY
|| locationInParent == ReturnStatement.EXPRESSION_PROPERTY || locationInParent == ForStatement.EXPRESSION_PROPERTY
|| locationInParent == AssertStatement.EXPRESSION_PROPERTY || locationInParent == MethodInvocation.ARGUMENTS_PROPERTY
|| locationInParent == ConstructorInvocation.ARGUMENTS_PROPERTY || locationInParent == SuperMethodInvocation.ARGUMENTS_PROPERTY
|| locationInParent == EnumConstantDeclaration.ARGUMENTS_PROPERTY || locationInParent == SuperConstructorInvocation.ARGUMENTS_PROPERTY
|| locationInParent == ClassInstanceCreation.ARGUMENTS_PROPERTY || locationInParent == ConditionalExpression.EXPRESSION_PROPERTY
|| locationInParent == PrefixExpression.OPERAND_PROPERTY) {
return expression;
}
return null;
}
private void processExpression(DefaultMutableTreeNode parent, Expression expression) {
if(expression instanceof InfixExpression) {
InfixExpression infixExpression = (InfixExpression)expression;
InfixExpression.Operator operator = infixExpression.getOperator();
if(operator.equals(InfixExpression.Operator.CONDITIONAL_AND) || operator.equals(InfixExpression.Operator.CONDITIONAL_OR)) {
parent.setUserObject(operator);
DefaultMutableTreeNode leftOperandNode = new DefaultMutableTreeNode();
DefaultMutableTreeNode rightOperandNode = new DefaultMutableTreeNode();
parent.add(leftOperandNode);
parent.add(rightOperandNode);
processExpression(leftOperandNode, infixExpression.getLeftOperand());
processExpression(rightOperandNode, infixExpression.getRightOperand());
if(infixExpression.hasExtendedOperands()) {
DefaultMutableTreeNode grandParent = (DefaultMutableTreeNode)parent.getParent();
int parentIndex = -1;
if(grandParent != null)
parentIndex = grandParent.getIndex(parent);
DefaultMutableTreeNode newParent = processExtendedOperands(parent, infixExpression.extendedOperands());
if(grandParent != null)
grandParent.insert(newParent, parentIndex);
else
root = newParent;
}
}
else {
parent.setUserObject(infixExpression);
}
}
else {
parent.setUserObject(expression);
}
}
private void writeRightShiftUnsigned(InfixExpression infixExpression) {
ITypeBinding typeBinding = infixExpression.getLeftOperand().resolveTypeBinding();
String typeName = typeBinding.getName();
//TODO: Remove inner parens for left operand if it's a simple (single elmt) expression, not needing them
String cSharpTypeName;
String cSharpUnsignedTypeName;
if (typeBinding.getName().equals("long")) {
cSharpTypeName = "long";
cSharpUnsignedTypeName = "ulong";
} else if (typeBinding.getName().equals("int")) {
cSharpTypeName = "int";
cSharpUnsignedTypeName = "uint";
} else if (typeBinding.getName().equals("short")) {
cSharpTypeName = "short";
cSharpUnsignedTypeName = "ushort";
} else if (typeBinding.getName().equals("byte")) {
cSharpTypeName = "sbyte";
cSharpUnsignedTypeName = "byte";
}
else throw new JUniversalException("Unexpected >>> left operand type: " + typeName);
write("(" + cSharpTypeName + ")((" + cSharpUnsignedTypeName + ")(");
writeNode(infixExpression.getLeftOperand());
write(")");
copySpaceAndComments();
matchAndWrite(">>>", ">>");
copySpaceAndComments();
writeNode(infixExpression.getRightOperand());
write(")");
if (infixExpression.hasExtendedOperands())
throw sourceNotSupported(">>> extended operands (with multiple >>> operators in a row, like 'a >>> b >>> c') not currently supported");
}
/**
* Creates an {@link InfixExpression} which is linked to the group of the variableToIncrement.
*
* @param rewrite the current {@link ASTRewrite} instance
* @param variableToIncrement the name of the variable to generate the {@link InfixExpression}
* for
* @param rightHandSide the right hand side expression which shall be included in the
* {@link InfixExpression}
* @param operator the {@link org.eclipse.jdt.core.dom.InfixExpression.Operator} to use in the
* {@link InfixExpression} to create
* @return a filled, new {@link InfixExpression} instance
*/
private InfixExpression getLinkedInfixExpression(ASTRewrite rewrite, String variableToIncrement, Expression rightHandSide, InfixExpression.Operator operator) {
AST ast= rewrite.getAST();
InfixExpression loopExpression= ast.newInfixExpression();
SimpleName name= ast.newSimpleName(variableToIncrement);
addLinkedPosition(rewrite.track(name), LinkedPositionGroup.NO_STOP, name.getIdentifier());
loopExpression.setLeftOperand(name);
loopExpression.setOperator(operator);
loopExpression.setRightOperand(rightHandSide);
return loopExpression;
}
protected InfixExpression createInfixExpression(Expression leftOperand, Operator operator, Expression rightOperand) {
InfixExpression expression= fAst.newInfixExpression();
expression.setLeftOperand(leftOperand);
expression.setOperator(operator);
expression.setRightOperand(rightOperand);
return expression;
}
@Override
public boolean visit(InfixExpression node) {
/* Try creating an associative infix expression fragment
/* for the full subtree. If this is not applicable,
* try something more generic.
*/
IASTFragment fragment = AssociativeInfixExpressionFragment.createFragmentForFullSubtree(node);
if (fragment == null) {
return visit((Expression) node);
}
setFragment(fragment);
return false;
}
@Override
public void endVisit(InfixExpression node) {
if (skipNode(node)) {
return;
}
GenericSequentialFlowInfo info = processSequential(node, node.getLeftOperand(), node.getRightOperand());
process(info, node.extendedOperands());
}
private static Expression getBooleanExpression(ASTNode node) {
if (!(node instanceof Expression)) {
return null;
}
// check if the node is a location where it can be negated
StructuralPropertyDescriptor locationInParent = node.getLocationInParent();
if (locationInParent == QualifiedName.NAME_PROPERTY) {
node = node.getParent();
locationInParent = node.getLocationInParent();
}
while (locationInParent == ParenthesizedExpression.EXPRESSION_PROPERTY) {
node = node.getParent();
locationInParent = node.getLocationInParent();
}
Expression expression = (Expression) node;
if (!isBoolean(expression)) {
return null;
}
if (expression.getParent() instanceof InfixExpression) {
return expression;
}
if (locationInParent == Assignment.RIGHT_HAND_SIDE_PROPERTY || locationInParent == IfStatement.EXPRESSION_PROPERTY || locationInParent == WhileStatement.EXPRESSION_PROPERTY || locationInParent == DoStatement.EXPRESSION_PROPERTY
|| locationInParent == ReturnStatement.EXPRESSION_PROPERTY || locationInParent == ForStatement.EXPRESSION_PROPERTY || locationInParent == AssertStatement.EXPRESSION_PROPERTY
|| locationInParent == MethodInvocation.ARGUMENTS_PROPERTY || locationInParent == ConstructorInvocation.ARGUMENTS_PROPERTY || locationInParent == SuperMethodInvocation.ARGUMENTS_PROPERTY
|| locationInParent == EnumConstantDeclaration.ARGUMENTS_PROPERTY || locationInParent == SuperConstructorInvocation.ARGUMENTS_PROPERTY || locationInParent == ClassInstanceCreation.ARGUMENTS_PROPERTY
|| locationInParent == ConditionalExpression.EXPRESSION_PROPERTY || locationInParent == PrefixExpression.OPERAND_PROPERTY) {
return expression;
}
return null;
}
private static Expression getInversedInfixExpression(ASTRewrite rewrite, InfixExpression expression, InfixExpression.Operator newOperator, SimpleNameRenameProvider provider) {
InfixExpression newExpression = rewrite.getAST().newInfixExpression();
newExpression.setOperator(newOperator);
newExpression.setLeftOperand(getRenamedNameCopy(provider, rewrite, expression.getLeftOperand()));
newExpression.setRightOperand(getRenamedNameCopy(provider, rewrite, expression.getRightOperand()));
return newExpression;
}
private static boolean isSelectingOperator(ASTNode n1, ASTNode n2, int offset, int length) {
// between the nodes
if (offset + length <= n2.getStartPosition() && offset >= ASTNodes.getExclusiveEnd(n1)) {
return true;
}
// or exactly select the node (but not with infix expressions)
if (n1.getStartPosition() == offset && ASTNodes.getExclusiveEnd(n2) == offset + length) {
if (n1 instanceof InfixExpression || n2 instanceof InfixExpression) {
return false;
}
return true;
}
return false;
}
public InfixExpressionWriter(SwiftSourceFileWriter swiftASTWriters) {
super(swiftASTWriters);
// TODO: Handle fact that Swift's operator precedence is different than Java's
equivalentOperators = new HashMap<>();
equivalentOperators.put(InfixExpression.Operator.TIMES, "*");
equivalentOperators.put(InfixExpression.Operator.DIVIDE, "/");
equivalentOperators.put(InfixExpression.Operator.REMAINDER, "%");
equivalentOperators.put(InfixExpression.Operator.PLUS, "+");
equivalentOperators.put(InfixExpression.Operator.MINUS, "-");
// TODO: Test signed / unsigned semantics here
equivalentOperators.put(InfixExpression.Operator.LEFT_SHIFT, "<<");
equivalentOperators.put(InfixExpression.Operator.RIGHT_SHIFT_SIGNED, ">>");
//cppOperators.put(InfixExpression.Operator.RIGHT_SHIFT_UNSIGNED, ">>>");
equivalentOperators.put(InfixExpression.Operator.LESS, "<");
equivalentOperators.put(InfixExpression.Operator.GREATER, ">");
equivalentOperators.put(InfixExpression.Operator.LESS_EQUALS, "<=");
equivalentOperators.put(InfixExpression.Operator.GREATER_EQUALS, ">=");
equivalentOperators.put(InfixExpression.Operator.EQUALS, "==");
equivalentOperators.put(InfixExpression.Operator.NOT_EQUALS, "!=");
equivalentOperators.put(InfixExpression.Operator.AND, "&");
equivalentOperators.put(InfixExpression.Operator.XOR, "^");
equivalentOperators.put(InfixExpression.Operator.OR, "|");
equivalentOperators.put(InfixExpression.Operator.CONDITIONAL_AND, "&&");
equivalentOperators.put(InfixExpression.Operator.CONDITIONAL_OR, "||");
}
protected boolean isInfixExpressionWithCompositeParent(ASTNode node) {
if(node instanceof InfixExpression &&
(node.getParent() instanceof IfStatement || node.getParent() instanceof InfixExpression ||
node.getParent() instanceof WhileStatement || node.getParent() instanceof DoStatement ||
node.getParent() instanceof ForStatement)) {
return true;
}
return false;
}
@Override
public boolean visit(InfixExpression node) {
/* Try creating an associative infix expression fragment
/* for the full subtree. If this is not applicable,
* try something more generic.
*/
IASTFragment fragment= AssociativeInfixExpressionFragment.createFragmentForFullSubtree(node);
if(fragment == null)
return visit((Expression) node);
setFragment(fragment);
return false;
}
private static ThrowStatement getThrowForUnsupportedCase(Expression switchExpr, AST ast, ASTRewrite astRewrite) {
ThrowStatement newThrowStatement = ast.newThrowStatement();
ClassInstanceCreation newCic = ast.newClassInstanceCreation();
newCic.setType(ast.newSimpleType(ast.newSimpleName("UnsupportedOperationException"))); //$NON-NLS-1$
InfixExpression newInfixExpr = ast.newInfixExpression();
StringLiteral newStringLiteral = ast.newStringLiteral();
newStringLiteral.setLiteralValue("Unimplemented case: "); //$NON-NLS-1$
newInfixExpr.setLeftOperand(newStringLiteral);
newInfixExpr.setOperator(InfixExpression.Operator.PLUS);
newInfixExpr.setRightOperand((Expression) astRewrite.createCopyTarget(switchExpr));
newCic.arguments().add(newInfixExpr);
newThrowStatement.setExpression(newCic);
return newThrowStatement;
}