use of org.eclipse.text.edits.TextEditGroup in project che by eclipse.
the class ExtractToNullCheckedLocalProposal method getRewrite.
@Override
protected ASTRewrite getRewrite() throws CoreException {
// infrastructure:
AST ast = this.compilationUnit.getAST();
ASTRewrite rewrite = ASTRewrite.create(ast);
ImportRewrite imports = ImportRewrite.create(this.compilationUnit, true);
TextEditGroup group = new TextEditGroup(FixMessages.ExtractToNullCheckedLocalProposal_extractCheckedLocal_editName);
LinkedProposalPositionGroup localNameGroup = new LinkedProposalPositionGroup(LOCAL_NAME_POSITION_GROUP);
getLinkedProposalModel().addPositionGroup(localNameGroup);
// AST context:
Statement origStmt = (Statement) ASTNodes.getParent(this.fieldReference, Statement.class);
// determine suitable strategy for rearranging elements towards a new code structure:
RearrangeStrategy rearrangeStrategy = RearrangeStrategy.create(origStmt, rewrite, group);
Expression toReplace;
ASTNode directParent = this.fieldReference.getParent();
if (directParent instanceof FieldAccess) {
toReplace = (Expression) directParent;
} else if (directParent instanceof QualifiedName && this.fieldReference.getLocationInParent() == QualifiedName.NAME_PROPERTY) {
toReplace = (Expression) directParent;
} else {
toReplace = this.fieldReference;
}
// new local declaration initialized from the field reference
VariableDeclarationFragment localFrag = ast.newVariableDeclarationFragment();
VariableDeclarationStatement localDecl = ast.newVariableDeclarationStatement(localFrag);
// ... type
localDecl.setType(newType(toReplace.resolveTypeBinding(), ast, imports));
localDecl.modifiers().add(ast.newModifier(Modifier.ModifierKeyword.FINAL_KEYWORD));
// ... name
String localName = proposeLocalName(this.fieldReference, this.compilationUnit, getCompilationUnit().getJavaProject());
localFrag.setName(ast.newSimpleName(localName));
// ... initialization
localFrag.setInitializer((Expression) ASTNode.copySubtree(ast, toReplace));
rearrangeStrategy.insertLocalDecl(localDecl);
// if statement:
IfStatement ifStmt = ast.newIfStatement();
// condition:
InfixExpression nullCheck = ast.newInfixExpression();
nullCheck.setLeftOperand(ast.newSimpleName(localName));
nullCheck.setRightOperand(ast.newNullLiteral());
nullCheck.setOperator(InfixExpression.Operator.NOT_EQUALS);
ifStmt.setExpression(nullCheck);
// then block: the original statement
Block thenBlock = ast.newBlock();
thenBlock.statements().add(rearrangeStrategy.createMoveTargetForOrigStmt());
ifStmt.setThenStatement(thenBlock);
// ... but with the field reference replaced by the new local:
SimpleName dereferencedName = ast.newSimpleName(localName);
rewrite.replace(toReplace, dereferencedName, group);
// else block: a Todo comment
Block elseBlock = ast.newBlock();
//$NON-NLS-1$
String elseStatement = "// TODO " + FixMessages.ExtractToNullCheckedLocalProposal_todoHandleNullDescription;
if (origStmt instanceof ReturnStatement) {
Type returnType = newType(((ReturnStatement) origStmt).getExpression().resolveTypeBinding(), ast, imports);
ReturnStatement returnStatement = ast.newReturnStatement();
returnStatement.setExpression(ASTNodeFactory.newDefaultExpression(ast, returnType, 0));
elseStatement += '\n' + ASTNodes.asFormattedString(returnStatement, 0, String.valueOf('\n'), getCompilationUnit().getJavaProject().getOptions(true));
}
EmptyStatement todoNode = (EmptyStatement) rewrite.createStringPlaceholder(elseStatement, ASTNode.EMPTY_STATEMENT);
elseBlock.statements().add(todoNode);
ifStmt.setElseStatement(elseBlock);
// link all three occurrences of the new local variable:
addLinkedPosition(rewrite.track(localFrag.getName()), true, /*first*/
LOCAL_NAME_POSITION_GROUP);
addLinkedPosition(rewrite.track(nullCheck.getLeftOperand()), false, LOCAL_NAME_POSITION_GROUP);
addLinkedPosition(rewrite.track(dereferencedName), false, LOCAL_NAME_POSITION_GROUP);
rearrangeStrategy.insertIfStatement(ifStmt, thenBlock);
return rewrite;
}
use of org.eclipse.text.edits.TextEditGroup in project che by eclipse.
the class InlineTempRefactoring method inlineTemp.
private void inlineTemp(CompilationUnitRewrite cuRewrite) throws JavaModelException {
SimpleName[] references = getReferences();
TextEditGroup groupDesc = cuRewrite.createGroupDescription(RefactoringCoreMessages.InlineTempRefactoring_inline_edit_name);
ASTRewrite rewrite = cuRewrite.getASTRewrite();
for (int i = 0; i < references.length; i++) {
SimpleName curr = references[i];
ASTNode initializerCopy = getInitializerSource(cuRewrite, curr);
rewrite.replace(curr, initializerCopy, groupDesc);
}
}
use of org.eclipse.text.edits.TextEditGroup in project che by eclipse.
the class ExtractMethodRefactoring method replaceBranches.
private void replaceBranches(final CompilationUnitChange result) {
ASTNode[] selectedNodes = fAnalyzer.getSelectedNodes();
for (int i = 0; i < selectedNodes.length; i++) {
ASTNode astNode = selectedNodes[i];
astNode.accept(new ASTVisitor() {
private LinkedList<String> fOpenLoopLabels = new LinkedList<String>();
private void registerLoopLabel(Statement node) {
String identifier;
if (node.getParent() instanceof LabeledStatement) {
LabeledStatement labeledStatement = (LabeledStatement) node.getParent();
identifier = labeledStatement.getLabel().getIdentifier();
} else {
identifier = null;
}
fOpenLoopLabels.add(identifier);
}
@Override
public boolean visit(ForStatement node) {
registerLoopLabel(node);
return super.visit(node);
}
@Override
public void endVisit(ForStatement node) {
fOpenLoopLabels.removeLast();
}
@Override
public boolean visit(WhileStatement node) {
registerLoopLabel(node);
return super.visit(node);
}
@Override
public void endVisit(WhileStatement node) {
fOpenLoopLabels.removeLast();
}
@Override
public boolean visit(EnhancedForStatement node) {
registerLoopLabel(node);
return super.visit(node);
}
@Override
public void endVisit(EnhancedForStatement node) {
fOpenLoopLabels.removeLast();
}
@Override
public boolean visit(DoStatement node) {
registerLoopLabel(node);
return super.visit(node);
}
@Override
public void endVisit(DoStatement node) {
fOpenLoopLabels.removeLast();
}
@Override
public void endVisit(ContinueStatement node) {
final SimpleName label = node.getLabel();
if (fOpenLoopLabels.isEmpty() || (label != null && !fOpenLoopLabels.contains(label.getIdentifier()))) {
TextEditGroup description = new TextEditGroup(RefactoringCoreMessages.ExtractMethodRefactoring_replace_continue);
result.addTextEditGroup(description);
ReturnStatement rs = fAST.newReturnStatement();
IVariableBinding returnValue = fAnalyzer.getReturnValue();
if (returnValue != null) {
rs.setExpression(fAST.newSimpleName(getName(returnValue)));
}
fRewriter.replace(node, rs, description);
}
}
});
}
}
use of org.eclipse.text.edits.TextEditGroup in project che by eclipse.
the class ExtractMethodRefactoring method createChange.
/* (non-Javadoc)
* Method declared in IRefactoring
*/
@Override
public Change createChange(IProgressMonitor pm) throws CoreException {
if (fMethodName == null)
return null;
//$NON-NLS-1$
pm.beginTask("", 2);
try {
fAnalyzer.aboutToCreateChange();
BodyDeclaration declaration = fAnalyzer.getEnclosingBodyDeclaration();
fRewriter = ASTRewrite.create(declaration.getAST());
final CompilationUnitChange result = new CompilationUnitChange(RefactoringCoreMessages.ExtractMethodRefactoring_change_name, fCUnit);
result.setSaveMode(TextFileChange.KEEP_SAVE_STATE);
result.setDescriptor(new RefactoringChangeDescriptor(getRefactoringDescriptor()));
MultiTextEdit root = new MultiTextEdit();
result.setEdit(root);
ASTNode[] selectedNodes = fAnalyzer.getSelectedNodes();
fRewriter.setTargetSourceRangeComputer(new SelectionAwareSourceRangeComputer(selectedNodes, fCUnit.getBuffer(), fSelectionStart, fSelectionLength));
TextEditGroup substituteDesc = new TextEditGroup(Messages.format(RefactoringCoreMessages.ExtractMethodRefactoring_substitute_with_call, BasicElementLabels.getJavaElementName(fMethodName)));
result.addTextEditGroup(substituteDesc);
MethodDeclaration mm = createNewMethod(selectedNodes, fCUnit.findRecommendedLineSeparator(), substituteDesc);
if (fLinkedProposalModel != null) {
LinkedProposalPositionGroup typeGroup = fLinkedProposalModel.getPositionGroup(KEY_TYPE, true);
typeGroup.addPosition(fRewriter.track(mm.getReturnType2()), false);
ITypeBinding typeBinding = fAnalyzer.getReturnTypeBinding();
if (typeBinding != null) {
ITypeBinding[] relaxingTypes = ASTResolving.getNarrowingTypes(fAST, typeBinding);
for (int i = 0; i < relaxingTypes.length; i++) {
typeGroup.addProposal(relaxingTypes[i], fCUnit, relaxingTypes.length - i);
}
}
LinkedProposalPositionGroup nameGroup = fLinkedProposalModel.getPositionGroup(KEY_NAME, true);
nameGroup.addPosition(fRewriter.track(mm.getName()), false);
ModifierCorrectionSubProcessor.installLinkedVisibilityProposals(fLinkedProposalModel, fRewriter, mm.modifiers(), false);
}
TextEditGroup insertDesc = new TextEditGroup(Messages.format(RefactoringCoreMessages.ExtractMethodRefactoring_add_method, BasicElementLabels.getJavaElementName(fMethodName)));
result.addTextEditGroup(insertDesc);
if (fDestination == ASTResolving.findParentType(declaration.getParent())) {
ChildListPropertyDescriptor desc = (ChildListPropertyDescriptor) declaration.getLocationInParent();
ListRewrite container = fRewriter.getListRewrite(declaration.getParent(), desc);
container.insertAfter(mm, declaration, insertDesc);
} else {
BodyDeclarationRewrite container = BodyDeclarationRewrite.create(fRewriter, fDestination);
container.insert(mm, insertDesc);
}
replaceDuplicates(result, mm.getModifiers());
replaceBranches(result);
if (fImportRewriter.hasRecordedChanges()) {
TextEdit edit = fImportRewriter.rewriteImports(null);
root.addChild(edit);
result.addTextEditGroup(new TextEditGroup(RefactoringCoreMessages.ExtractMethodRefactoring_organize_imports, new TextEdit[] { edit }));
}
root.addChild(fRewriter.rewriteAST());
return result;
} finally {
pm.done();
}
}
use of org.eclipse.text.edits.TextEditGroup in project che by eclipse.
the class IntroduceFactoryRefactoring method addAllChangesFor.
/**
* Add all changes necessary on the <code>ICompilationUnit</code> in the given
* <code>SearchResultGroup</code> to implement the refactoring transformation
* to the given <code>CompilationUnitChange</code>.
* @param rg the <code>SearchResultGroup</code> for which changes should be created
* @param unitHandle
* @param unitChange the CompilationUnitChange object for the compilation unit in question
* @return <code>true</code> iff a change has been added
* @throws CoreException
*/
private boolean addAllChangesFor(SearchResultGroup rg, ICompilationUnit unitHandle, CompilationUnitChange unitChange) throws CoreException {
// ICompilationUnit unitHandle= rg.getCompilationUnit();
Assert.isTrue(rg == null || rg.getCompilationUnit() == unitHandle);
CompilationUnit unit = getASTFor(unitHandle);
ASTRewrite unitRewriter = ASTRewrite.create(unit.getAST());
MultiTextEdit root = new MultiTextEdit();
boolean someChange = false;
unitChange.setEdit(root);
fImportRewriter = StubUtility.createImportRewrite(unit, true);
// First create the factory method
if (unitHandle.equals(fFactoryUnitHandle)) {
TextEditGroup factoryGD = new TextEditGroup(RefactoringCoreMessages.IntroduceFactory_addFactoryMethod);
createFactoryChange(unitRewriter, unit, factoryGD);
unitChange.addTextEditGroup(factoryGD);
someChange = true;
}
// Now rewrite all the constructor calls to use the factory method
if (rg != null)
if (replaceConstructorCalls(rg, unit, unitRewriter, unitChange))
someChange = true;
// Finally, make the constructor private, if requested.
if (shouldProtectConstructor() && isConstructorUnit(unitHandle)) {
TextEditGroup declGD = new TextEditGroup(RefactoringCoreMessages.IntroduceFactory_protectConstructor);
if (protectConstructor(unit, unitRewriter, declGD)) {
unitChange.addTextEditGroup(declGD);
someChange = true;
}
}
if (someChange) {
root.addChild(unitRewriter.rewriteAST());
root.addChild(fImportRewriter.rewriteImports(null));
}
return someChange;
}
Aggregations