use of org.eclipse.jdt.core.dom.rewrite.ImportRewrite in project che 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));
Expression placeholder = (Expression) rewrite.createCopyTarget(assignment.getRightHandSide());
newDeclFrag.setInitializer(placeholder);
newDeclFrag.setName(ast.newSimpleName(node.getIdentifier()));
rewrite.replace(assignment, newDecl, null);
addLinkedPosition(rewrite.track(newDecl.getType()), false, KEY_TYPE);
addLinkedPosition(rewrite.track(newDeclFrag.getName()), true, KEY_NAME);
setEndPosition(rewrite.track(assignment.getParent()));
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));
rewrite.replace(assignment, expression, null);
addLinkedPosition(rewrite.track(expression.getType()), false, KEY_TYPE);
addLinkedPosition(rewrite.track(frag.getName()), true, KEY_NAME);
setEndPosition(rewrite.track(expression));
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);
} else {
//$NON-NLS-1$
type = ast.newSimpleType(ast.newSimpleName("Object"));
}
rewrite.set(parameter, SingleVariableDeclaration.TYPE_PROPERTY, type, null);
addLinkedPosition(rewrite.track(type), false, KEY_TYPE);
addLinkedPosition(rewrite.track(newName), true, KEY_NAME);
setEndPosition(rewrite.track(expression));
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));
// newDeclFrag.setInitializer(ASTNodeFactory.newDefaultExpression(ast, newDecl.getType(), 0));
addLinkedPosition(rewrite.track(newDecl.getType()), false, KEY_TYPE);
addLinkedPosition(rewrite.track(node), true, KEY_NAME);
addLinkedPosition(rewrite.track(newDeclFrag.getName()), false, KEY_NAME);
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.rewrite.ImportRewrite in project che by eclipse.
the class AssignToVariableAssistProposal method evaluateType.
private Type evaluateType(AST ast) {
ITypeBinding[] proposals = ASTResolving.getRelaxingTypes(ast, fTypeBinding);
for (int i = 0; i < proposals.length; i++) {
addLinkedPositionProposal(KEY_TYPE, proposals[i]);
}
ImportRewrite importRewrite = getImportRewrite();
CompilationUnit cuNode = (CompilationUnit) fNodeToAssign.getRoot();
ImportRewriteContext context = new ContextSensitiveImportRewriteContext(cuNode, fNodeToAssign.getStartPosition(), importRewrite);
return importRewrite.addImport(fTypeBinding, ast, context);
}
use of org.eclipse.jdt.core.dom.rewrite.ImportRewrite in project che by eclipse.
the class ChangeMethodSignatureProposal method modifyExceptions.
private void modifyExceptions(ASTRewrite rewrite, MethodDeclaration methodDecl) {
AST ast = methodDecl.getAST();
ImportRewrite imports = getImportRewrite();
ImportRewriteContext context = new ContextSensitiveImportRewriteContext(methodDecl, imports);
ListRewrite listRewrite = rewrite.getListRewrite(methodDecl, MethodDeclaration.THROWN_EXCEPTION_TYPES_PROPERTY);
// old exceptions
List<Type> exceptions = methodDecl.thrownExceptionTypes();
// index over the old exceptions
int k = 0;
for (int i = 0; i < fExceptionChanges.length; i++) {
ChangeDescription curr = fExceptionChanges[i];
if (curr == null) {
k++;
} else if (curr instanceof InsertDescription) {
InsertDescription desc = (InsertDescription) curr;
String type = imports.addImport(desc.type, context);
ASTNode newNode = imports.addImport(desc.type, ast, context);
listRewrite.insertAt(newNode, i, null);
String key = getExceptionTypeGroupId(i);
addLinkedPosition(rewrite.track(newNode), false, key);
Javadoc javadoc = methodDecl.getJavadoc();
if (javadoc != null && JavadocTagsSubProcessor.findThrowsTag(javadoc, type) == null) {
TagElement newTagElement = ast.newTagElement();
newTagElement.setTagName(TagElement.TAG_THROWS);
ASTNode newRef = ASTNodeFactory.newName(ast, type);
newTagElement.fragments().add(newRef);
//$NON-NLS-1$
insertTabStop(rewrite, newTagElement.fragments(), "throws_tagcomment" + i);
insertThrowsTag(rewrite.getListRewrite(javadoc, Javadoc.TAGS_PROPERTY), exceptions, k, newTagElement);
addLinkedPosition(rewrite.track(newRef), false, key);
}
} else if (curr instanceof RemoveDescription) {
Type node = exceptions.get(k);
listRewrite.remove(node, null);
k++;
TagElement tagNode = findThrowsTag(methodDecl, node);
if (tagNode != null) {
rewrite.remove(tagNode, null);
}
} else if (curr instanceof EditDescription) {
EditDescription desc = (EditDescription) curr;
Type oldNode = exceptions.get(k);
String type = imports.addImport(desc.type, context);
ASTNode newNode = imports.addImport(desc.type, ast, context);
listRewrite.replace(oldNode, newNode, null);
String key = getExceptionTypeGroupId(i);
addLinkedPosition(rewrite.track(newNode), false, key);
k++;
TagElement tagNode = findThrowsTag(methodDecl, oldNode);
if (tagNode != null) {
ASTNode newRef = ASTNodeFactory.newType(ast, type);
rewrite.replace((ASTNode) tagNode.fragments().get(0), newRef, null);
addLinkedPosition(rewrite.track(newRef), false, key);
}
} else if (curr instanceof SwapDescription) {
Type decl1 = exceptions.get(k);
Type decl2 = exceptions.get(((SwapDescription) curr).index);
rewrite.replace(decl1, rewrite.createCopyTarget(decl2), null);
rewrite.replace(decl2, rewrite.createCopyTarget(decl1), null);
k++;
TagElement tagNode1 = findThrowsTag(methodDecl, decl1);
TagElement tagNode2 = findThrowsTag(methodDecl, decl2);
if (tagNode1 != null && tagNode2 != null) {
rewrite.replace(tagNode1, rewrite.createCopyTarget(tagNode2), null);
rewrite.replace(tagNode2, rewrite.createCopyTarget(tagNode1), null);
}
}
}
}
use of org.eclipse.jdt.core.dom.rewrite.ImportRewrite in project che by eclipse.
the class ExtractTempRefactoring method createTempType.
private Type createTempType() throws CoreException {
Expression expression = getSelectedExpression().getAssociatedExpression();
Type resultingType = null;
ITypeBinding typeBinding = expression.resolveTypeBinding();
ASTRewrite rewrite = fCURewrite.getASTRewrite();
AST ast = rewrite.getAST();
if (expression instanceof ClassInstanceCreation && (typeBinding == null || typeBinding.getTypeArguments().length == 0)) {
resultingType = (Type) rewrite.createCopyTarget(((ClassInstanceCreation) expression).getType());
} else if (expression instanceof CastExpression) {
resultingType = (Type) rewrite.createCopyTarget(((CastExpression) expression).getType());
} else {
if (typeBinding == null) {
typeBinding = ASTResolving.guessBindingForReference(expression);
}
if (typeBinding != null) {
typeBinding = Bindings.normalizeForDeclarationUse(typeBinding, ast);
ImportRewrite importRewrite = fCURewrite.getImportRewrite();
ImportRewriteContext context = new ContextSensitiveImportRewriteContext(expression, importRewrite);
resultingType = importRewrite.addImport(typeBinding, ast, context);
} else {
//$NON-NLS-1$
resultingType = ast.newSimpleType(ast.newSimpleName("Object"));
}
}
if (fLinkedProposalModel != null) {
LinkedProposalPositionGroup typeGroup = fLinkedProposalModel.getPositionGroup(KEY_TYPE, true);
typeGroup.addPosition(rewrite.track(resultingType), false);
if (typeBinding != null) {
ITypeBinding[] relaxingTypes = ASTResolving.getNarrowingTypes(ast, typeBinding);
for (int i = 0; i < relaxingTypes.length; i++) {
typeGroup.addProposal(relaxingTypes[i], fCURewrite.getCu(), relaxingTypes.length - i);
}
}
}
return resultingType;
}
use of org.eclipse.jdt.core.dom.rewrite.ImportRewrite in project che by eclipse.
the class InlineMethodRefactoring method checkFinalConditions.
@Override
public RefactoringStatus checkFinalConditions(IProgressMonitor pm) throws CoreException {
//$NON-NLS-1$
pm.beginTask("", 20);
fChangeManager = new TextChangeManager();
RefactoringStatus result = new RefactoringStatus();
fSourceProvider.initialize();
fTargetProvider.initialize();
pm.setTaskName(RefactoringCoreMessages.InlineMethodRefactoring_searching);
RefactoringStatus searchStatus = new RefactoringStatus();
String binaryRefsDescription = Messages.format(RefactoringCoreMessages.ReferencesInBinaryContext_ref_in_binaries_description, BasicElementLabels.getJavaElementName(fSourceProvider.getMethodName()));
ReferencesInBinaryContext binaryRefs = new ReferencesInBinaryContext(binaryRefsDescription);
ICompilationUnit[] units = fTargetProvider.getAffectedCompilationUnits(searchStatus, binaryRefs, new SubProgressMonitor(pm, 1));
binaryRefs.addErrorIfNecessary(searchStatus);
if (searchStatus.hasFatalError()) {
result.merge(searchStatus);
return result;
}
IFile[] filesToBeModified = getFilesToBeModified(units);
result.merge(Checks.validateModifiesFiles(filesToBeModified, getValidationContext()));
if (result.hasFatalError())
return result;
result.merge(ResourceChangeChecker.checkFilesToBeChanged(filesToBeModified, new SubProgressMonitor(pm, 1)));
checkOverridden(result, new SubProgressMonitor(pm, 4));
IProgressMonitor sub = new SubProgressMonitor(pm, 15);
//$NON-NLS-1$
sub.beginTask("", units.length * 3);
for (int c = 0; c < units.length; c++) {
ICompilationUnit unit = units[c];
sub.subTask(Messages.format(RefactoringCoreMessages.InlineMethodRefactoring_processing, BasicElementLabels.getFileName(unit)));
CallInliner inliner = null;
try {
boolean added = false;
MultiTextEdit root = new MultiTextEdit();
CompilationUnitChange change = (CompilationUnitChange) fChangeManager.get(unit);
change.setEdit(root);
BodyDeclaration[] bodies = fTargetProvider.getAffectedBodyDeclarations(unit, new SubProgressMonitor(pm, 1));
if (bodies.length == 0)
continue;
inliner = new CallInliner(unit, (CompilationUnit) bodies[0].getRoot(), fSourceProvider);
for (int b = 0; b < bodies.length; b++) {
BodyDeclaration body = bodies[b];
inliner.initialize(body);
RefactoringStatus nestedInvocations = new RefactoringStatus();
ASTNode[] invocations = removeNestedCalls(nestedInvocations, unit, fTargetProvider.getInvocations(body, new SubProgressMonitor(sub, 2)));
for (int i = 0; i < invocations.length; i++) {
ASTNode invocation = invocations[i];
result.merge(inliner.initialize(invocation, fTargetProvider.getStatusSeverity()));
if (result.hasFatalError())
break;
if (result.getSeverity() < fTargetProvider.getStatusSeverity()) {
added = true;
TextEditGroup group = new TextEditGroup(RefactoringCoreMessages.InlineMethodRefactoring_edit_inline);
change.addTextEditGroup(group);
result.merge(inliner.perform(group));
} else {
fDeleteSource = false;
}
}
// to generate the modifications.
if (!nestedInvocations.isOK()) {
result.merge(nestedInvocations);
fDeleteSource = false;
}
}
if (!added) {
fChangeManager.remove(unit);
} else {
root.addChild(inliner.getModifications());
ImportRewrite rewrite = inliner.getImportEdit();
if (rewrite.hasRecordedChanges()) {
TextEdit edit = rewrite.rewriteImports(null);
if (edit instanceof MultiTextEdit ? ((MultiTextEdit) edit).getChildrenSize() > 0 : true) {
root.addChild(edit);
change.addTextEditGroup(new TextEditGroup(RefactoringCoreMessages.InlineMethodRefactoring_edit_import, new TextEdit[] { edit }));
}
}
}
} finally {
if (inliner != null)
inliner.dispose();
}
sub.worked(1);
if (sub.isCanceled())
throw new OperationCanceledException();
}
result.merge(searchStatus);
sub.done();
pm.done();
return result;
}
Aggregations