Java Code Examples for org.eclipse.jdt.core.dom.CastExpression#setType()

The following examples show how to use org.eclipse.jdt.core.dom.CastExpression#setType() . 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: BaseTranslator.java    From junion with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
public Expression methodB(String methodName, Type castType, Object... args) {
		MethodInvocation p = ast.newMethodInvocation();
		p.setExpression(name(MEM0_B));
//		p.setName(name(Translator.StringCache.getString(
//				type,
//				t,
//				opsymbol)));
		p.setName(name(methodName));

		for(Object arg : args)
			p.arguments().add(arg);
		
		if(castType != null) {
			CastExpression cast = ast.newCastExpression();			
			cast.setType(castType);
			cast.setExpression(p);
			cast.setProperty(TYPEBIND_PROP, FieldType.OBJECT);
			return cast;
		}
		return p;
	}
 
Example 2
Source File: GenerateHashCodeEqualsOperation.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
private Expression createShiftAssignment(Expression shift1, Expression shift2) {
	// (int)(element ^ (element >>> 32));
	// see implementation in Arrays.hashCode(), Double.hashCode() and
	// Long.hashCode()
	CastExpression ce= fAst.newCastExpression();
	ce.setType(fAst.newPrimitiveType(PrimitiveType.INT));

	InfixExpression unsignedShiftRight= fAst.newInfixExpression();
	unsignedShiftRight.setLeftOperand(shift1);
	unsignedShiftRight.setRightOperand(fAst.newNumberLiteral("32")); //$NON-NLS-1$
	unsignedShiftRight.setOperator(Operator.RIGHT_SHIFT_UNSIGNED);

	InfixExpression xor= fAst.newInfixExpression();
	xor.setLeftOperand(shift2);
	xor.setRightOperand(parenthesize(unsignedShiftRight));
	xor.setOperator(InfixExpression.Operator.XOR);

	ce.setExpression(parenthesize(xor));
	return ce;
}
 
Example 3
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 4
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 5
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 6
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 7
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 8
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 9
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);
}