use of org.eclipse.jdt.core.dom.ChildListPropertyDescriptor in project AutoRefactor by JnRouvignac.
the class Refactorings method getListRewrite.
private ListRewrite getListRewrite(ASTNode node, ChildListPropertyDescriptor listProperty) {
final Pair<ASTNode, ChildListPropertyDescriptor> key = Pair.of(node, listProperty);
ListRewrite listRewrite = listRewriteCache.get(key);
if (listRewrite == null) {
listRewrite = rewrite.getListRewrite(node, listProperty);
listRewriteCache.put(key, listRewrite);
}
return listRewrite;
}
use of org.eclipse.jdt.core.dom.ChildListPropertyDescriptor 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.ChildListPropertyDescriptor in project eclipse.jdt.ls by eclipse.
the class NewVariableCorrectionProposal method doAddField.
private ASTRewrite doAddField(CompilationUnit astRoot) {
SimpleName node = fOriginalNode;
boolean isInDifferentCU = false;
ASTNode newTypeDecl = astRoot.findDeclaringNode(fSenderBinding);
if (newTypeDecl == null) {
astRoot = ASTResolving.createQuickFixAST(getCompilationUnit(), null);
newTypeDecl = astRoot.findDeclaringNode(fSenderBinding.getKey());
isInDifferentCU = true;
}
ImportRewrite imports = createImportRewrite(astRoot);
ImportRewriteContext importRewriteContext = new ContextSensitiveImportRewriteContext(ASTResolving.findParentBodyDeclaration(node), imports);
if (newTypeDecl != null) {
AST ast = newTypeDecl.getAST();
ASTRewrite rewrite = ASTRewrite.create(ast);
VariableDeclarationFragment fragment = ast.newVariableDeclarationFragment();
fragment.setName(ast.newSimpleName(node.getIdentifier()));
Type type = evaluateVariableType(ast, imports, importRewriteContext, fSenderBinding, TypeLocation.FIELD);
FieldDeclaration newDecl = ast.newFieldDeclaration(fragment);
newDecl.setType(type);
newDecl.modifiers().addAll(ASTNodeFactory.newModifiers(ast, evaluateFieldModifiers(newTypeDecl)));
if (fSenderBinding.isInterface() || fVariableKind == CONST_FIELD) {
fragment.setInitializer(ASTNodeFactory.newDefaultExpression(ast, type, 0));
}
ChildListPropertyDescriptor property = ASTNodes.getBodyDeclarationsProperty(newTypeDecl);
List<BodyDeclaration> decls = ASTNodes.<BodyDeclaration>getChildListProperty(newTypeDecl, property);
int maxOffset = isInDifferentCU ? -1 : node.getStartPosition();
int insertIndex = findFieldInsertIndex(decls, newDecl, maxOffset);
ListRewrite listRewriter = rewrite.getListRewrite(newTypeDecl, property);
listRewriter.insertAt(newDecl, insertIndex, null);
return rewrite;
}
return null;
}
use of org.eclipse.jdt.core.dom.ChildListPropertyDescriptor in project eclipse.jdt.ls by eclipse.
the class OverrideCompletionProposal method updateReplacementString.
/*
* @see JavaTypeCompletionProposal#updateReplacementString(IDocument,char,int,ImportRewrite)
*/
public String updateReplacementString(IDocument document, int offset, ImportRewrite importRewrite, boolean snippetStringSupport) throws CoreException, BadLocationException {
Document recoveredDocument = new Document();
CompilationUnit unit = getRecoveredAST(document, offset, recoveredDocument);
ImportRewriteContext context = new ContextSensitiveImportRewriteContext(unit, offset, importRewrite);
ITypeBinding declaringType = null;
ChildListPropertyDescriptor descriptor = null;
ASTNode node = NodeFinder.perform(unit, offset, 1);
node = ASTResolving.findParentType(node);
String result = null;
if (node instanceof AnonymousClassDeclaration) {
declaringType = ((AnonymousClassDeclaration) node).resolveBinding();
descriptor = AnonymousClassDeclaration.BODY_DECLARATIONS_PROPERTY;
} else if (node instanceof AbstractTypeDeclaration) {
AbstractTypeDeclaration declaration = (AbstractTypeDeclaration) node;
descriptor = declaration.getBodyDeclarationsProperty();
declaringType = declaration.resolveBinding();
}
if (declaringType != null) {
ASTRewrite rewrite = ASTRewrite.create(unit.getAST());
IMethodBinding methodToOverride = Bindings.findMethodInHierarchy(declaringType, fMethodName, fParamTypes);
if (methodToOverride == null && declaringType.isInterface()) {
// $NON-NLS-1$
methodToOverride = Bindings.findMethodInType(node.getAST().resolveWellKnownType("java.lang.Object"), fMethodName, fParamTypes);
}
if (methodToOverride != null) {
CodeGenerationSettings settings = PreferenceManager.getCodeGenerationSettings(fJavaProject.getProject());
MethodDeclaration stub = StubUtility2.createImplementationStub(fCompilationUnit, rewrite, importRewrite, context, methodToOverride, declaringType, settings, declaringType.isInterface(), declaringType, snippetStringSupport);
ListRewrite rewriter = rewrite.getListRewrite(node, descriptor);
rewriter.insertFirst(stub, null);
ITrackedNodePosition position = rewrite.track(stub);
try {
Map<String, String> options = fJavaProject.getOptions(true);
rewrite.rewriteAST(recoveredDocument, options).apply(recoveredDocument);
String generatedCode = recoveredDocument.get(position.getStartPosition(), position.getLength());
String indentAt = getIndentAt(recoveredDocument, position.getStartPosition(), settings);
int generatedIndent = IndentManipulation.measureIndentUnits(indentAt, settings.tabWidth, settings.indentWidth);
// Kinda fishy but empirical data shows Override needs to change indent by at
// least 1
generatedIndent = Math.max(1, generatedIndent);
// Cancel generated code indent
String delimiter = TextUtilities.getDefaultLineDelimiter(document);
result = IndentManipulation.changeIndent(generatedCode, generatedIndent, settings.tabWidth, settings.indentWidth, "", delimiter);
} catch (MalformedTreeException | BadLocationException exception) {
JavaLanguageServerPlugin.logException("Unable to compute override proposal", exception);
}
}
}
return result;
}
use of org.eclipse.jdt.core.dom.ChildListPropertyDescriptor in project AutoRefactor by JnRouvignac.
the class ASTRewrite method getListRewrite.
/**
* Get the list rewrite.
*
* @param node The node
* @param listProperty The list property
* @return the list rewrite.
*/
public ListRewrite getListRewrite(final ASTNode node, final ChildListPropertyDescriptor listProperty) {
Pair<ASTNode, ChildListPropertyDescriptor> key = Pair.of(node, listProperty);
ListRewrite listRewrite = listRewriteCache.get(key);
if (listRewrite == null) {
listRewrite = rewrite.getListRewrite(node, listProperty);
listRewriteCache.put(key, listRewrite);
}
return listRewrite;
}
Aggregations