use of org.eclipse.jdt.core.dom.Initializer in project eclipse.jdt.ls by eclipse.
the class NewVariableCorrectionProposal method doAddLocal.
private ASTRewrite doAddLocal(CompilationUnit cu) {
AST ast = cu.getAST();
Block body;
BodyDeclaration decl = ASTResolving.findParentBodyDeclaration(fOriginalNode);
IBinding targetContext = null;
if (decl instanceof MethodDeclaration) {
body = (((MethodDeclaration) decl).getBody());
targetContext = ((MethodDeclaration) decl).resolveBinding();
} else if (decl instanceof Initializer) {
body = (((Initializer) decl).getBody());
targetContext = Bindings.getBindingOfParentType(decl);
} else {
return null;
}
ASTRewrite rewrite = ASTRewrite.create(ast);
ImportRewrite imports = createImportRewrite((CompilationUnit) decl.getRoot());
SimpleName[] names = getAllReferences(body);
ASTNode dominant = getDominantNode(names);
Statement dominantStatement = ASTResolving.findParentStatement(dominant);
if (ASTNodes.isControlStatementBody(dominantStatement.getLocationInParent())) {
dominantStatement = (Statement) dominantStatement.getParent();
}
SimpleName node = names[0];
ImportRewriteContext importRewriteContext = new ContextSensitiveImportRewriteContext(node, imports);
if (isAssigned(dominantStatement, node)) {
// x = 1; -> int x = 1;
Assignment assignment = (Assignment) node.getParent();
// trick to avoid comment removal around the statement: keep the expression statement
// and replace the assignment with an VariableDeclarationExpression
VariableDeclarationFragment newDeclFrag = ast.newVariableDeclarationFragment();
VariableDeclarationExpression newDecl = ast.newVariableDeclarationExpression(newDeclFrag);
newDecl.setType(evaluateVariableType(ast, imports, importRewriteContext, targetContext, TypeLocation.LOCAL_VARIABLE));
Expression placeholder = (Expression) rewrite.createCopyTarget(assignment.getRightHandSide());
newDeclFrag.setInitializer(placeholder);
newDeclFrag.setName(ast.newSimpleName(node.getIdentifier()));
rewrite.replace(assignment, newDecl, null);
return rewrite;
} else if ((dominant != dominantStatement) && isForStatementInit(dominantStatement, node)) {
// for (x = 1;;) ->for (int x = 1;;)
Assignment assignment = (Assignment) node.getParent();
VariableDeclarationFragment frag = ast.newVariableDeclarationFragment();
VariableDeclarationExpression expression = ast.newVariableDeclarationExpression(frag);
frag.setName(ast.newSimpleName(node.getIdentifier()));
Expression placeholder = (Expression) rewrite.createCopyTarget(assignment.getRightHandSide());
frag.setInitializer(placeholder);
expression.setType(evaluateVariableType(ast, imports, importRewriteContext, targetContext, TypeLocation.LOCAL_VARIABLE));
rewrite.replace(assignment, expression, null);
return rewrite;
} else if ((dominant != dominantStatement) && isEnhancedForStatementVariable(dominantStatement, node)) {
// for (x: collectionOfT) -> for (T x: collectionOfT)
EnhancedForStatement enhancedForStatement = (EnhancedForStatement) dominantStatement;
SingleVariableDeclaration parameter = enhancedForStatement.getParameter();
Expression expression = enhancedForStatement.getExpression();
SimpleName newName = (SimpleName) rewrite.createMoveTarget(node);
rewrite.set(parameter, SingleVariableDeclaration.NAME_PROPERTY, newName, null);
ITypeBinding elementBinding = null;
ITypeBinding typeBinding = expression.resolveTypeBinding();
if (typeBinding != null) {
if (typeBinding.isArray()) {
elementBinding = typeBinding.getElementType();
} else {
// $NON-NLS-1$
ITypeBinding iterable = Bindings.findTypeInHierarchy(typeBinding, "java.lang.Iterable");
if (iterable != null) {
ITypeBinding[] typeArguments = iterable.getTypeArguments();
if (typeArguments.length == 1) {
elementBinding = typeArguments[0];
elementBinding = Bindings.normalizeForDeclarationUse(elementBinding, ast);
}
}
}
}
Type type;
if (elementBinding != null) {
type = imports.addImport(elementBinding, ast, importRewriteContext, TypeLocation.LOCAL_VARIABLE);
} else {
// $NON-NLS-1$
type = ast.newSimpleType(ast.newSimpleName("Object"));
}
rewrite.set(parameter, SingleVariableDeclaration.TYPE_PROPERTY, type, null);
return rewrite;
}
// foo(x) -> int x; foo(x)
VariableDeclarationFragment newDeclFrag = ast.newVariableDeclarationFragment();
VariableDeclarationStatement newDecl = ast.newVariableDeclarationStatement(newDeclFrag);
newDeclFrag.setName(ast.newSimpleName(node.getIdentifier()));
newDecl.setType(evaluateVariableType(ast, imports, importRewriteContext, targetContext, TypeLocation.LOCAL_VARIABLE));
// newDeclFrag.setInitializer(ASTNodeFactory.newDefaultExpression(ast, newDecl.getType(), 0));
Statement statement = dominantStatement;
List<? extends ASTNode> list = ASTNodes.getContainingList(statement);
while (list == null && statement.getParent() instanceof Statement) {
// parent must be if, for or while
statement = (Statement) statement.getParent();
list = ASTNodes.getContainingList(statement);
}
if (list != null) {
ASTNode parent = statement.getParent();
StructuralPropertyDescriptor childProperty = statement.getLocationInParent();
if (childProperty.isChildListProperty()) {
rewrite.getListRewrite(parent, (ChildListPropertyDescriptor) childProperty).insertBefore(newDecl, statement, null);
return rewrite;
} else {
return null;
}
}
return rewrite;
}
use of org.eclipse.jdt.core.dom.Initializer in project eclipse.jdt.ls by eclipse.
the class AssignToVariableAssistProposal method doAddField.
private ASTRewrite doAddField(ASTRewrite rewrite, ASTNode nodeToAssign, ITypeBinding typeBinding, int index) {
boolean isParamToField = nodeToAssign.getNodeType() == ASTNode.SINGLE_VARIABLE_DECLARATION;
ASTNode newTypeDecl = ASTResolving.findParentType(nodeToAssign);
if (newTypeDecl == null) {
return null;
}
Expression expression = isParamToField ? ((SingleVariableDeclaration) nodeToAssign).getName() : ((ExpressionStatement) nodeToAssign).getExpression();
AST ast = newTypeDecl.getAST();
createImportRewrite((CompilationUnit) nodeToAssign.getRoot());
BodyDeclaration bodyDecl = ASTResolving.findParentBodyDeclaration(nodeToAssign);
Block body;
if (bodyDecl instanceof MethodDeclaration) {
body = ((MethodDeclaration) bodyDecl).getBody();
} else if (bodyDecl instanceof Initializer) {
body = ((Initializer) bodyDecl).getBody();
} else {
return null;
}
IJavaProject project = getCompilationUnit().getJavaProject();
boolean isAnonymous = newTypeDecl.getNodeType() == ASTNode.ANONYMOUS_CLASS_DECLARATION;
boolean isStatic = Modifier.isStatic(bodyDecl.getModifiers()) && !isAnonymous;
int modifiers = Modifier.PRIVATE;
if (isStatic) {
modifiers |= Modifier.STATIC;
}
VariableDeclarationFragment newDeclFrag = addFieldDeclaration(rewrite, newTypeDecl, modifiers, expression, nodeToAssign, typeBinding, index);
String varName = newDeclFrag.getName().getIdentifier();
Assignment assignment = ast.newAssignment();
assignment.setRightHandSide((Expression) rewrite.createCopyTarget(expression));
boolean needsThis = StubUtility.useThisForFieldAccess(project);
if (isParamToField) {
needsThis |= varName.equals(((SimpleName) expression).getIdentifier());
}
SimpleName accessName = ast.newSimpleName(varName);
if (needsThis) {
FieldAccess fieldAccess = ast.newFieldAccess();
fieldAccess.setName(accessName);
if (isStatic) {
String typeName = ((AbstractTypeDeclaration) newTypeDecl).getName().getIdentifier();
fieldAccess.setExpression(ast.newSimpleName(typeName));
} else {
fieldAccess.setExpression(ast.newThisExpression());
}
assignment.setLeftHandSide(fieldAccess);
} else {
assignment.setLeftHandSide(accessName);
}
ASTNode selectionNode;
if (isParamToField) {
// assign parameter to field
ExpressionStatement statement = ast.newExpressionStatement(assignment);
int insertIdx = findAssignmentInsertIndex(body.statements(), nodeToAssign) + index;
rewrite.getListRewrite(body, Block.STATEMENTS_PROPERTY).insertAt(statement, insertIdx, null);
selectionNode = statement;
} else {
if (needsSemicolon(expression)) {
rewrite.replace(expression, ast.newExpressionStatement(assignment), null);
} else {
rewrite.replace(expression, assignment, null);
}
selectionNode = nodeToAssign;
}
addLinkedPosition(rewrite.track(newDeclFrag.getName()), false, KEY_NAME + index);
if (!isParamToField) {
FieldDeclaration fieldDeclaration = (FieldDeclaration) newDeclFrag.getParent();
addLinkedPosition(rewrite.track(fieldDeclaration.getType()), false, KEY_TYPE);
}
addLinkedPosition(rewrite.track(accessName), true, KEY_NAME + index);
IVariableBinding variableBinding = newDeclFrag.resolveBinding();
if (variableBinding != null) {
SimpleName[] linkedNodes = LinkedNodeFinder.findByBinding(nodeToAssign.getRoot(), variableBinding);
for (int i = 0; i < linkedNodes.length; i++) {
addLinkedPosition(rewrite.track(linkedNodes[i]), false, KEY_NAME + index);
}
}
setEndPosition(rewrite.track(selectionNode));
return rewrite;
}
use of org.eclipse.jdt.core.dom.Initializer in project eclipse.jdt.ls by eclipse.
the class QuickAssistProcessor method getCatchClauseToThrowsProposals.
public static boolean getCatchClauseToThrowsProposals(IInvocationContext context, ASTNode node, Collection<ChangeCorrectionProposal> resultingCollections) {
if (resultingCollections == null) {
return true;
}
CatchClause catchClause = (CatchClause) ASTResolving.findAncestor(node, ASTNode.CATCH_CLAUSE);
if (catchClause == null) {
return false;
}
Statement statement = ASTResolving.findParentStatement(node);
if (statement != catchClause.getParent() && statement != catchClause.getBody()) {
// selection is in a statement inside the body
return false;
}
Type type = catchClause.getException().getType();
if (!type.isSimpleType() && !type.isUnionType() && !type.isNameQualifiedType()) {
return false;
}
BodyDeclaration bodyDeclaration = ASTResolving.findParentBodyDeclaration(catchClause);
if (!(bodyDeclaration instanceof MethodDeclaration) && !(bodyDeclaration instanceof Initializer)) {
return false;
}
AST ast = bodyDeclaration.getAST();
Type selectedMultiCatchType = null;
if (type.isUnionType() && node instanceof Name) {
Name topMostName = ASTNodes.getTopMostName((Name) node);
ASTNode parent = topMostName.getParent();
if (parent instanceof SimpleType) {
selectedMultiCatchType = (SimpleType) parent;
} else if (parent instanceof NameQualifiedType) {
selectedMultiCatchType = (NameQualifiedType) parent;
}
}
if (bodyDeclaration instanceof MethodDeclaration) {
MethodDeclaration methodDeclaration = (MethodDeclaration) bodyDeclaration;
ASTRewrite rewrite = ASTRewrite.create(ast);
if (selectedMultiCatchType != null) {
removeException(rewrite, (UnionType) type, selectedMultiCatchType);
addExceptionToThrows(ast, methodDeclaration, rewrite, selectedMultiCatchType);
String label = CorrectionMessages.QuickAssistProcessor_exceptiontothrows_description;
ASTRewriteCorrectionProposal proposal = new ASTRewriteCorrectionProposal(label, CodeActionKind.QuickFix, context.getCompilationUnit(), rewrite, IProposalRelevance.REPLACE_EXCEPTION_WITH_THROWS);
resultingCollections.add(proposal);
} else {
removeCatchBlock(rewrite, catchClause);
if (type.isUnionType()) {
UnionType unionType = (UnionType) type;
List<Type> types = unionType.types();
for (Type elementType : types) {
if (!(elementType instanceof SimpleType || elementType instanceof NameQualifiedType)) {
return false;
}
addExceptionToThrows(ast, methodDeclaration, rewrite, elementType);
}
} else {
addExceptionToThrows(ast, methodDeclaration, rewrite, type);
}
String label = CorrectionMessages.QuickAssistProcessor_catchclausetothrows_description;
ASTRewriteCorrectionProposal proposal = new ASTRewriteCorrectionProposal(label, CodeActionKind.QuickFix, context.getCompilationUnit(), rewrite, IProposalRelevance.REPLACE_CATCH_CLAUSE_WITH_THROWS);
resultingCollections.add(proposal);
}
}
{
// for initializers or method declarations
ASTRewrite rewrite = ASTRewrite.create(ast);
if (selectedMultiCatchType != null) {
removeException(rewrite, (UnionType) type, selectedMultiCatchType);
String label = CorrectionMessages.QuickAssistProcessor_removeexception_description;
ASTRewriteCorrectionProposal proposal = new ASTRewriteCorrectionProposal(label, CodeActionKind.QuickFix, context.getCompilationUnit(), rewrite, IProposalRelevance.REMOVE_EXCEPTION);
resultingCollections.add(proposal);
} else {
removeCatchBlock(rewrite, catchClause);
String label = CorrectionMessages.QuickAssistProcessor_removecatchclause_description;
ASTRewriteCorrectionProposal proposal = new ASTRewriteCorrectionProposal(label, CodeActionKind.QuickFix, context.getCompilationUnit(), rewrite, IProposalRelevance.REMOVE_CATCH_CLAUSE);
resultingCollections.add(proposal);
}
}
return true;
}
Aggregations