use of org.eclipse.jdt.core.dom.ClassInstanceCreation in project flux by eclipse.
the class QuickAssistProcessor method getConvertToStringBufferProposal.
private static LinkedCorrectionProposal getConvertToStringBufferProposal(IInvocationContext context, AST ast, InfixExpression oldInfixExpression) {
String bufferOrBuilderName;
ICompilationUnit cu = context.getCompilationUnit();
if (JavaModelUtil.is50OrHigher(cu.getJavaProject())) {
//$NON-NLS-1$
bufferOrBuilderName = "StringBuilder";
} else {
//$NON-NLS-1$
bufferOrBuilderName = "StringBuffer";
}
ASTRewrite rewrite = ASTRewrite.create(ast);
SimpleName existingBuffer = getEnclosingAppendBuffer(oldInfixExpression);
String mechanismName = BasicElementLabels.getJavaElementName(existingBuffer == null ? bufferOrBuilderName : existingBuffer.getIdentifier());
String label = Messages.format(CorrectionMessages.QuickAssistProcessor_convert_to_string_buffer_description, mechanismName);
//Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE);
LinkedCorrectionProposal proposal = new LinkedCorrectionProposal(label, cu, rewrite, IProposalRelevance.CONVERT_TO_STRING_BUFFER);
proposal.setCommandId(CONVERT_TO_STRING_BUFFER_ID);
Statement insertAfter;
String bufferName;
//$NON-NLS-1$
String groupID = "nameId";
ListRewrite listRewrite;
Statement enclosingStatement = ASTResolving.findParentStatement(oldInfixExpression);
if (existingBuffer != null) {
if (ASTNodes.isControlStatementBody(enclosingStatement.getLocationInParent())) {
Block newBlock = ast.newBlock();
listRewrite = rewrite.getListRewrite(newBlock, Block.STATEMENTS_PROPERTY);
insertAfter = null;
rewrite.replace(enclosingStatement, newBlock, null);
} else {
listRewrite = rewrite.getListRewrite(enclosingStatement.getParent(), (ChildListPropertyDescriptor) enclosingStatement.getLocationInParent());
insertAfter = enclosingStatement;
}
bufferName = existingBuffer.getIdentifier();
} else {
// create buffer
VariableDeclarationFragment frag = ast.newVariableDeclarationFragment();
// check if name is already in use and provide alternative
List<String> fExcludedVariableNames = Arrays.asList(ASTResolving.getUsedVariableNames(oldInfixExpression));
SimpleType bufferType = ast.newSimpleType(ast.newName(bufferOrBuilderName));
ClassInstanceCreation newBufferExpression = ast.newClassInstanceCreation();
//StubUtility.getVariableNameSuggestions(NamingConventions.VK_LOCAL, cu.getJavaProject(), bufferOrBuilderName, 0, fExcludedVariableNames, true);
String[] newBufferNames = new String[] {};
bufferName = newBufferNames[0];
SimpleName bufferNameDeclaration = ast.newSimpleName(bufferName);
frag.setName(bufferNameDeclaration);
proposal.addLinkedPosition(rewrite.track(bufferNameDeclaration), true, groupID);
for (int i = 0; i < newBufferNames.length; i++) {
proposal.addLinkedPositionProposal(groupID, newBufferNames[i], null);
}
newBufferExpression.setType(bufferType);
frag.setInitializer(newBufferExpression);
VariableDeclarationStatement bufferDeclaration = ast.newVariableDeclarationStatement(frag);
bufferDeclaration.setType(ast.newSimpleType(ast.newName(bufferOrBuilderName)));
insertAfter = bufferDeclaration;
Statement statement = ASTResolving.findParentStatement(oldInfixExpression);
if (ASTNodes.isControlStatementBody(statement.getLocationInParent())) {
Block newBlock = ast.newBlock();
listRewrite = rewrite.getListRewrite(newBlock, Block.STATEMENTS_PROPERTY);
listRewrite.insertFirst(bufferDeclaration, null);
listRewrite.insertLast(rewrite.createMoveTarget(statement), null);
rewrite.replace(statement, newBlock, null);
} else {
listRewrite = rewrite.getListRewrite(statement.getParent(), (ChildListPropertyDescriptor) statement.getLocationInParent());
listRewrite.insertBefore(bufferDeclaration, statement, null);
}
}
List<Expression> operands = new ArrayList<Expression>();
collectInfixPlusOperands(oldInfixExpression, operands);
Statement lastAppend = insertAfter;
for (Iterator<Expression> iter = operands.iterator(); iter.hasNext(); ) {
Expression operand = iter.next();
MethodInvocation appendIncovationExpression = ast.newMethodInvocation();
//$NON-NLS-1$
appendIncovationExpression.setName(ast.newSimpleName("append"));
SimpleName bufferNameReference = ast.newSimpleName(bufferName);
// If there was an existing name, don't offer to rename it
if (existingBuffer == null) {
proposal.addLinkedPosition(rewrite.track(bufferNameReference), true, groupID);
}
appendIncovationExpression.setExpression(bufferNameReference);
appendIncovationExpression.arguments().add(rewrite.createCopyTarget(operand));
ExpressionStatement appendExpressionStatement = ast.newExpressionStatement(appendIncovationExpression);
if (lastAppend == null) {
listRewrite.insertFirst(appendExpressionStatement, null);
} else {
listRewrite.insertAfter(appendExpressionStatement, lastAppend, null);
}
lastAppend = appendExpressionStatement;
}
if (existingBuffer != null) {
proposal.setEndPosition(rewrite.track(lastAppend));
if (insertAfter != null) {
rewrite.remove(enclosingStatement, null);
}
} else {
// replace old expression with toString
MethodInvocation bufferToString = ast.newMethodInvocation();
//$NON-NLS-1$
bufferToString.setName(ast.newSimpleName("toString"));
SimpleName bufferNameReference = ast.newSimpleName(bufferName);
bufferToString.setExpression(bufferNameReference);
proposal.addLinkedPosition(rewrite.track(bufferNameReference), true, groupID);
rewrite.replace(oldInfixExpression, bufferToString, null);
proposal.setEndPosition(rewrite.track(bufferToString));
}
return proposal;
}
use of org.eclipse.jdt.core.dom.ClassInstanceCreation in project AutoRefactor by JnRouvignac.
the class PrimitiveWrapperCreationRefactoring method visit.
// TODO Can we reduce bad effects of autoboxing / unboxing
// fix autoboxing and unboxing (returning boxed value in primitive context)
@Override
public boolean visit(MethodInvocation node) {
if (node.getExpression() == null) {
return VISIT_SUBTREE;
}
final ASTNode parent = removeParentheses(node.getParent());
if (parent instanceof VariableDeclarationFragment) {
final ITypeBinding typeBinding = resolveTypeBinding((VariableDeclarationFragment) parent);
if (typeBinding.isPrimitive() && "valueOf".equals(node.getName().getIdentifier())) {
if (isMethod(node, "java.lang.Boolean", "valueOf", "boolean") || isMethod(node, "java.lang.Byte", "valueOf", "byte") || isMethod(node, "java.lang.Character", "valueOf", "char") || isMethod(node, "java.lang.Short", "valueOf", "short") || isMethod(node, "java.lang.Integer", "valueOf", "int") || isMethod(node, "java.lang.Long", "valueOf", "long") || isMethod(node, "java.lang.Float", "valueOf", "float") || isMethod(node, "java.lang.Double", "valueOf", "double")) {
return replaceWithTheSingleArgument(node);
}
if (is(node, "java.lang.Byte")) {
return replaceMethodName(node, "parseByte");
}
if (is(node, "java.lang.Short")) {
return replaceMethodName(node, "parseShort");
}
if (is(node, "java.lang.Integer")) {
return replaceMethodName(node, "parseInt");
}
if (is(node, "java.lang.Long")) {
return replaceMethodName(node, "parseLong");
}
if (isMethod(node, "java.lang.Boolean", "valueOf", "java.lang.String")) {
return replaceMethodName(node, "parseBoolean");
}
if (is(node, "java.lang.Float")) {
return replaceMethodName(node, "parseFloat");
}
if (is(node, "java.lang.Double")) {
return replaceMethodName(node, "parseDouble");
}
}
}
final ITypeBinding typeBinding = node.getExpression().resolveTypeBinding();
if (typeBinding != null && node.getExpression() instanceof ClassInstanceCreation) {
final List<Expression> cicArgs = arguments((ClassInstanceCreation) node.getExpression());
if (cicArgs.size() == 1) {
final Expression arg0 = cicArgs.get(0);
if (arguments(node).isEmpty() && hasType(arg0, "java.lang.String")) {
final String methodName = getMethodName(typeBinding.getQualifiedName(), node.getName().getIdentifier());
if (methodName != null) {
ctx.getRefactorings().replace(node, newMethodInvocation(typeBinding.getName(), methodName, arg0));
return DO_NOT_VISIT_SUBTREE;
}
}
}
}
return VISIT_SUBTREE;
}
use of org.eclipse.jdt.core.dom.ClassInstanceCreation in project che by eclipse.
the class IntroduceFactoryRefactoring method replaceConstructorCalls.
/**
* Use the given <code>ASTRewrite</code> to replace direct calls to the constructor
* with calls to the newly-created factory method.
* @param rg the <code>SearchResultGroup</code> indicating all of the constructor references
* @param unit the <code>CompilationUnit</code> to be rewritten
* @param unitRewriter the rewriter
* @param unitChange the compilation unit change
* @throws CoreException
* @return true iff at least one constructor call site was rewritten.
*/
private boolean replaceConstructorCalls(SearchResultGroup rg, CompilationUnit unit, ASTRewrite unitRewriter, CompilationUnitChange unitChange) throws CoreException {
Assert.isTrue(ASTCreator.getCu(unit).equals(rg.getCompilationUnit()));
SearchMatch[] hits = rg.getSearchResults();
Arrays.sort(hits, new Comparator<SearchMatch>() {
/**
* Sort by descending offset, such that nested constructor calls are processed first.
* This is necessary, since they can only be moved into the factory method invocation
* after they have been rewritten.
*/
public int compare(SearchMatch m1, SearchMatch m2) {
return m2.getOffset() - m1.getOffset();
}
});
boolean someCallPatched = false;
for (int i = 0; i < hits.length; i++) {
ASTNode ctrCall = getCtorCallAt(hits[i].getOffset(), hits[i].getLength(), unit);
if (ctrCall instanceof ClassInstanceCreation) {
TextEditGroup gd = new TextEditGroup(RefactoringCoreMessages.IntroduceFactory_replaceCalls);
rewriteFactoryMethodCall((ClassInstanceCreation) ctrCall, unitRewriter, gd);
unitChange.addTextEditGroup(gd);
someCallPatched = true;
} else if (ctrCall instanceof MethodRef) {
TextEditGroup gd = new TextEditGroup(RefactoringCoreMessages.IntroduceFactoryRefactoring_replaceJavadocReference);
rewriteJavadocReference((MethodRef) ctrCall, unitRewriter, gd);
unitChange.addTextEditGroup(gd);
someCallPatched = true;
}
}
return someCallPatched;
}
use of org.eclipse.jdt.core.dom.ClassInstanceCreation in project che by eclipse.
the class IntroduceFactoryRefactoring method createFactoryMethod.
/**
* Creates and returns a new MethodDeclaration that represents the factory method to be used in
* place of direct calls to the constructor in question.
*
* @param ast An AST used as a factory for various AST nodes
* @param ctorBinding binding for the constructor being wrapped
* @param unitRewriter the ASTRewrite to be used
* @return the new method declaration
* @throws CoreException if an exception occurs while accessing its corresponding resource
*/
private MethodDeclaration createFactoryMethod(AST ast, IMethodBinding ctorBinding, ASTRewrite unitRewriter) throws CoreException {
MethodDeclaration newMethod = ast.newMethodDeclaration();
SimpleName newMethodName = ast.newSimpleName(fNewMethodName);
ClassInstanceCreation newCtorCall = ast.newClassInstanceCreation();
ReturnStatement ret = ast.newReturnStatement();
Block body = ast.newBlock();
List<Statement> stmts = body.statements();
String retTypeName = ctorBinding.getName();
createFactoryMethodSignature(ast, newMethod);
newMethod.setName(newMethodName);
newMethod.setBody(body);
ITypeBinding declaringClass = fCtorBinding.getDeclaringClass();
ITypeBinding[] ctorOwnerTypeParameters = declaringClass.getTypeParameters();
setMethodReturnType(newMethod, retTypeName, ctorOwnerTypeParameters, ast);
newMethod.modifiers().addAll(ASTNodeFactory.newModifiers(ast, Modifier.STATIC | Modifier.PUBLIC));
setCtorTypeArguments(newCtorCall, retTypeName, ctorOwnerTypeParameters, ast);
createFactoryMethodConstructorArgs(ast, newCtorCall);
if (Modifier.isAbstract(declaringClass.getModifiers())) {
AnonymousClassDeclaration decl = ast.newAnonymousClassDeclaration();
IMethodBinding[] unimplementedMethods = getUnimplementedMethods(declaringClass);
CodeGenerationSettings settings = JavaPreferencesSettings.getCodeGenerationSettings(fCUHandle.getJavaProject());
ImportRewriteContext context = new ContextSensitiveImportRewriteContext(fFactoryCU, decl.getStartPosition(), fImportRewriter);
for (int i = 0; i < unimplementedMethods.length; i++) {
IMethodBinding unImplementedMethod = unimplementedMethods[i];
MethodDeclaration newMethodDecl = StubUtility2.createImplementationStub(fCUHandle, unitRewriter, fImportRewriter, context, unImplementedMethod, unImplementedMethod.getDeclaringClass().getName(), settings, false);
decl.bodyDeclarations().add(newMethodDecl);
}
newCtorCall.setAnonymousClassDeclaration(decl);
}
ret.setExpression(newCtorCall);
stmts.add(ret);
return newMethod;
}
use of org.eclipse.jdt.core.dom.ClassInstanceCreation in project che by eclipse.
the class UnresolvedElementsSubProcessor method getConstructorProposals.
public static void getConstructorProposals(IInvocationContext context, IProblemLocation problem, Collection<ICommandAccess> proposals) throws CoreException {
ICompilationUnit cu = context.getCompilationUnit();
CompilationUnit astRoot = context.getASTRoot();
ASTNode selectedNode = problem.getCoveringNode(astRoot);
if (selectedNode == null) {
return;
}
ITypeBinding targetBinding = null;
List<Expression> arguments = null;
IMethodBinding recursiveConstructor = null;
int type = selectedNode.getNodeType();
if (type == ASTNode.CLASS_INSTANCE_CREATION) {
ClassInstanceCreation creation = (ClassInstanceCreation) selectedNode;
IBinding binding = creation.getType().resolveBinding();
if (binding instanceof ITypeBinding) {
targetBinding = (ITypeBinding) binding;
arguments = creation.arguments();
}
} else if (type == ASTNode.SUPER_CONSTRUCTOR_INVOCATION) {
ITypeBinding typeBinding = Bindings.getBindingOfParentType(selectedNode);
if (typeBinding != null && !typeBinding.isAnonymous()) {
targetBinding = typeBinding.getSuperclass();
arguments = ((SuperConstructorInvocation) selectedNode).arguments();
}
} else if (type == ASTNode.CONSTRUCTOR_INVOCATION) {
ITypeBinding typeBinding = Bindings.getBindingOfParentType(selectedNode);
if (typeBinding != null && !typeBinding.isAnonymous()) {
targetBinding = typeBinding;
arguments = ((ConstructorInvocation) selectedNode).arguments();
recursiveConstructor = ASTResolving.findParentMethodDeclaration(selectedNode).resolveBinding();
}
}
if (targetBinding == null) {
return;
}
IMethodBinding[] methods = targetBinding.getDeclaredMethods();
ArrayList<IMethodBinding> similarElements = new ArrayList<IMethodBinding>();
for (int i = 0; i < methods.length; i++) {
IMethodBinding curr = methods[i];
if (curr.isConstructor() && recursiveConstructor != curr) {
// similar elements can contain a implicit default constructor
similarElements.add(curr);
}
}
addParameterMissmatchProposals(context, problem, similarElements, selectedNode, arguments, proposals);
if (targetBinding.isFromSource()) {
ITypeBinding targetDecl = targetBinding.getTypeDeclaration();
ICompilationUnit targetCU = ASTResolving.findCompilationUnitForBinding(cu, astRoot, targetDecl);
if (targetCU != null) {
String[] args = new String[] { ASTResolving.getMethodSignature(ASTResolving.getTypeSignature(targetDecl), getParameterTypes(arguments), false) };
String label = Messages.format(CorrectionMessages.UnresolvedElementsSubProcessor_createconstructor_description, args);
Image image = JavaElementImageProvider.getDecoratedImage(JavaPluginImages.DESC_MISC_PUBLIC, JavaElementImageDescriptor.CONSTRUCTOR, JavaElementImageProvider.SMALL_SIZE);
proposals.add(new NewMethodCorrectionProposal(label, targetCU, selectedNode, arguments, targetDecl, IProposalRelevance.CREATE_CONSTRUCTOR, image));
}
}
}
Aggregations