org.eclipse.jdt.core.dom.ParenthesizedExpression Java Examples

The following examples show how to use org.eclipse.jdt.core.dom.ParenthesizedExpression. 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: ExtractTempRefactoring.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
private RefactoringStatus checkExpression() throws JavaModelException {
	Expression selectedExpression= getSelectedExpression().getAssociatedExpression();
	if (selectedExpression != null) {
		final ASTNode parent= selectedExpression.getParent();
		if (selectedExpression instanceof NullLiteral) {
			return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.ExtractTempRefactoring_null_literals);
		} else if (selectedExpression instanceof ArrayInitializer) {
			return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.ExtractTempRefactoring_array_initializer);
		} else if (selectedExpression instanceof Assignment) {
			if (parent instanceof Expression && !(parent instanceof ParenthesizedExpression))
				return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.ExtractTempRefactoring_assignment);
			else
				return null;
		} else if (selectedExpression instanceof SimpleName) {
			if ((((SimpleName) selectedExpression)).isDeclaration())
				return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.ExtractTempRefactoring_names_in_declarations);
			if (parent instanceof QualifiedName && selectedExpression.getLocationInParent() == QualifiedName.NAME_PROPERTY || parent instanceof FieldAccess && selectedExpression.getLocationInParent() == FieldAccess.NAME_PROPERTY)
				return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.ExtractTempRefactoring_select_expression);
		} else if (selectedExpression instanceof VariableDeclarationExpression && parent instanceof TryStatement) {
			return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.ExtractTempRefactoring_resource_in_try_with_resources);
		}
	}

	return null;
}
 
Example #2
Source File: AdvancedQuickAssistProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
private static Expression combineOperands(ASTRewrite rewrite, Expression existing, Expression originalNode, boolean removeParentheses, Operator operator) {
	if (existing == null && removeParentheses) {
		while (originalNode instanceof ParenthesizedExpression) {
			originalNode= ((ParenthesizedExpression)originalNode).getExpression();
		}
	}
	Expression newRight= (Expression)rewrite.createMoveTarget(originalNode);
	if (originalNode instanceof InfixExpression) {
		((InfixExpression)newRight).setOperator(((InfixExpression)originalNode).getOperator());
	}

	if (existing == null) {
		return newRight;
	}
	AST ast= rewrite.getAST();
	InfixExpression infix= ast.newInfixExpression();
	infix.setOperator(operator);
	infix.setLeftOperand(existing);
	infix.setRightOperand(newRight);
	return infix;
}
 
Example #3
Source File: AdvancedQuickAssistProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
private static boolean getRemoveExtraParenthesesProposals(IInvocationContext context, ASTNode covering, ArrayList<ASTNode> coveredNodes, Collection<ICommandAccess> resultingCollections) {
	ArrayList<ASTNode> nodes;
	if (context.getSelectionLength() == 0 && covering instanceof ParenthesizedExpression) {
		nodes= new ArrayList<ASTNode>();
		nodes.add(covering);
	} else {
		nodes= coveredNodes;
	}
	if (nodes.isEmpty())
		return false;

	IProposableFix fix= ExpressionsFix.createRemoveUnnecessaryParenthesisFix(context.getASTRoot(), nodes.toArray(new ASTNode[nodes.size()]));
	if (fix == null)
		return false;

	if (resultingCollections == null)
		return true;

	Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_REMOVE);
	Map<String, String> options= new Hashtable<String, String>();
	options.put(CleanUpConstants.EXPRESSIONS_USE_PARENTHESES, CleanUpOptions.TRUE);
	options.put(CleanUpConstants.EXPRESSIONS_USE_PARENTHESES_NEVER, CleanUpOptions.TRUE);
	FixCorrectionProposal proposal= new FixCorrectionProposal(fix, new ExpressionsCleanUp(options), IProposalRelevance.REMOVE_EXTRA_PARENTHESES, image, context);
	resultingCollections.add(proposal);
	return true;
}
 
Example #4
Source File: ExpressionVariable.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
public static IBinding resolveBinding(Expression expression){
	if (expression instanceof Name)
		return ((Name)expression).resolveBinding();
	if (expression instanceof ParenthesizedExpression)
		return resolveBinding(((ParenthesizedExpression)expression).getExpression());
	else if (expression instanceof Assignment)
		return resolveBinding(((Assignment)expression).getLeftHandSide());//TODO ???
	else if (expression instanceof MethodInvocation)
		return ((MethodInvocation)expression).resolveMethodBinding();
	else if (expression instanceof SuperMethodInvocation)
		return ((SuperMethodInvocation)expression).resolveMethodBinding();
	else if (expression instanceof FieldAccess)
		return ((FieldAccess)expression).resolveFieldBinding();
	else if (expression instanceof SuperFieldAccess)
		return ((SuperFieldAccess)expression).resolveFieldBinding();
	else if (expression instanceof ConditionalExpression)
		return resolveBinding(((ConditionalExpression)expression).getThenExpression());
	return null;
}
 
Example #5
Source File: NecessaryParenthesesChecker.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
private static boolean locationNeedsParentheses(StructuralPropertyDescriptor locationInParent) {
	if (locationInParent instanceof ChildListPropertyDescriptor && locationInParent != InfixExpression.EXTENDED_OPERANDS_PROPERTY) {
		// e.g. argument lists of MethodInvocation, ClassInstanceCreation, dimensions of ArrayCreation ...
		return false;
	}
	if (locationInParent == VariableDeclarationFragment.INITIALIZER_PROPERTY
			|| locationInParent == SingleVariableDeclaration.INITIALIZER_PROPERTY
			|| locationInParent == ReturnStatement.EXPRESSION_PROPERTY
			|| locationInParent == EnhancedForStatement.EXPRESSION_PROPERTY
			|| locationInParent == ForStatement.EXPRESSION_PROPERTY
			|| locationInParent == WhileStatement.EXPRESSION_PROPERTY
			|| locationInParent == DoStatement.EXPRESSION_PROPERTY
			|| locationInParent == AssertStatement.EXPRESSION_PROPERTY
			|| locationInParent == AssertStatement.MESSAGE_PROPERTY
			|| locationInParent == IfStatement.EXPRESSION_PROPERTY
			|| locationInParent == SwitchStatement.EXPRESSION_PROPERTY
			|| locationInParent == SwitchCase.EXPRESSION_PROPERTY
			|| locationInParent == ArrayAccess.INDEX_PROPERTY
			|| locationInParent == ThrowStatement.EXPRESSION_PROPERTY
			|| locationInParent == SynchronizedStatement.EXPRESSION_PROPERTY
			|| locationInParent == ParenthesizedExpression.EXPRESSION_PROPERTY) {
		return false;
	}
	return true;
}
 
Example #6
Source File: CreateAndOddnessCheckResolution.java    From spotbugs with GNU Lesser General Public License v2.1 6 votes vote down vote up
/**
 * Creates the new <CODE>InfixExpression</CODE> <CODE>(x &amp; 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;

}
 
Example #7
Source File: AssociativeInfixExpressionFragment.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
public void replace(ASTRewrite rewrite, ASTNode replacement, TextEditGroup textEditGroup) {
	ASTNode groupNode= getGroupRoot();

	List<Expression> allOperands= findGroupMembersInOrderFor(getGroupRoot());
	if (allOperands.size() == fOperands.size()) {
		if (replacement instanceof Name && groupNode.getParent() instanceof ParenthesizedExpression) {
			// replace including the parenthesized expression around it
			rewrite.replace(groupNode.getParent(), replacement, textEditGroup);
		} else {
			rewrite.replace(groupNode, replacement, textEditGroup);
		}
		return;
	}

	rewrite.replace(fOperands.get(0), replacement, textEditGroup);
	int first= allOperands.indexOf(fOperands.get(0));
	int after= first + fOperands.size();
	for (int i= first + 1; i < after; i++) {
		rewrite.remove(allOperands.get(i), textEditGroup);
	}
}
 
Example #8
Source File: ExpressionsFix.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public void rewriteAST(CompilationUnitRewrite cuRewrite, LinkedProposalModel model) throws CoreException {
	TextEditGroup group= createTextEditGroup(FixMessages.ExpressionsFix_addParanoiacParentheses_description, cuRewrite);

	ASTRewrite rewrite= cuRewrite.getASTRewrite();
	AST ast= cuRewrite.getRoot().getAST();

	for (int i= 0; i < fExpressions.length; i++) {
		// add parenthesis around expression
		Expression expression= fExpressions[i];

		ParenthesizedExpression parenthesizedExpression= ast.newParenthesizedExpression();
		parenthesizedExpression.setExpression((Expression) rewrite.createCopyTarget(expression));
		rewrite.replace(expression, parenthesizedExpression, group);
	}
}
 
Example #9
Source File: ASTNodeMatcher.java    From JDeodorant with MIT License 6 votes vote down vote up
protected boolean isTypeHolder(Object o) {
	if(o.getClass().equals(MethodInvocation.class) || o.getClass().equals(SuperMethodInvocation.class)			
			|| o.getClass().equals(NumberLiteral.class) || o.getClass().equals(StringLiteral.class)
			|| o.getClass().equals(CharacterLiteral.class) || o.getClass().equals(BooleanLiteral.class)
			|| o.getClass().equals(TypeLiteral.class) || o.getClass().equals(NullLiteral.class)
			|| o.getClass().equals(ArrayCreation.class)
			|| o.getClass().equals(ClassInstanceCreation.class)
			|| o.getClass().equals(ArrayAccess.class) || o.getClass().equals(FieldAccess.class)
			|| o.getClass().equals(SuperFieldAccess.class) || o.getClass().equals(ParenthesizedExpression.class)
			|| o.getClass().equals(SimpleName.class) || o.getClass().equals(QualifiedName.class)
			|| o.getClass().equals(CastExpression.class) || o.getClass().equals(InfixExpression.class)
			|| o.getClass().equals(PrefixExpression.class) || o.getClass().equals(InstanceofExpression.class)
			|| o.getClass().equals(ThisExpression.class) || o.getClass().equals(ConditionalExpression.class))
		return true;
	return false;
}
 
Example #10
Source File: UnusedCodeFix.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
private static void replaceCast(CastExpression castExpression, Expression replacement, ASTRewrite rewrite, TextEditGroup group) {
	boolean castEnclosedInNecessaryParentheses= castExpression.getParent() instanceof ParenthesizedExpression
			&& NecessaryParenthesesChecker.needsParentheses(castExpression, castExpression.getParent().getParent(), castExpression.getParent().getLocationInParent());
	
	ASTNode toReplace= castEnclosedInNecessaryParentheses ? castExpression.getParent() : castExpression;
	ASTNode move;
	if (NecessaryParenthesesChecker.needsParentheses(replacement, toReplace.getParent(), toReplace.getLocationInParent())) {
		if (replacement.getParent() instanceof ParenthesizedExpression) {
			move= rewrite.createMoveTarget(replacement.getParent());
		} else if (castEnclosedInNecessaryParentheses) {
			toReplace= castExpression;
			move= rewrite.createMoveTarget(replacement);
		} else {
			ParenthesizedExpression parentheses= replacement.getAST().newParenthesizedExpression();
			parentheses.setExpression((Expression) rewrite.createMoveTarget(replacement));
			move= parentheses;
		}
	} else {
		move= rewrite.createMoveTarget(replacement);
	}
	rewrite.replace(toReplace, move, group);
}
 
Example #11
Source File: UnusedCodeFix.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
public static UnusedCodeFix createRemoveUnusedCastFix(CompilationUnit compilationUnit, IProblemLocation problem) {
	if (problem.getProblemId() != IProblem.UnnecessaryCast)
		return null;

	ASTNode selectedNode= problem.getCoveringNode(compilationUnit);

	ASTNode curr= selectedNode;
	while (curr instanceof ParenthesizedExpression) {
		curr= ((ParenthesizedExpression) curr).getExpression();
	}

	if (!(curr instanceof CastExpression))
		return null;

	return new UnusedCodeFix(FixMessages.UnusedCodeFix_RemoveCast_description, compilationUnit, new CompilationUnitRewriteOperation[] {new RemoveCastOperation((CastExpression)curr)});
}
 
Example #12
Source File: UnusedCodeFix.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public void rewriteAST(CompilationUnitRewrite cuRewrite, LinkedProposalModel model) throws CoreException {

	TextEditGroup group= createTextEditGroup(FixMessages.UnusedCodeFix_RemoveCast_description, cuRewrite);

	ASTRewrite rewrite= cuRewrite.getASTRewrite();

	CastExpression cast= fCast;
	Expression expression= cast.getExpression();
	if (expression instanceof ParenthesizedExpression) {
		Expression childExpression= ((ParenthesizedExpression) expression).getExpression();
		if (NecessaryParenthesesChecker.needsParentheses(childExpression, cast, CastExpression.EXPRESSION_PROPERTY)) {
			expression= childExpression;
		}
	}
	
	replaceCast(cast, expression, rewrite, group);
}
 
Example #13
Source File: InvertBooleanUtility.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
private static Expression combineOperands(ASTRewrite rewrite, Expression existing, Expression originalNode, boolean removeParentheses, Operator operator) {
	if (existing == null && removeParentheses) {
		while (originalNode instanceof ParenthesizedExpression) {
			originalNode = ((ParenthesizedExpression) originalNode).getExpression();
		}
	}
	Expression newRight = (Expression) rewrite.createMoveTarget(originalNode);
	if (originalNode instanceof InfixExpression) {
		((InfixExpression) newRight).setOperator(((InfixExpression) originalNode).getOperator());
	}

	if (existing == null) {
		return newRight;
	}
	AST ast = rewrite.getAST();
	InfixExpression infix = ast.newInfixExpression();
	infix.setOperator(operator);
	infix.setLeftOperand(existing);
	infix.setRightOperand(newRight);
	return infix;
}
 
Example #14
Source File: AdvancedQuickAssistProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
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;
}
 
Example #15
Source File: SimpleFragment.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
public void replace(ASTRewrite rewrite, ASTNode replacement, TextEditGroup textEditGroup) {
	if (replacement instanceof Name && fNode.getParent() instanceof ParenthesizedExpression) {
		// replace including the parenthesized expression around it
		rewrite.replace(fNode.getParent(), replacement, textEditGroup);
	} else {
		rewrite.replace(fNode, replacement, textEditGroup);
	}
}
 
Example #16
Source File: AdvancedQuickAssistProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private static boolean isNegated(Expression expression) {
	if (!(expression.getParent() instanceof ParenthesizedExpression))
		return false;

	ParenthesizedExpression parenthesis= (ParenthesizedExpression) expression.getParent();
	if (!(parenthesis.getParent() instanceof PrefixExpression))
		return false;

	PrefixExpression prefix= (PrefixExpression) parenthesis.getParent();
	if (!(prefix.getOperator() == PrefixExpression.Operator.NOT))
		return false;

	return true;
}
 
Example #17
Source File: AdvancedQuickAssistProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private static Expression getInversedNotExpression(ASTRewrite rewrite, Expression expression, AST ast) {
	PrefixExpression prefixExpression= ast.newPrefixExpression();
	prefixExpression.setOperator(PrefixExpression.Operator.NOT);
	ParenthesizedExpression parenthesizedExpression= getParenthesizedExpression(ast, (Expression)rewrite.createCopyTarget(expression));
	prefixExpression.setOperand(parenthesizedExpression);
	return prefixExpression;
}
 
Example #18
Source File: UnresolvedElementsSubProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private static boolean useExistingParentCastProposal(ICompilationUnit cu, CastExpression expression, Expression accessExpression, SimpleName accessSelector, ITypeBinding[] paramTypes, Collection<ICommandAccess> proposals) {
	ITypeBinding castType= expression.getType().resolveBinding();
	if (castType == null) {
		return false;
	}
	if (paramTypes != null) {
		if (Bindings.findMethodInHierarchy(castType, accessSelector.getIdentifier(), paramTypes) == null) {
			return false;
		}
	} else if (Bindings.findFieldInHierarchy(castType, accessSelector.getIdentifier()) == null) {
		return false;
	}
	ITypeBinding bindingToCast= accessExpression.resolveTypeBinding();
	if (bindingToCast != null && !bindingToCast.isCastCompatible(castType)) {
		return false;
	}

	IMethodBinding res= Bindings.findMethodInHierarchy(castType, accessSelector.getIdentifier(), paramTypes);
	if (res != null) {
		AST ast= expression.getAST();
		ASTRewrite rewrite= ASTRewrite.create(ast);
		CastExpression newCast= ast.newCastExpression();
		newCast.setType((Type) ASTNode.copySubtree(ast, expression.getType()));
		newCast.setExpression((Expression) rewrite.createCopyTarget(accessExpression));
		ParenthesizedExpression parents= ast.newParenthesizedExpression();
		parents.setExpression(newCast);

		ASTNode node= rewrite.createCopyTarget(expression.getExpression());
		rewrite.replace(expression, node, null);
		rewrite.replace(accessExpression, parents, null);

		String label= CorrectionMessages.UnresolvedElementsSubProcessor_missingcastbrackets_description;
		Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CAST);
		ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal(label, cu, rewrite, IProposalRelevance.ADD_PARENTHESES_AROUND_CAST, image);
		proposals.add(proposal);
		return true;
	}
	return false;
}
 
Example #19
Source File: GetterSetterUtil.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Checks if the assignment needs a downcast and inserts it if necessary
 *
 * @param expression the right hand-side
 * @param expressionType the type of the right hand-side. Can be null
 * @param ast the AST
 * @param variableType the Type of the variable the expression will be assigned to
 * @param is50OrHigher if <code>true</code> java 5.0 code will be assumed
 * @return the casted expression if necessary
 */
private static Expression createNarrowCastIfNessecary(Expression expression, ITypeBinding expressionType, AST ast, ITypeBinding variableType, boolean is50OrHigher) {
	PrimitiveType castTo= null;
	if (variableType.isEqualTo(expressionType))
		return expression; //no cast for same type
	if (is50OrHigher) {
		if (ast.resolveWellKnownType("java.lang.Character").isEqualTo(variableType)) //$NON-NLS-1$
			castTo= ast.newPrimitiveType(PrimitiveType.CHAR);
		if (ast.resolveWellKnownType("java.lang.Byte").isEqualTo(variableType)) //$NON-NLS-1$
			castTo= ast.newPrimitiveType(PrimitiveType.BYTE);
		if (ast.resolveWellKnownType("java.lang.Short").isEqualTo(variableType)) //$NON-NLS-1$
			castTo= ast.newPrimitiveType(PrimitiveType.SHORT);
	}
	if (ast.resolveWellKnownType("char").isEqualTo(variableType)) //$NON-NLS-1$
		castTo= ast.newPrimitiveType(PrimitiveType.CHAR);
	if (ast.resolveWellKnownType("byte").isEqualTo(variableType)) //$NON-NLS-1$
		castTo= ast.newPrimitiveType(PrimitiveType.BYTE);
	if (ast.resolveWellKnownType("short").isEqualTo(variableType)) //$NON-NLS-1$
		castTo= ast.newPrimitiveType(PrimitiveType.SHORT);
	if (castTo != null) {
		CastExpression cast= ast.newCastExpression();
		if (NecessaryParenthesesChecker.needsParentheses(expression, cast, CastExpression.EXPRESSION_PROPERTY)) {
			ParenthesizedExpression parenthesized= ast.newParenthesizedExpression();
			parenthesized.setExpression(expression);
			cast.setExpression(parenthesized);
		} else
			cast.setExpression(expression);
		cast.setType(castTo);
		return cast;
	}
	return expression;
}
 
Example #20
Source File: StringConcatenationGenerator.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private void addElement(Object element, SumExpressionBuilder builder) {
	if (element instanceof String) {
		builder.addString((String)element);
	}
	if (element instanceof Expression) {
		Expression expr= (Expression)element;
		if (expr instanceof ConditionalExpression) {
			ParenthesizedExpression expr2= fAst.newParenthesizedExpression();
			expr2.setExpression(expr);
			expr= expr2;
		}
		builder.addExpression(expr);
	}
}
 
Example #21
Source File: BaseTranslator.java    From junion with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public Expression trimWrap(Expression expr) {
	Expression e = expr;
	while(e instanceof ParenthesizedExpression) {
		e = ((ParenthesizedExpression)e).getExpression();
	}
	return e;
}
 
Example #22
Source File: NecessaryParenthesesChecker.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private static Expression getExpression(ParenthesizedExpression node) {
	Expression expression= node.getExpression();
	while (expression instanceof ParenthesizedExpression) {
		expression= ((ParenthesizedExpression)expression).getExpression();
	}
	return expression;
}
 
Example #23
Source File: CastCorrectionProposal.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private Type getNewCastTypeNode(ASTRewrite rewrite, ImportRewrite importRewrite) {
	AST ast= rewrite.getAST();

	ImportRewriteContext context= new ContextSensitiveImportRewriteContext((CompilationUnit) fNodeToCast.getRoot(), fNodeToCast.getStartPosition(), importRewrite);

	if (fCastType != null) {
		return importRewrite.addImport(fCastType, ast,context);
	}

	ASTNode node= fNodeToCast;
	ASTNode parent= node.getParent();
	if (parent instanceof CastExpression) {
		node= parent;
		parent= parent.getParent();
	}
	while (parent instanceof ParenthesizedExpression) {
		node= parent;
		parent= parent.getParent();
	}
	if (parent instanceof MethodInvocation) {
		MethodInvocation invocation= (MethodInvocation) node.getParent();
		if (invocation.getExpression() == node) {
			IBinding targetContext= ASTResolving.getParentMethodOrTypeBinding(node);
			ITypeBinding[] bindings= ASTResolving.getQualifierGuess(node.getRoot(), invocation.getName().getIdentifier(), invocation.arguments(), targetContext);
			if (bindings.length > 0) {
				ITypeBinding first= getCastFavorite(bindings, fNodeToCast.resolveTypeBinding());

				Type newTypeNode= importRewrite.addImport(first, ast, context);
				addLinkedPosition(rewrite.track(newTypeNode), true, "casttype"); //$NON-NLS-1$
				for (int i= 0; i < bindings.length; i++) {
					addLinkedPositionProposal("casttype", bindings[i]); //$NON-NLS-1$
				}
				return newTypeNode;
			}
		}
	}
	Type newCastType= ast.newSimpleType(ast.newSimpleName("Object")); //$NON-NLS-1$
	addLinkedPosition(rewrite.track(newCastType), true, "casttype"); //$NON-NLS-1$
	return newCastType;
}
 
Example #24
Source File: LocalCorrectionsSubProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
public static void addUnnecessaryInstanceofProposal(IInvocationContext context, IProblemLocation problem, Collection<ICommandAccess> proposals) {
	ASTNode selectedNode= problem.getCoveringNode(context.getASTRoot());

	ASTNode curr= selectedNode;
	while (curr instanceof ParenthesizedExpression) {
		curr= ((ParenthesizedExpression) curr).getExpression();
	}

	if (curr instanceof InstanceofExpression) {
		AST ast= curr.getAST();

		ASTRewrite rewrite= ASTRewrite.create(ast);

		InstanceofExpression inst= (InstanceofExpression) curr;

		InfixExpression expression= ast.newInfixExpression();
		expression.setLeftOperand((Expression) rewrite.createCopyTarget(inst.getLeftOperand()));
		expression.setOperator(InfixExpression.Operator.NOT_EQUALS);
		expression.setRightOperand(ast.newNullLiteral());

		rewrite.replace(inst, expression, null);

		String label= CorrectionMessages.LocalCorrectionsSubProcessor_unnecessaryinstanceof_description;
		Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE);
		ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal(label, context.getCompilationUnit(), rewrite, IProposalRelevance.UNNECESSARY_INSTANCEOF, image);
		proposals.add(proposal);
	}

}
 
Example #25
Source File: ASTNodes.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Returns whether an expression at the given location needs explicit boxing.
 * 
 * @param expression the expression
 * @return <code>true</code> iff an expression at the given location needs explicit boxing
 * @since 3.6
 */
private static boolean needsExplicitBoxing(Expression expression) {
	StructuralPropertyDescriptor locationInParent= expression.getLocationInParent();
	if (locationInParent == ParenthesizedExpression.EXPRESSION_PROPERTY)
		return needsExplicitBoxing((ParenthesizedExpression) expression.getParent());
	
	if (locationInParent == ClassInstanceCreation.EXPRESSION_PROPERTY
			|| locationInParent == FieldAccess.EXPRESSION_PROPERTY
			|| locationInParent == MethodInvocation.EXPRESSION_PROPERTY)
		return true;
	
	return false;
}
 
Example #26
Source File: StringConcatenationGenerator.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
@Override
protected void addMemberCheckNull(Object member, boolean addSeparator) {
	ConditionalExpression cExpression= fAst.newConditionalExpression();

	// member != null ?
	InfixExpression infExpression= fAst.newInfixExpression();
	infExpression.setLeftOperand(createMemberAccessExpression(member, true, true));
	infExpression.setRightOperand(fAst.newNullLiteral());
	infExpression.setOperator(Operator.NOT_EQUALS);
	cExpression.setExpression(infExpression);

	SumExpressionBuilder builder= new SumExpressionBuilder(null);
	String[] arrayString= getContext().getTemplateParser().getBody();
	for (int i= 0; i < arrayString.length; i++) {
		addElement(processElement(arrayString[i], member), builder);
	}
	if (addSeparator)
		addElement(getContext().getTemplateParser().getSeparator(), builder);
	cExpression.setThenExpression(builder.getExpression());

	StringLiteral literal= fAst.newStringLiteral();
	literal.setLiteralValue(getContext().isSkipNulls() ? "" : "null"); //$NON-NLS-1$ //$NON-NLS-2$
	cExpression.setElseExpression(literal);

	ParenthesizedExpression pExpression= fAst.newParenthesizedExpression();
	pExpression.setExpression(cExpression);
	toStringExpressionBuilder.addExpression(pExpression);
}
 
Example #27
Source File: AccessAnalyzer.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private Expression getReceiver(Expression expression) {
	int type= expression.getNodeType();
	switch(type) {
		case ASTNode.SIMPLE_NAME:
			return null;
		case ASTNode.QUALIFIED_NAME:
			return ((QualifiedName)expression).getQualifier();
		case ASTNode.FIELD_ACCESS:
			return ((FieldAccess)expression).getExpression();
		case ASTNode.PARENTHESIZED_EXPRESSION:
			return getReceiver(((ParenthesizedExpression)expression).getExpression());
	}
	return null;
}
 
Example #28
Source File: FullConstraintCreator.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public ITypeConstraint[] create(ParenthesizedExpression node) {
	ConstraintVariable v1= fConstraintVariableFactory.makeExpressionOrTypeVariable(node, getContext());
	ConstraintVariable v2= fConstraintVariableFactory.makeExpressionOrTypeVariable(node.getExpression(), getContext());
	ITypeConstraint[] equal= fTypeConstraintFactory.createEqualsConstraint(v1, v2);
	return equal;
}
 
Example #29
Source File: ExtractMethodRefactoring.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private void replaceDuplicates(CompilationUnitChange result, int modifiers) {
	int numberOf= getNumberOfDuplicates();
	if (numberOf == 0 || !fReplaceDuplicates)
		return;
	String label= null;
	if (numberOf == 1)
		label= Messages.format(RefactoringCoreMessages.ExtractMethodRefactoring_duplicates_single, BasicElementLabels.getJavaElementName(fMethodName));
	else
		label= Messages.format(RefactoringCoreMessages.ExtractMethodRefactoring_duplicates_multi, BasicElementLabels.getJavaElementName(fMethodName));

	TextEditGroup description= new TextEditGroup(label);
	result.addTextEditGroup(description);

	for (int d= 0; d < fDuplicates.length; d++) {
		SnippetFinder.Match duplicate= fDuplicates[d];
		if (!duplicate.isInvalidNode()) {
			if (isDestinationReachable(duplicate.getEnclosingMethod())) {
				ASTNode[] callNodes= createCallNodes(duplicate, modifiers);
				ASTNode[] duplicateNodes= duplicate.getNodes();
				for (int i= 0; i < duplicateNodes.length; i++) {
					ASTNode parent= duplicateNodes[i].getParent();
					if (parent instanceof ParenthesizedExpression) {
						duplicateNodes[i]= parent;
					}
				}
				new StatementRewrite(fRewriter, duplicateNodes).replace(callNodes, description);
			}
		}
	}
}
 
Example #30
Source File: IntroduceParameterRefactoring.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private void replaceSelectedExpression(CompilationUnitRewrite cuRewrite) {
	if (! fSourceCU.equals(cuRewrite.getCu()))
		return;
	// TODO: do for all methodDeclarations and replace matching fragments?

	// cannot use fSelectedExpression here, since it could be from another AST (if method was replaced by overridden):
	Expression expression= (Expression) NodeFinder.perform(cuRewrite.getRoot(), fSelectedExpression.getStartPosition(), fSelectedExpression.getLength());

	ASTNode newExpression= cuRewrite.getRoot().getAST().newSimpleName(fParameter.getNewName());
	String description= RefactoringCoreMessages.IntroduceParameterRefactoring_replace;
	cuRewrite.getASTRewrite().replace(expression.getParent() instanceof ParenthesizedExpression
			? expression.getParent() : expression, newExpression, cuRewrite.createGroupDescription(description));
}