use of org.eclipse.jdt.core.dom.rewrite.ImportRewrite.ImportRewriteContext in project eclipse.jdt.ls by eclipse.
the class ExtractConstantRefactoring method getConstantType.
private Type getConstantType() throws JavaModelException {
if (fConstantTypeCache == null) {
IExpressionFragment fragment = getSelectedExpression();
ITypeBinding typeBinding = guessBindingForReference(fragment.getAssociatedExpression());
AST ast = fCuRewrite.getAST();
typeBinding = Bindings.normalizeForDeclarationUse(typeBinding, ast);
ImportRewrite importRewrite = fCuRewrite.getImportRewrite();
ImportRewriteContext context = new ContextSensitiveImportRewriteContext(fCuRewrite.getRoot(), fSelectionStart, importRewrite);
fConstantTypeCache = importRewrite.addImport(typeBinding, ast, context, TypeLocation.FIELD);
}
return fConstantTypeCache;
}
use of org.eclipse.jdt.core.dom.rewrite.ImportRewrite.ImportRewriteContext 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(fCompilationUnit);
MethodDeclaration stub = StubUtility2Core.createImplementationStubCore(fCompilationUnit, rewrite, importRewrite, context, methodToOverride, declaringType, settings, declaringType.isInterface(), node, snippetStringSupport);
ListRewrite rewriter = rewrite.getListRewrite(node, descriptor);
rewriter.insertFirst(stub, null);
ITrackedNodePosition position = rewrite.track(stub);
try {
Map<String, String> options = fCompilationUnit.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);
}
}
}
if (result == null) {
return replacementString;
}
return result;
}
use of org.eclipse.jdt.core.dom.rewrite.ImportRewrite.ImportRewriteContext in project eclipse.jdt.ls by eclipse.
the class ConstructorFromSuperclassProposal method getRewrite.
@Override
protected ASTRewrite getRewrite() throws CoreException {
AST ast = fTypeNode.getAST();
ASTRewrite rewrite = ASTRewrite.create(ast);
createImportRewrite((CompilationUnit) fTypeNode.getRoot());
CodeGenerationSettings settings = JavaPreferencesSettings.getCodeGenerationSettings(getCompilationUnit());
if (!settings.createComments) {
settings = null;
}
ImportRewriteContext importRewriteContext = new ContextSensitiveImportRewriteContext(fTypeNode, getImportRewrite());
MethodDeclaration newMethodDecl = createNewMethodDeclaration(ast, fSuperConstructor, rewrite, importRewriteContext, settings);
rewrite.getListRewrite(fTypeNode, TypeDeclaration.BODY_DECLARATIONS_PROPERTY).insertFirst(newMethodDecl, null);
addLinkedRanges(rewrite, newMethodDecl);
return rewrite;
}
use of org.eclipse.jdt.core.dom.rewrite.ImportRewrite.ImportRewriteContext in project eclipse.jdt.ls by eclipse.
the class ImplementInterfaceProposal method getRewrite.
@Override
protected ASTRewrite getRewrite() throws CoreException {
ASTNode boundNode = fAstRoot.findDeclaringNode(fBinding);
ASTNode declNode = null;
CompilationUnit newRoot = fAstRoot;
if (boundNode != null) {
// is same CU
declNode = boundNode;
} else {
newRoot = ASTResolving.createQuickFixAST(getCompilationUnit(), null);
declNode = newRoot.findDeclaringNode(fBinding.getKey());
}
ImportRewrite imports = createImportRewrite(newRoot);
if (declNode instanceof TypeDeclaration) {
AST ast = declNode.getAST();
ASTRewrite rewrite = ASTRewrite.create(ast);
ImportRewriteContext importRewriteContext = new ContextSensitiveImportRewriteContext(declNode, imports);
Type newInterface = imports.addImport(fNewInterface, ast, importRewriteContext, TypeLocation.OTHER);
ListRewrite listRewrite = rewrite.getListRewrite(declNode, TypeDeclaration.SUPER_INTERFACE_TYPES_PROPERTY);
listRewrite.insertLast(newInterface, null);
return rewrite;
}
return null;
}
use of org.eclipse.jdt.core.dom.rewrite.ImportRewrite.ImportRewriteContext 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;
}
Aggregations