use of org.eclipse.jdt.core.dom.SimpleName in project che by eclipse.
the class IntroduceFactoryRefactoring method getCtorCallAt.
/**
* Look "in the vicinity" of the given range to find the <code>ClassInstanceCreation</code>
* node that this search hit identified. Necessary because the <code>SearchEngine</code>
* doesn't always cough up text extents that <code>NodeFinder.perform()</code> agrees with.
* @param start
* @param length
* @param unitAST
* @return return a {@link ClassInstanceCreation} or a {@link MethodRef} or <code>null</code> if this is really a constructor->constructor call (e.g. "this(...)")
* @throws CoreException
*/
private ASTNode getCtorCallAt(int start, int length, CompilationUnit unitAST) throws CoreException {
ICompilationUnit unitHandle = ASTCreator.getCu(unitAST);
ASTNode node = NodeFinder.perform(unitAST, start, length);
if (node == null)
throw new CoreException(JavaUIStatus.createError(IStatus.ERROR, Messages.format(RefactoringCoreMessages.IntroduceFactory_noASTNodeForConstructorSearchHit, new Object[] { Integer.toString(start), Integer.toString(start + length), BasicElementLabels.getJavaCodeString(unitHandle.getSource().substring(start, start + length)), BasicElementLabels.getFileName(unitHandle) }), null));
if (node instanceof ClassInstanceCreation) {
if (((ClassInstanceCreation) node).getAnonymousClassDeclaration() != null) {
// Cannot replace anonymous inner class, see https://bugs.eclipse.org/bugs/show_bug.cgi?id=250660
fConstructorVisibility = Modifier.PROTECTED;
return null;
}
return node;
} else if (node instanceof VariableDeclaration) {
Expression init = ((VariableDeclaration) node).getInitializer();
if (init instanceof ClassInstanceCreation) {
return init;
} else if (init != null)
throw new CoreException(JavaUIStatus.createError(IStatus.ERROR, Messages.format(RefactoringCoreMessages.IntroduceFactory_unexpectedInitializerNodeType, new Object[] { BasicElementLabels.getJavaCodeString(init.toString()), BasicElementLabels.getFileName(unitHandle) }), null));
else
throw new CoreException(JavaUIStatus.createError(IStatus.ERROR, Messages.format(RefactoringCoreMessages.IntroduceFactory_noConstructorCallNodeInsideFoundVarbleDecl, BasicElementLabels.getJavaCodeString(node.toString())), null));
} else if (node instanceof ConstructorInvocation) {
// to another flavor on the same class.
return null;
} else if (node instanceof SuperConstructorInvocation) {
// This is a call we can bypass; it's from one constructor flavor
// to another flavor on the same class.
fConstructorVisibility = Modifier.PROTECTED;
return null;
} else if (node instanceof ExpressionStatement) {
Expression expr = ((ExpressionStatement) node).getExpression();
if (expr instanceof ClassInstanceCreation)
return expr;
else
throw new CoreException(JavaUIStatus.createError(IStatus.ERROR, Messages.format(RefactoringCoreMessages.IntroduceFactory_unexpectedASTNodeTypeForConstructorSearchHit, new Object[] { BasicElementLabels.getJavaCodeString(expr.toString()), BasicElementLabels.getFileName(unitHandle) }), null));
} else if (node instanceof SimpleName && (node.getParent() instanceof MethodDeclaration || node.getParent() instanceof AbstractTypeDeclaration)) {
// We seem to have been given a hit for an implicit call to the base-class constructor.
// Do nothing with this (implicit) call, but have to make sure we make the derived class
// doesn't lose access to the base-class constructor (so make it 'protected', not 'private').
fConstructorVisibility = Modifier.PROTECTED;
return null;
} else if (node instanceof MethodRef) {
return node;
} else
throw new CoreException(JavaUIStatus.createError(IStatus.ERROR, Messages.format(RefactoringCoreMessages.IntroduceFactory_unexpectedASTNodeTypeForConstructorSearchHit, new Object[] { BasicElementLabels.getJavaElementName(node.getClass().getName() + "('" + node.toString() + "')"), BasicElementLabels.getFileName(unitHandle) }), //$NON-NLS-1$ //$NON-NLS-2$
null));
}
use of org.eclipse.jdt.core.dom.SimpleName 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.jdt.core.dom.SimpleName in project che by eclipse.
the class ExtractMethodRefactoring method createCallNodes.
//---- Code generation -----------------------------------------------------------------------
private ASTNode[] createCallNodes(SnippetFinder.Match duplicate, int modifiers) {
List<ASTNode> result = new ArrayList<ASTNode>(2);
IVariableBinding[] locals = fAnalyzer.getCallerLocals();
for (int i = 0; i < locals.length; i++) {
result.add(createDeclaration(locals[i], null));
}
MethodInvocation invocation = fAST.newMethodInvocation();
invocation.setName(fAST.newSimpleName(fMethodName));
ASTNode typeNode = ASTResolving.findParentType(fAnalyzer.getEnclosingBodyDeclaration());
RefactoringStatus status = new RefactoringStatus();
while (fDestination != typeNode) {
fAnalyzer.checkInput(status, fMethodName, typeNode);
if (!status.isOK()) {
SimpleName destinationTypeName = fAST.newSimpleName(ASTNodes.getEnclosingType(fDestination).getName());
if ((modifiers & Modifier.STATIC) == 0) {
ThisExpression thisExpression = fAST.newThisExpression();
thisExpression.setQualifier(destinationTypeName);
invocation.setExpression(thisExpression);
} else {
invocation.setExpression(destinationTypeName);
}
break;
}
typeNode = typeNode.getParent();
}
List<Expression> arguments = invocation.arguments();
for (int i = 0; i < fParameterInfos.size(); i++) {
ParameterInfo parameter = fParameterInfos.get(i);
arguments.add(ASTNodeFactory.newName(fAST, getMappedName(duplicate, parameter)));
}
if (fLinkedProposalModel != null) {
LinkedProposalPositionGroup nameGroup = fLinkedProposalModel.getPositionGroup(KEY_NAME, true);
nameGroup.addPosition(fRewriter.track(invocation.getName()), false);
}
ASTNode call;
int returnKind = fAnalyzer.getReturnKind();
switch(returnKind) {
case ExtractMethodAnalyzer.ACCESS_TO_LOCAL:
IVariableBinding binding = fAnalyzer.getReturnLocal();
if (binding != null) {
VariableDeclarationStatement decl = createDeclaration(getMappedBinding(duplicate, binding), invocation);
call = decl;
} else {
Assignment assignment = fAST.newAssignment();
assignment.setLeftHandSide(ASTNodeFactory.newName(fAST, getMappedBinding(duplicate, fAnalyzer.getReturnValue()).getName()));
assignment.setRightHandSide(invocation);
call = assignment;
}
break;
case ExtractMethodAnalyzer.RETURN_STATEMENT_VALUE:
ReturnStatement rs = fAST.newReturnStatement();
rs.setExpression(invocation);
call = rs;
break;
default:
call = invocation;
}
if (call instanceof Expression && !fAnalyzer.isExpressionSelected()) {
call = fAST.newExpressionStatement((Expression) call);
}
result.add(call);
// return;
if (returnKind == ExtractMethodAnalyzer.RETURN_STATEMENT_VOID && !fAnalyzer.isLastStatementSelected()) {
result.add(fAST.newReturnStatement());
}
return result.toArray(new ASTNode[result.size()]);
}
use of org.eclipse.jdt.core.dom.SimpleName in project che by eclipse.
the class ExtractMethodAnalyzer method canHandleBranches.
private String canHandleBranches() {
if (fReturnValue != null)
return RefactoringCoreMessages.ExtractMethodAnalyzer_branch_mismatch;
ASTNode[] selectedNodes = getSelectedNodes();
final ASTNode lastSelectedNode = selectedNodes[selectedNodes.length - 1];
Statement body = getParentLoopBody(lastSelectedNode.getParent());
if (!(body instanceof Block))
return RefactoringCoreMessages.ExtractMethodAnalyzer_branch_mismatch;
if (body != lastSelectedNode) {
Block block = (Block) body;
List<Statement> statements = block.statements();
ASTNode lastStatementInLoop = statements.get(statements.size() - 1);
if (lastSelectedNode != lastStatementInLoop)
return RefactoringCoreMessages.ExtractMethodAnalyzer_branch_mismatch;
}
final String[] continueMatchesLoopProblem = { null };
for (int i = 0; i < selectedNodes.length; i++) {
final ASTNode astNode = selectedNodes[i];
astNode.accept(new ASTVisitor() {
ArrayList<String> fLocalLoopLabels = new ArrayList<String>();
@Override
public boolean visit(BreakStatement node) {
SimpleName label = node.getLabel();
if (label != null && !fLocalLoopLabels.contains(label.getIdentifier())) {
continueMatchesLoopProblem[0] = Messages.format(RefactoringCoreMessages.ExtractMethodAnalyzer_branch_break_mismatch, //$NON-NLS-1$
new Object[] { ("break " + label.getIdentifier()) });
}
return false;
}
@Override
public boolean visit(LabeledStatement node) {
SimpleName label = node.getLabel();
if (label != null)
fLocalLoopLabels.add(label.getIdentifier());
return true;
}
@Override
public void endVisit(ContinueStatement node) {
SimpleName label = node.getLabel();
if (label != null && !fLocalLoopLabels.contains(label.getIdentifier())) {
if (fEnclosingLoopLabel == null || !label.getIdentifier().equals(fEnclosingLoopLabel.getIdentifier())) {
continueMatchesLoopProblem[0] = Messages.format(RefactoringCoreMessages.ExtractMethodAnalyzer_branch_continue_mismatch, //$NON-NLS-1$
new Object[] { "continue " + label.getIdentifier() });
}
}
}
});
}
return continueMatchesLoopProblem[0];
}
use of org.eclipse.jdt.core.dom.SimpleName in project che by eclipse.
the class InlineConstantRefactoring method checkFinalConditions.
@Override
public RefactoringStatus checkFinalConditions(IProgressMonitor pm) throws CoreException {
RefactoringStatus result = new RefactoringStatus();
//$NON-NLS-1$
pm.beginTask("", 3);
try {
fSelectionCuRewrite.clearASTAndImportRewrites();
fDeclarationCuRewrite.clearASTAndImportRewrites();
List<CompilationUnitChange> changes = new ArrayList<CompilationUnitChange>();
HashSet<SimpleName> staticImportsInInitializer = new HashSet<SimpleName>();
ImportReferencesCollector.collect(getInitializer(), fField.getJavaProject(), null, new ArrayList<SimpleName>(), staticImportsInInitializer);
if (getReplaceAllReferences()) {
SearchResultGroup[] searchResultGroups = findReferences(pm, result);
for (int i = 0; i < searchResultGroups.length; i++) {
if (pm.isCanceled())
throw new OperationCanceledException();
SearchResultGroup group = searchResultGroups[i];
ICompilationUnit cu = group.getCompilationUnit();
CompilationUnitRewrite cuRewrite = getCuRewrite(cu);
Name[] references = extractReferenceNodes(group.getSearchResults(), cuRewrite.getRoot());
InlineTargetCompilationUnit targetCompilationUnit = new InlineTargetCompilationUnit(cuRewrite, references, this, staticImportsInInitializer);
CompilationUnitChange change = targetCompilationUnit.getChange();
if (change != null)
changes.add(change);
}
} else {
Assert.isTrue(!isDeclarationSelected());
InlineTargetCompilationUnit targetForOnlySelectedReference = new InlineTargetCompilationUnit(fSelectionCuRewrite, new Name[] { fSelectedConstantName }, this, staticImportsInInitializer);
CompilationUnitChange change = targetForOnlySelectedReference.getChange();
if (change != null)
changes.add(change);
}
if (result.hasFatalError())
return result;
if (getRemoveDeclaration() && getReplaceAllReferences()) {
boolean declarationRemoved = false;
for (Iterator<CompilationUnitChange> iter = changes.iterator(); iter.hasNext(); ) {
CompilationUnitChange change = iter.next();
if (change.getCompilationUnit().equals(fDeclarationCuRewrite.getCu())) {
declarationRemoved = true;
break;
}
}
if (!declarationRemoved) {
InlineTargetCompilationUnit targetForDeclaration = new InlineTargetCompilationUnit(fDeclarationCuRewrite, new Name[0], this, staticImportsInInitializer);
CompilationUnitChange change = targetForDeclaration.getChange();
if (change != null)
changes.add(change);
}
}
ICompilationUnit[] cus = new ICompilationUnit[changes.size()];
for (int i = 0; i < changes.size(); i++) {
CompilationUnitChange change = changes.get(i);
cus[i] = change.getCompilationUnit();
}
result.merge(Checks.validateModifiesFiles(ResourceUtil.getFiles(cus), getValidationContext()));
pm.worked(1);
fChanges = changes.toArray(new CompilationUnitChange[changes.size()]);
return result;
} finally {
pm.done();
}
}
Aggregations