下面列出了怎么用org.eclipse.jdt.core.dom.ExpressionStatement的API类实例代码及写法,或者点击链接到github查看源代码。
private Set<Integer> findAllMethodCall(){
Set<Integer> methodStmt = new HashSet<>();
if(_backupBody != null){
Block body = _backupBody;
for(int i = 0; i < body.statements().size(); i++){
ASTNode stmt = (ASTNode) body.statements().get(i);
if(stmt instanceof ExpressionStatement){
stmt = ((ExpressionStatement) stmt).getExpression();
if(stmt instanceof MethodInvocation){
methodStmt.add(i);
} else if(stmt instanceof Assignment){
Assignment assign = (Assignment) stmt;
if(assign.getRightHandSide() instanceof MethodInvocation){
methodStmt.add(i);
}
}
}
}
}
return methodStmt;
}
private static boolean accept(ICompilationUnit cu, CompletionContext completionContext, boolean acceptClass) {
if (completionContext != null && completionContext.isExtended()) {
if (completionContext.isInJavadoc()) {
return false;
}
if (completionContext instanceof InternalCompletionContext) {
InternalCompletionContext internalCompletionContext = (InternalCompletionContext) completionContext;
ASTNode node = internalCompletionContext.getCompletionNode();
if (node instanceof CompletionOnKeyword2) {
return true;
}
if (node instanceof CompletionOnFieldType) {
return true;
}
if (acceptClass && node instanceof CompletionOnSingleNameReference) {
if (completionContext.getEnclosingElement() instanceof IMethod) {
CompilationUnit ast = CoreASTProvider.getInstance().getAST(cu, CoreASTProvider.WAIT_YES, null);
org.eclipse.jdt.core.dom.ASTNode astNode = ASTNodeSearchUtil.getAstNode(ast, completionContext.getTokenStart(), completionContext.getTokenEnd() - completionContext.getTokenStart() + 1);
return (astNode == null || (astNode.getParent() instanceof ExpressionStatement));
}
return true;
}
}
}
return false;
}
private static ASTNode getInlineableMethodNode(ASTNode node, IJavaElement unit) {
if (node == null) {
return null;
}
switch (node.getNodeType()) {
case ASTNode.SIMPLE_NAME:
StructuralPropertyDescriptor locationInParent = node.getLocationInParent();
if (locationInParent == MethodDeclaration.NAME_PROPERTY) {
return node.getParent();
} else if (locationInParent == MethodInvocation.NAME_PROPERTY || locationInParent == SuperMethodInvocation.NAME_PROPERTY) {
return unit instanceof ICompilationUnit ? node.getParent() : null; // don't start on invocations in binary
}
return null;
case ASTNode.EXPRESSION_STATEMENT:
node = ((ExpressionStatement) node).getExpression();
}
switch (node.getNodeType()) {
case ASTNode.METHOD_DECLARATION:
return node;
case ASTNode.METHOD_INVOCATION:
case ASTNode.SUPER_METHOD_INVOCATION:
case ASTNode.CONSTRUCTOR_INVOCATION:
return unit instanceof ICompilationUnit ? node : null; // don't start on invocations in binary
}
return null;
}
private IExpressionFragment getSelectedExpression() throws JavaModelException {
if (fSelectedExpression != null) {
return fSelectedExpression;
}
IASTFragment selectedFragment = ASTFragmentFactory.createFragmentForSourceRange(new SourceRange(fSelectionStart, fSelectionLength), fCompilationUnitNode, fCu);
if (selectedFragment instanceof IExpressionFragment && !Checks.isInsideJavadoc(selectedFragment.getAssociatedNode())) {
fSelectedExpression = (IExpressionFragment) selectedFragment;
} else if (selectedFragment != null) {
if (selectedFragment.getAssociatedNode() instanceof ExpressionStatement) {
ExpressionStatement exprStatement = (ExpressionStatement) selectedFragment.getAssociatedNode();
Expression expression = exprStatement.getExpression();
fSelectedExpression = (IExpressionFragment) ASTFragmentFactory.createFragmentForFullSubtree(expression);
} else if (selectedFragment.getAssociatedNode() instanceof Assignment) {
Assignment assignment = (Assignment) selectedFragment.getAssociatedNode();
fSelectedExpression = (IExpressionFragment) ASTFragmentFactory.createFragmentForFullSubtree(assignment);
}
}
if (fSelectedExpression != null && Checks.isEnumCase(fSelectedExpression.getAssociatedExpression().getParent())) {
fSelectedExpression = null;
}
return fSelectedExpression;
}
private IExpressionFragment getSelectedExpression() throws JavaModelException {
if (fSelectedExpression != null) {
return fSelectedExpression;
}
IASTFragment selectedFragment = ASTFragmentFactory.createFragmentForSourceRange(new SourceRange(fSelectionStart, fSelectionLength), fCompilationUnitNode, fCu);
if (selectedFragment instanceof IExpressionFragment && !Checks.isInsideJavadoc(selectedFragment.getAssociatedNode())) {
fSelectedExpression = (IExpressionFragment) selectedFragment;
} else if (selectedFragment != null) {
if (selectedFragment.getAssociatedNode() instanceof ExpressionStatement) {
ExpressionStatement exprStatement = (ExpressionStatement) selectedFragment.getAssociatedNode();
Expression expression = exprStatement.getExpression();
fSelectedExpression = (IExpressionFragment) ASTFragmentFactory.createFragmentForFullSubtree(expression);
} else if (selectedFragment.getAssociatedNode() instanceof Assignment) {
Assignment assignment = (Assignment) selectedFragment.getAssociatedNode();
fSelectedExpression = (IExpressionFragment) ASTFragmentFactory.createFragmentForFullSubtree(assignment);
}
}
if (fSelectedExpression != null && Checks.isEnumCase(fSelectedExpression.getAssociatedExpression().getParent())) {
fSelectedExpression = null;
}
return fSelectedExpression;
}
private static boolean canReplace(IASTFragment fragment) {
ASTNode node = fragment.getAssociatedNode();
ASTNode parent = node.getParent();
if (parent instanceof VariableDeclarationFragment) {
VariableDeclarationFragment vdf = (VariableDeclarationFragment) parent;
if (node.equals(vdf.getName())) {
return false;
}
}
if (parent instanceof ExpressionStatement) {
return false;
}
if (parent instanceof SwitchCase) {
if (node instanceof Name) {
Name name = (Name) node;
ITypeBinding typeBinding = name.resolveTypeBinding();
if (typeBinding != null) {
return !typeBinding.isEnum();
}
}
}
return true;
}
private static ASTNode getInlineableMethodNode(ASTNode node, IJavaElement unit) {
if (node == null)
return null;
switch (node.getNodeType()) {
case ASTNode.SIMPLE_NAME:
StructuralPropertyDescriptor locationInParent= node.getLocationInParent();
if (locationInParent == MethodDeclaration.NAME_PROPERTY) {
return node.getParent();
} else if (locationInParent == MethodInvocation.NAME_PROPERTY
|| locationInParent == SuperMethodInvocation.NAME_PROPERTY) {
return unit instanceof ICompilationUnit ? node.getParent() : null; // don't start on invocations in binary
}
return null;
case ASTNode.EXPRESSION_STATEMENT:
node= ((ExpressionStatement)node).getExpression();
}
switch (node.getNodeType()) {
case ASTNode.METHOD_DECLARATION:
return node;
case ASTNode.METHOD_INVOCATION:
case ASTNode.SUPER_METHOD_INVOCATION:
case ASTNode.CONSTRUCTOR_INVOCATION:
return unit instanceof ICompilationUnit ? node : null; // don't start on invocations in binary
}
return null;
}
private static boolean canReplace(IASTFragment fragment) {
ASTNode node= fragment.getAssociatedNode();
ASTNode parent= node.getParent();
if (parent instanceof VariableDeclarationFragment) {
VariableDeclarationFragment vdf= (VariableDeclarationFragment) parent;
if (node.equals(vdf.getName()))
return false;
}
if (isMethodParameter(node))
return false;
if (isThrowableInCatchBlock(node))
return false;
if (parent instanceof ExpressionStatement)
return false;
if (isLeftValue(node))
return false;
if (isReferringToLocalVariableFromFor((Expression) node))
return false;
if (isUsedInForInitializerOrUpdater((Expression) node))
return false;
if (parent instanceof SwitchCase)
return false;
return true;
}
private IExpressionFragment getSelectedExpression() throws JavaModelException {
if (fSelectedExpression != null)
return fSelectedExpression;
IASTFragment selectedFragment= ASTFragmentFactory.createFragmentForSourceRange(new SourceRange(fSelectionStart, fSelectionLength), fCompilationUnitNode, fCu);
if (selectedFragment instanceof IExpressionFragment && !Checks.isInsideJavadoc(selectedFragment.getAssociatedNode())) {
fSelectedExpression= (IExpressionFragment) selectedFragment;
} else if (selectedFragment != null) {
if (selectedFragment.getAssociatedNode() instanceof ExpressionStatement) {
ExpressionStatement exprStatement= (ExpressionStatement) selectedFragment.getAssociatedNode();
Expression expression= exprStatement.getExpression();
fSelectedExpression= (IExpressionFragment) ASTFragmentFactory.createFragmentForFullSubtree(expression);
} else if (selectedFragment.getAssociatedNode() instanceof Assignment) {
Assignment assignment= (Assignment) selectedFragment.getAssociatedNode();
fSelectedExpression= (IExpressionFragment) ASTFragmentFactory.createFragmentForFullSubtree(assignment);
}
}
if (fSelectedExpression != null && Checks.isEnumCase(fSelectedExpression.getAssociatedExpression().getParent())) {
fSelectedExpression= null;
}
return fSelectedExpression;
}
private static ASTNode checkNode(ASTNode node) {
if (node == null)
return null;
if (node.getNodeType() == ASTNode.SIMPLE_NAME) {
node= node.getParent();
} else if (node.getNodeType() == ASTNode.EXPRESSION_STATEMENT) {
node= ((ExpressionStatement)node).getExpression();
}
switch(node.getNodeType()) {
case ASTNode.METHOD_DECLARATION:
case ASTNode.METHOD_INVOCATION:
// not yet...
// case ASTNode.SUPER_METHOD_INVOCATION:
// case ASTNode.CONSTRUCTOR_INVOCATION:
return node;
}
return null;
}
private static ASTNode checkNode(ASTNode node) {
if (node == null)
return null;
if (node.getNodeType() == ASTNode.SIMPLE_NAME) {
node= node.getParent();
} else if (node.getNodeType() == ASTNode.EXPRESSION_STATEMENT) {
node= ((ExpressionStatement) node).getExpression();
}
switch (node.getNodeType()) {
case ASTNode.METHOD_INVOCATION:
case ASTNode.METHOD_DECLARATION:
case ASTNode.SUPER_METHOD_INVOCATION:
return node;
}
return null;
}
private static boolean canReplace(IASTFragment fragment) {
ASTNode node= fragment.getAssociatedNode();
ASTNode parent= node.getParent();
if (parent instanceof VariableDeclarationFragment) {
VariableDeclarationFragment vdf= (VariableDeclarationFragment) parent;
if (node.equals(vdf.getName()))
return false;
}
if (parent instanceof ExpressionStatement)
return false;
if (parent instanceof SwitchCase) {
if (node instanceof Name) {
Name name= (Name) node;
ITypeBinding typeBinding= name.resolveTypeBinding();
if (typeBinding != null) {
return !typeBinding.isEnum();
}
}
}
return true;
}
@Override
public boolean visit(PostfixExpression node) {
Expression operand= node.getOperand();
if (!considerBinding(resolveBinding(operand), operand))
return true;
ASTNode parent= node.getParent();
if (!(parent instanceof ExpressionStatement)) {
fStatus.addError(RefactoringCoreMessages.SelfEncapsulateField_AccessAnalyzer_cannot_convert_postfix_expression,
JavaStatusContext.create(fCUnit, SourceRangeFactory.create(node)));
return false;
}
fRewriter.replace(node,
createInvocation(node.getAST(), node.getOperand(), node.getOperator().toString()),
createGroupDescription(POSTFIX_ACCESS));
return false;
}
private MethodDeclaration getWritingConstructor(SimpleName name) {
Assignment assignement= (Assignment)ASTNodes.getParent(name, Assignment.class);
if (assignement == null)
return null;
ASTNode expression= assignement.getParent();
if (!(expression instanceof ExpressionStatement))
return null;
ASTNode block= expression.getParent();
if (!(block instanceof Block))
return null;
ASTNode methodDeclaration= block.getParent();
if (!(methodDeclaration instanceof MethodDeclaration))
return null;
return (MethodDeclaration)methodDeclaration;
}
private void removeVariableWithInitializer(ASTRewrite rewrite, ASTNode initializerNode, ASTNode statementNode, TextEditGroup group) {
boolean performRemove= fForceRemove;
if (!performRemove) {
ArrayList<Expression> sideEffectNodes= new ArrayList<Expression>();
initializerNode.accept(new SideEffectFinder(sideEffectNodes));
performRemove= sideEffectNodes.isEmpty();
}
if (performRemove) {
removeStatement(rewrite, statementNode, group);
fRemovedAssignmentsCount++;
} else {
ASTNode initNode = rewrite.createMoveTarget(initializerNode);
ExpressionStatement statement = rewrite.getAST().newExpressionStatement((Expression) initNode);
rewrite.replace(statementNode, statement, null);
fAlteredAssignmentsCount++;
}
}
public AssignToVariableAssistProposal(ICompilationUnit cu, int variableKind, ExpressionStatement node, ITypeBinding typeBinding, int relevance) {
super("", cu, null, relevance, null); //$NON-NLS-1$
fVariableKind= variableKind;
fNodeToAssign= node;
if (typeBinding.isWildcardType()) {
typeBinding= ASTResolving.normalizeWildcardType(typeBinding, true, node.getAST());
}
fTypeBinding= typeBinding;
if (variableKind == LOCAL) {
setDisplayName(CorrectionMessages.AssignToVariableAssistProposal_assigntolocal_description);
setImage(JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_LOCAL));
} else {
setDisplayName(CorrectionMessages.AssignToVariableAssistProposal_assigntofield_description);
setImage(JavaPluginImages.get(JavaPluginImages.IMG_FIELD_PRIVATE));
}
createImportRewrite((CompilationUnit) node.getRoot());
}
public FieldInstructionObject isSetter() {
if(getMethodBody() != null) {
List<AbstractStatement> abstractStatements = getMethodBody().getCompositeStatement().getStatements();
if(abstractStatements.size() == 1 && abstractStatements.get(0) instanceof StatementObject) {
StatementObject statementObject = (StatementObject)abstractStatements.get(0);
Statement statement = statementObject.getStatement();
if(statement instanceof ExpressionStatement) {
ExpressionStatement expressionStatement = (ExpressionStatement)statement;
if(expressionStatement.getExpression() instanceof Assignment && statementObject.getFieldInstructions().size() == 1 && statementObject.getMethodInvocations().size() == 0 &&
statementObject.getLocalVariableDeclarations().size() == 0 && statementObject.getLocalVariableInstructions().size() == 1 && this.constructorObject.parameterList.size() == 1) {
Assignment assignment = (Assignment)expressionStatement.getExpression();
if((assignment.getLeftHandSide() instanceof SimpleName || assignment.getLeftHandSide() instanceof FieldAccess) && assignment.getRightHandSide() instanceof SimpleName)
return statementObject.getFieldInstructions().get(0);
}
}
}
}
return null;
}
public boolean isVoidMethodCallDifferenceCoveringEntireStatement() {
boolean expression1IsVoidMethodCallDifference = false;
boolean expression2IsVoidMethodCallDifference = false;
for(ASTNodeDifference difference : nodeDifferences) {
Expression expr1 = ASTNodeDifference.getParentExpressionOfMethodNameOrTypeName(difference.getExpression1().getExpression());
Expression expr2 = ASTNodeDifference.getParentExpressionOfMethodNameOrTypeName(difference.getExpression2().getExpression());
for(PreconditionViolation violation : getPreconditionViolations()) {
if(violation instanceof ExpressionPreconditionViolation && violation.getType().equals(PreconditionViolationType.EXPRESSION_DIFFERENCE_IS_VOID_METHOD_CALL)) {
ExpressionPreconditionViolation expressionViolation = (ExpressionPreconditionViolation)violation;
Expression expression = ASTNodeDifference.getParentExpressionOfMethodNameOrTypeName(expressionViolation.getExpression().getExpression());
if(expression.equals(expr1)) {
if(expr1.getParent() instanceof ExpressionStatement) {
expression1IsVoidMethodCallDifference = true;
}
}
if(expression.equals(expr2)) {
if(expr2.getParent() instanceof ExpressionStatement) {
expression2IsVoidMethodCallDifference = true;
}
}
}
}
}
return expression1IsVoidMethodCallDifference && expression2IsVoidMethodCallDifference;
}
private static Statement genPrinter(Expression expression) {
MethodInvocation methodInvocation = ast.newMethodInvocation();
methodInvocation.setExpression(ast.newName("System.out"));
methodInvocation.setName(ast.newSimpleName("println"));
methodInvocation.arguments().add(expression);
ExpressionStatement expressionStatement = ast.newExpressionStatement(methodInvocation);
return expressionStatement;
}
public boolean visit(ExpressionStatement node) {
int start = _unit.getLineNumber(node.getStartPosition());
if(start == _extendedLine){
_extendedStatement = node;
return false;
}
return true;
}
private ExpressionStmt visit(ExpressionStatement node) {
int startLine = _cunit.getLineNumber(node.getStartPosition());
int endLine = _cunit.getLineNumber(node.getStartPosition() + node.getLength());
ExpressionStmt expressionStmt = new ExpressionStmt(startLine, endLine, node);
Expr expression = (Expr) process(node.getExpression());
expression.setParent(expressionStmt);
expressionStmt.setExpression(expression);
return expressionStmt;
}
private static Block getBlockBodyForLambda(Expression bodyExpr, ITypeBinding returnTypeBinding, AST ast) {
Statement statementInBlockBody;
if (ast.resolveWellKnownType("void").isEqualTo(returnTypeBinding)) { //$NON-NLS-1$
ExpressionStatement expressionStatement = ast.newExpressionStatement(bodyExpr);
statementInBlockBody = expressionStatement;
} else {
ReturnStatement returnStatement = ast.newReturnStatement();
returnStatement.setExpression(bodyExpr);
statementInBlockBody = returnStatement;
}
Block blockBody = ast.newBlock();
blockBody.statements().add(statementInBlockBody);
return blockBody;
}
public static CUCorrectionProposal getAssignVariableProposal(CodeActionParams params, IInvocationContext context, boolean problemsAtLocation, Map formatterOptions, boolean returnAsCommand,
IProblemLocationCore[] locations)
throws CoreException {
ASTNode node = context.getCoveringNode();
Statement statement = ASTResolving.findParentStatement(node);
if (!(statement instanceof ExpressionStatement)) {
return null;
}
ExpressionStatement expressionStatement = (ExpressionStatement) statement;
Expression expression = expressionStatement.getExpression();
if (expression.getNodeType() == ASTNode.ASSIGNMENT) {
return null;
}
ITypeBinding typeBinding = expression.resolveTypeBinding();
typeBinding = Bindings.normalizeTypeBinding(typeBinding);
if (typeBinding == null) {
return null;
}
if (containsMatchingProblem(locations, IProblem.UnusedObjectAllocation)) {
return null;
}
final ICompilationUnit cu = context.getCompilationUnit();
int relevance;
if (context.getSelectionLength() == 0) {
relevance = IProposalRelevance.EXTRACT_LOCAL_ZERO_SELECTION;
} else if (problemsAtLocation) {
relevance = IProposalRelevance.EXTRACT_LOCAL_ERROR;
} else {
relevance = IProposalRelevance.EXTRACT_LOCAL;
}
if (returnAsCommand) {
return new AssignToVariableAssistCommandProposal(cu, JavaCodeActionKind.REFACTOR_ASSIGN_VARIABLE, AssignToVariableAssistProposal.LOCAL, expressionStatement, typeBinding, relevance, APPLY_REFACTORING_COMMAND_ID,
Arrays.asList(ASSIGN_VARIABLE_COMMAND, params));
} else {
return new AssignToVariableAssistProposal(cu, JavaCodeActionKind.REFACTOR_ASSIGN_VARIABLE, AssignToVariableAssistProposal.LOCAL, expressionStatement, typeBinding, relevance);
}
}
public static CUCorrectionProposal getAssignFieldProposal(CodeActionParams params, IInvocationContext context, boolean problemsAtLocation, Map formatterOptions, boolean returnAsCommand,
IProblemLocationCore[] locations) throws CoreException {
ASTNode node = context.getCoveringNode();
Statement statement = ASTResolving.findParentStatement(node);
if (!(statement instanceof ExpressionStatement)) {
return null;
}
ExpressionStatement expressionStatement = (ExpressionStatement) statement;
Expression expression = expressionStatement.getExpression();
if (expression.getNodeType() == ASTNode.ASSIGNMENT) {
return null;
}
ITypeBinding typeBinding = expression.resolveTypeBinding();
typeBinding = Bindings.normalizeTypeBinding(typeBinding);
if (typeBinding == null) {
return null;
}
if (containsMatchingProblem(locations, IProblem.UnusedObjectAllocation)) {
return null;
}
final ICompilationUnit cu = context.getCompilationUnit();
ASTNode type = ASTResolving.findParentType(expression);
if (type != null) {
int relevance;
if (context.getSelectionLength() == 0) {
relevance = IProposalRelevance.EXTRACT_LOCAL_ZERO_SELECTION;
} else if (problemsAtLocation) {
relevance = IProposalRelevance.EXTRACT_LOCAL_ERROR;
} else {
relevance = IProposalRelevance.EXTRACT_LOCAL;
}
if (returnAsCommand) {
return new AssignToVariableAssistCommandProposal(cu, JavaCodeActionKind.REFACTOR_ASSIGN_FIELD, AssignToVariableAssistProposal.FIELD, expressionStatement, typeBinding, relevance, APPLY_REFACTORING_COMMAND_ID,
Arrays.asList(ASSIGN_FIELD_COMMAND, params));
} else {
return new AssignToVariableAssistProposal(cu, JavaCodeActionKind.REFACTOR_ASSIGN_FIELD, AssignToVariableAssistProposal.FIELD, expressionStatement, typeBinding, relevance);
}
}
return null;
}
@Override
public void endVisit(ExpressionStatement node) {
if (skipNode(node)) {
return;
}
assignFlowInfo(node, node.getExpression());
}
private static boolean canReplace(IASTFragment fragment) {
ASTNode node = fragment.getAssociatedNode();
ASTNode parent = node.getParent();
if (parent instanceof VariableDeclarationFragment) {
VariableDeclarationFragment vdf = (VariableDeclarationFragment) parent;
if (node.equals(vdf.getName())) {
return false;
}
}
if (isMethodParameter(node)) {
return false;
}
if (isThrowableInCatchBlock(node)) {
return false;
}
if (parent instanceof ExpressionStatement) {
return false;
}
if (parent instanceof LambdaExpression) {
return false;
}
if (isLeftValue(node)) {
return false;
}
if (isReferringToLocalVariableFromFor((Expression) node)) {
return false;
}
if (isUsedInForInitializerOrUpdater((Expression) node)) {
return false;
}
if (parent instanceof SwitchCase) {
return false;
}
return true;
}
private void replaceSelectedExpressionWithTempDeclaration() throws CoreException {
ASTRewrite rewrite = fCURewrite.getASTRewrite();
Expression selectedExpression = getSelectedExpression().getAssociatedExpression(); // whole expression selected
Expression initializer = (Expression) rewrite.createMoveTarget(selectedExpression);
VariableDeclarationStatement tempDeclaration = createTempDeclaration(initializer);
ASTNode replacement;
ASTNode parent = selectedExpression.getParent();
boolean isParentLambda = parent instanceof LambdaExpression;
AST ast = rewrite.getAST();
if (isParentLambda) {
Block blockBody = ast.newBlock();
blockBody.statements().add(tempDeclaration);
if (!Bindings.isVoidType(((LambdaExpression) parent).resolveMethodBinding().getReturnType())) {
List<VariableDeclarationFragment> fragments = tempDeclaration.fragments();
SimpleName varName = fragments.get(0).getName();
ReturnStatement returnStatement = ast.newReturnStatement();
returnStatement.setExpression(ast.newSimpleName(varName.getIdentifier()));
blockBody.statements().add(returnStatement);
}
replacement = blockBody;
} else if (ASTNodes.isControlStatementBody(parent.getLocationInParent())) {
Block block = ast.newBlock();
block.statements().add(tempDeclaration);
replacement = block;
} else {
replacement = tempDeclaration;
}
ASTNode replacee = isParentLambda || !ASTNodes.hasSemicolon((ExpressionStatement) parent, fCu) ? selectedExpression : parent;
rewrite.replace(replacee, replacement, fCURewrite.createGroupDescription(RefactoringCoreMessages.ExtractTempRefactoring_declare_local_variable));
}
private boolean shouldReplaceSelectedExpressionWithTempDeclaration() throws JavaModelException {
IExpressionFragment selectedFragment = getSelectedExpression();
IExpressionFragment firstExpression = getFirstReplacedExpression();
if (firstExpression.getStartPosition() < selectedFragment.getStartPosition()) {
return false;
}
ASTNode associatedNode = selectedFragment.getAssociatedNode();
return (associatedNode.getParent() instanceof ExpressionStatement || associatedNode.getParent() instanceof LambdaExpression) && selectedFragment.matches(ASTFragmentFactory.createFragmentForFullSubtree(associatedNode));
}
private static boolean canReplace(IASTFragment fragment) {
ASTNode node = fragment.getAssociatedNode();
ASTNode parent = node.getParent();
if (parent instanceof VariableDeclarationFragment) {
VariableDeclarationFragment vdf = (VariableDeclarationFragment) parent;
if (node.equals(vdf.getName())) {
return false;
}
}
if (isMethodParameter(node)) {
return false;
}
if (isThrowableInCatchBlock(node)) {
return false;
}
if (parent instanceof ExpressionStatement) {
return false;
}
if (parent instanceof LambdaExpression) {
return false;
}
if (isLeftValue(node)) {
return false;
}
if (isReferringToLocalVariableFromFor((Expression) node)) {
return false;
}
if (isUsedInForInitializerOrUpdater((Expression) node)) {
return false;
}
if (parent instanceof SwitchCase) {
return false;
}
return true;
}
private static ASTNode[] getNodesToDelete(IJavaElement element, CompilationUnit cuNode) throws JavaModelException {
// fields are different because you don't delete the whole declaration but only a fragment of it
if (element.getElementType() == IJavaElement.FIELD) {
if (JdtFlags.isEnum((IField) element)) {
return new ASTNode[] { ASTNodeSearchUtil.getEnumConstantDeclaration((IField) element, cuNode)};
} else {
return new ASTNode[] { ASTNodeSearchUtil.getFieldDeclarationFragmentNode((IField) element, cuNode)};
}
}
if (element.getElementType() == IJavaElement.TYPE && ((IType) element).isLocal()) {
IType type= (IType) element;
if (type.isAnonymous()) {
if (type.getParent().getElementType() == IJavaElement.FIELD) {
EnumConstantDeclaration enumDecl= ASTNodeSearchUtil.getEnumConstantDeclaration((IField) element.getParent(), cuNode);
if (enumDecl != null && enumDecl.getAnonymousClassDeclaration() != null) {
return new ASTNode[] { enumDecl.getAnonymousClassDeclaration() };
}
}
ClassInstanceCreation creation= ASTNodeSearchUtil.getClassInstanceCreationNode(type, cuNode);
if (creation != null) {
if (creation.getLocationInParent() == ExpressionStatement.EXPRESSION_PROPERTY) {
return new ASTNode[] { creation.getParent() };
} else if (creation.getLocationInParent() == VariableDeclarationFragment.INITIALIZER_PROPERTY) {
return new ASTNode[] { creation};
}
return new ASTNode[] { creation.getAnonymousClassDeclaration() };
}
return new ASTNode[0];
} else {
ASTNode[] nodes= ASTNodeSearchUtil.getDeclarationNodes(element, cuNode);
// we have to delete the TypeDeclarationStatement
nodes[0]= nodes[0].getParent();
return nodes;
}
}
return ASTNodeSearchUtil.getDeclarationNodes(element, cuNode);
}