Java Code Examples for org.eclipse.jdt.core.dom.AST#newCastExpression()

The following examples show how to use org.eclipse.jdt.core.dom.AST#newCastExpression() . 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: 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 2
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 3
Source File: LocalCorrectionsSubProcessor.java    From eclipse.jdt.ls with Eclipse Public License 2.0 4 votes vote down vote up
private static void addRemoveIncludingConditionProposal(IInvocationContext context, ASTNode toRemove, ASTNode replacement, Collection<ChangeCorrectionProposal> proposals) {
	String label = CorrectionMessages.LocalCorrectionsSubProcessor_removeunreachablecode_including_condition_description;
	AST ast = toRemove.getAST();
	ASTRewrite rewrite = ASTRewrite.create(ast);
	ASTRewriteCorrectionProposal proposal = new ASTRewriteCorrectionProposal(label, CodeActionKind.QuickFix, context.getCompilationUnit(), rewrite, IProposalRelevance.REMOVE_UNREACHABLE_CODE_INCLUDING_CONDITION);

	if (replacement == null || replacement instanceof EmptyStatement || replacement instanceof Block && ((Block) replacement).statements().size() == 0) {
		if (ASTNodes.isControlStatementBody(toRemove.getLocationInParent())) {
			rewrite.replace(toRemove, toRemove.getAST().newBlock(), null);
		} else {
			rewrite.remove(toRemove, null);
		}

	} else if (toRemove instanceof Expression && replacement instanceof Expression) {
		Expression moved = (Expression) rewrite.createMoveTarget(replacement);
		Expression toRemoveExpression = (Expression) toRemove;
		Expression replacementExpression = (Expression) replacement;
		ITypeBinding explicitCast = ASTNodes.getExplicitCast(replacementExpression, toRemoveExpression);
		if (explicitCast != null) {
			CastExpression cast = ast.newCastExpression();
			if (NecessaryParenthesesChecker.needsParentheses(replacementExpression, cast, CastExpression.EXPRESSION_PROPERTY)) {
				ParenthesizedExpression parenthesized = ast.newParenthesizedExpression();
				parenthesized.setExpression(moved);
				moved = parenthesized;
			}
			cast.setExpression(moved);
			ImportRewrite imports = proposal.createImportRewrite(context.getASTRoot());
			ImportRewriteContext importRewriteContext = new ContextSensitiveImportRewriteContext(toRemove, imports);
			cast.setType(imports.addImport(explicitCast, ast, importRewriteContext, TypeLocation.CAST));
			moved = cast;
		}
		rewrite.replace(toRemove, moved, null);

	} else {
		ASTNode parent = toRemove.getParent();
		ASTNode moveTarget;
		if ((parent instanceof Block || parent instanceof SwitchStatement) && replacement instanceof Block) {
			ListRewrite listRewrite = rewrite.getListRewrite(replacement, Block.STATEMENTS_PROPERTY);
			List<Statement> list = ((Block) replacement).statements();
			int lastIndex = list.size() - 1;
			moveTarget = listRewrite.createMoveTarget(list.get(0), list.get(lastIndex));
		} else {
			moveTarget = rewrite.createMoveTarget(replacement);
		}

		rewrite.replace(toRemove, moveTarget, null);
	}

	proposals.add(proposal);
}
 
Example 4
Source File: UnresolvedElementsSubProcessor.java    From eclipse.jdt.ls with Eclipse Public License 2.0 4 votes vote down vote up
private static boolean useExistingParentCastProposal(ICompilationUnit cu, CastExpression expression,
		Expression accessExpression, SimpleName accessSelector, ITypeBinding[] paramTypes,
		Collection<ChangeCorrectionProposal> 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;
		ASTRewriteCorrectionProposal proposal = new ASTRewriteCorrectionProposal(label, CodeActionKind.QuickFix, cu, rewrite,
				IProposalRelevance.ADD_PARENTHESES_AROUND_CAST);
		proposals.add(proposal);
		return true;
	}
	return false;
}
 
Example 5
Source File: SourceProvider.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
private void replaceParameterWithExpression(ASTRewrite rewriter, CallContext context, ImportRewrite importRewrite) throws CoreException {
	Expression[] arguments= context.arguments;
	try {
		ITextFileBuffer buffer= RefactoringFileBuffers.acquire(context.compilationUnit);
		for (int i= 0; i < arguments.length; i++) {
			Expression expression= arguments[i];
			String expressionString= null;
			if (expression instanceof SimpleName) {
				expressionString= ((SimpleName)expression).getIdentifier();
			} else {
				try {
					expressionString= buffer.getDocument().get(expression.getStartPosition(), expression.getLength());
				} catch (BadLocationException exception) {
					JavaPlugin.log(exception);
					continue;
				}
			}
			ParameterData parameter= getParameterData(i);
			List<SimpleName> references= parameter.references();
			for (Iterator<SimpleName> iter= references.iterator(); iter.hasNext();) {
				ASTNode element= iter.next();
				Expression newExpression= (Expression)rewriter.createStringPlaceholder(expressionString, expression.getNodeType());
				AST ast= rewriter.getAST();
				ITypeBinding explicitCast= ASTNodes.getExplicitCast(expression, (Expression)element);
				if (explicitCast != null) {
					CastExpression cast= ast.newCastExpression();
					if (NecessaryParenthesesChecker.needsParentheses(expression, cast, CastExpression.EXPRESSION_PROPERTY)) {
						newExpression= createParenthesizedExpression(newExpression, ast);
					}
					cast.setExpression(newExpression);
					ImportRewriteContext importRewriteContext= new ContextSensitiveImportRewriteContext(expression, importRewrite);
					cast.setType(importRewrite.addImport(explicitCast, ast, importRewriteContext));
					expression= newExpression= cast;
				}
				if (NecessaryParenthesesChecker.needsParentheses(expression, element.getParent(), element.getLocationInParent())) {
					newExpression= createParenthesizedExpression(newExpression, ast);
				}
				rewriter.replace(element, newExpression, null);
			}
		}
	} finally {
		RefactoringFileBuffers.release(context.compilationUnit);
	}
}
 
Example 6
Source File: LambdaExpressionsFix.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
/**
		 * {@inheritDoc}
		 */
		@Override
		public void rewriteAST(CompilationUnitRewrite cuRewrite, LinkedProposalModel model) throws CoreException {

			ASTRewrite rewrite= cuRewrite.getASTRewrite();
			ImportRemover importRemover= cuRewrite.getImportRemover();
			AST ast= rewrite.getAST();

			HashMap<ClassInstanceCreation, HashSet<String>> cicToNewNames= new HashMap<ClassInstanceCreation, HashSet<String>>();
			for (int i= 0; i < fExpressions.size(); i++) {
				ClassInstanceCreation classInstanceCreation= fExpressions.get(i);
				TextEditGroup group= createTextEditGroup(FixMessages.LambdaExpressionsFix_convert_to_lambda_expression, cuRewrite);

				AnonymousClassDeclaration anonymTypeDecl= classInstanceCreation.getAnonymousClassDeclaration();
				List<BodyDeclaration> bodyDeclarations= anonymTypeDecl.bodyDeclarations();

				Object object= bodyDeclarations.get(0);
				if (!(object instanceof MethodDeclaration))
					continue;
				MethodDeclaration methodDeclaration= (MethodDeclaration) object;
				HashSet<String> excludedNames= new HashSet<String>();
				if (i != 0) {
					for (ClassInstanceCreation convertedCic : fExpressions.subList(0, i)) {
						if (ASTNodes.isParent(classInstanceCreation, convertedCic)) {
							excludedNames.addAll(cicToNewNames.get(convertedCic));
						}
					}
				}
				HashSet<String> newNames= makeNamesUnique(excludedNames, methodDeclaration, rewrite, group);
				cicToNewNames.put(classInstanceCreation, new HashSet<String>(newNames));
				List<SingleVariableDeclaration> methodParameters= methodDeclaration.parameters();

				// use short form with inferred parameter types and without parentheses if possible
				LambdaExpression lambdaExpression= ast.newLambdaExpression();
				List<VariableDeclaration> lambdaParameters= lambdaExpression.parameters();
				lambdaExpression.setParentheses(methodParameters.size() != 1);
				for (SingleVariableDeclaration methodParameter : methodParameters) {
					VariableDeclarationFragment lambdaParameter= ast.newVariableDeclarationFragment();
					lambdaParameter.setName((SimpleName) rewrite.createCopyTarget(methodParameter.getName()));
					lambdaParameters.add(lambdaParameter);
				}
				
				Block body= methodDeclaration.getBody();
				List<Statement> statements= body.statements();
				ASTNode lambdaBody= body;
				if (statements.size() == 1) {
					// use short form with just an expression body if possible
					Statement statement= statements.get(0);
					if (statement instanceof ExpressionStatement) {
						lambdaBody= ((ExpressionStatement) statement).getExpression();
					} else if (statement instanceof ReturnStatement) {
						Expression returnExpression= ((ReturnStatement) statement).getExpression();
						if (returnExpression != null) {
							lambdaBody= returnExpression;
						}
					}
				}
				//TODO: Bug 421479: [1.8][clean up][quick assist] convert anonymous to lambda must consider lost scope of interface
//				lambdaBody.accept(new InterfaceAccessQualifier(rewrite, classInstanceCreation.getType().resolveBinding())); //TODO: maybe need a separate ASTRewrite and string placeholder
				
				lambdaExpression.setBody(rewrite.createCopyTarget(lambdaBody));
				Expression replacement= lambdaExpression;
				if (ASTNodes.isTargetAmbiguous(classInstanceCreation, lambdaParameters.isEmpty())) {
					CastExpression cast= ast.newCastExpression();
					cast.setExpression(lambdaExpression);
					ImportRewrite importRewrite= cuRewrite.getImportRewrite();
					ImportRewriteContext importRewriteContext= new ContextSensitiveImportRewriteContext(classInstanceCreation, importRewrite);
					Type castType= importRewrite.addImport(classInstanceCreation.getType().resolveBinding(), ast, importRewriteContext);
					cast.setType(castType);
					importRemover.registerAddedImports(castType);
					replacement= cast;
				}
				rewrite.replace(classInstanceCreation, replacement, group);

				importRemover.registerRemovedNode(classInstanceCreation);
				importRemover.registerRetainedNode(lambdaBody);
			}
		}
 
Example 7
Source File: LocalCorrectionsSubProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
private static void addRemoveIncludingConditionProposal(IInvocationContext context, ASTNode toRemove, ASTNode replacement, Collection<ICommandAccess> proposals) {
	Image image= JavaPlugin.getDefault().getWorkbench().getSharedImages().getImage(ISharedImages.IMG_TOOL_DELETE);
	String label= CorrectionMessages.LocalCorrectionsSubProcessor_removeunreachablecode_including_condition_description;
	AST ast= toRemove.getAST();
	ASTRewrite rewrite= ASTRewrite.create(ast);
	ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal(label, context.getCompilationUnit(), rewrite, IProposalRelevance.REMOVE_UNREACHABLE_CODE_INCLUDING_CONDITION, image);
	
	if (replacement == null
			|| replacement instanceof EmptyStatement
			|| replacement instanceof Block && ((Block)replacement).statements().size() == 0) {
		if (ASTNodes.isControlStatementBody(toRemove.getLocationInParent())) {
			rewrite.replace(toRemove, toRemove.getAST().newBlock(), null);
		} else {
			rewrite.remove(toRemove, null);
		}
		
	} else if (toRemove instanceof Expression && replacement instanceof Expression) {
		Expression moved= (Expression) rewrite.createMoveTarget(replacement);
		Expression toRemoveExpression= (Expression) toRemove;
		Expression replacementExpression= (Expression) replacement;
		ITypeBinding explicitCast= ASTNodes.getExplicitCast(replacementExpression, toRemoveExpression);
		if (explicitCast != null) {
			CastExpression cast= ast.newCastExpression();
			if (NecessaryParenthesesChecker.needsParentheses(replacementExpression, cast, CastExpression.EXPRESSION_PROPERTY)) {
				ParenthesizedExpression parenthesized= ast.newParenthesizedExpression();
				parenthesized.setExpression(moved);
				moved= parenthesized;
			}
			cast.setExpression(moved);
			ImportRewrite imports= proposal.createImportRewrite(context.getASTRoot());
			ImportRewriteContext importRewriteContext= new ContextSensitiveImportRewriteContext(toRemove, imports);
			cast.setType(imports.addImport(explicitCast, ast, importRewriteContext));
			moved= cast;
		}
		rewrite.replace(toRemove, moved, null);
		
	} else {
		ASTNode parent= toRemove.getParent();
		ASTNode moveTarget;
		if ((parent instanceof Block || parent instanceof SwitchStatement) && replacement instanceof Block) {
			ListRewrite listRewrite= rewrite.getListRewrite(replacement, Block.STATEMENTS_PROPERTY);
			List<Statement> list= ((Block)replacement).statements();
			int lastIndex= list.size() - 1;
			moveTarget= listRewrite.createMoveTarget(list.get(0), list.get(lastIndex));
		} else {
			moveTarget= rewrite.createMoveTarget(replacement);
		}

		rewrite.replace(toRemove, moveTarget, null);
	}
	
	proposals.add(proposal);
}