private void findUnnecessaryStore(ReturnStatement node) { Block block = TraversalUtil.findClosestAncestor(node, Block.class); @SuppressWarnings("unchecked") List<Statement> blockStatements = block.statements(); for (int i = 1; i < blockStatements.size(); i++) { Statement statement = blockStatements.get(i); if (statement == this.originalReturn) { for (int j = i - 1; j >= 0; j--) { Statement storeStatement = blockStatements.get(j); if (storeStatement instanceof VariableDeclarationStatement) { splitStatementAndInitializer((VariableDeclarationStatement) storeStatement); return; } else if (storeStatement instanceof ExpressionStatement) { if (splitStatementAndInitializer((ExpressionStatement) storeStatement)) { // we found our extra storage statement return; } } } } } }
/** * Method that check statement type. * @author Mariana Azevedo * @since 13/07/2014 * @param itStatement */ private void getStatementType(Object itStatement) { if (itStatement instanceof CatchClause){ this.visitor.visit((CatchClause)itStatement); }else if (itStatement instanceof ForStatement){ this.visitor.visit((ForStatement)itStatement); }else if (itStatement instanceof IfStatement){ this.visitor.visit((IfStatement)itStatement); }else if (itStatement instanceof WhileStatement){ this.visitor.visit((WhileStatement)itStatement); }else if (itStatement instanceof TryStatement){ this.visitor.visit((TryStatement)itStatement); }else if (itStatement instanceof ConditionalExpression){ this.visitor.visit((ConditionalExpression)itStatement); }else if (itStatement instanceof SwitchCase){ this.visitor.visit((SwitchCase)itStatement); }else if (itStatement instanceof DoStatement){ this.visitor.visit((DoStatement)itStatement); }else if (itStatement instanceof ExpressionStatement){ this.visitor.visit((ExpressionStatement)itStatement); } }
private void splitUpDeclarations(ASTRewrite rewrite, TextEditGroup group, VariableDeclarationFragment frag, VariableDeclarationStatement originalStatement, List<Expression> sideEffects) { if (sideEffects.size() > 0) { ListRewrite statementRewrite= rewrite.getListRewrite(originalStatement.getParent(), (ChildListPropertyDescriptor) originalStatement.getLocationInParent()); Statement previousStatement= originalStatement; for (int i= 0; i < sideEffects.size(); i++) { Expression sideEffect= sideEffects.get(i); Expression movedInit= (Expression) rewrite.createMoveTarget(sideEffect); ExpressionStatement wrapped= rewrite.getAST().newExpressionStatement(movedInit); statementRewrite.insertAfter(wrapped, previousStatement, group); previousStatement= wrapped; } VariableDeclarationStatement newDeclaration= null; List<VariableDeclarationFragment> fragments= originalStatement.fragments(); int fragIndex= fragments.indexOf(frag); ListIterator<VariableDeclarationFragment> fragmentIterator= fragments.listIterator(fragIndex+1); while (fragmentIterator.hasNext()) { VariableDeclarationFragment currentFragment= fragmentIterator.next(); VariableDeclarationFragment movedFragment= (VariableDeclarationFragment) rewrite.createMoveTarget(currentFragment); if (newDeclaration == null) { newDeclaration= rewrite.getAST().newVariableDeclarationStatement(movedFragment); Type copiedType= (Type) rewrite.createCopyTarget(originalStatement.getType()); newDeclaration.setType(copiedType); } else { newDeclaration.fragments().add(movedFragment); } } if (newDeclaration != null){ statementRewrite.insertAfter(newDeclaration, previousStatement, group); if (originalStatement.fragments().size() == newDeclaration.fragments().size() + 1){ rewrite.remove(originalStatement, group); } } } }
private void removeVariableWithInitializer(ASTRewrite rewrite, ASTNode initializerNode, ASTNode statementNode, TextEditGroup group) { boolean performRemove= fForceRemove; if (!performRemove) { ArrayList<Expression> sideEffectNodes= new ArrayList<>(); 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++; } }
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++; } }
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 void replaceSelectedExpressionWithTempDeclaration() throws CoreException { ASTRewrite rewrite = fCURewrite.getASTRewrite(); Expression selectedExpression = getSelectedExpression().getAssociatedExpression(); // whole expression selected Expression initializer = (Expression) rewrite.createMoveTarget(selectedExpression); ASTNode replacement = createTempDeclaration(initializer); // creates a VariableDeclarationStatement ExpressionStatement parent = (ExpressionStatement) selectedExpression.getParent(); if (ASTNodes.isControlStatementBody(parent.getLocationInParent())) { Block block = rewrite.getAST().newBlock(); block.statements().add(replacement); replacement = block; } rewrite.replace( parent, replacement, fCURewrite.createGroupDescription( RefactoringCoreMessages.ExtractTempRefactoring_declare_local_variable)); }
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 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; }
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()); }
private ASTRewrite doAddLocal() { Expression expression = ((ExpressionStatement) fNodeToAssign).getExpression(); AST ast = fNodeToAssign.getAST(); ASTRewrite rewrite = ASTRewrite.create(ast); createImportRewrite((CompilationUnit) fNodeToAssign.getRoot()); String[] varNames = suggestLocalVariableNames(fTypeBinding, expression); for (int i = 0; i < varNames.length; i++) { addLinkedPositionProposal(KEY_NAME, varNames[i], null); } VariableDeclarationFragment newDeclFrag = ast.newVariableDeclarationFragment(); newDeclFrag.setName(ast.newSimpleName(varNames[0])); newDeclFrag.setInitializer((Expression) rewrite.createCopyTarget(expression)); Type type = evaluateType(ast); if (ASTNodes.isControlStatementBody(fNodeToAssign.getLocationInParent())) { Block block = ast.newBlock(); block.statements().add(rewrite.createMoveTarget(fNodeToAssign)); rewrite.replace(fNodeToAssign, block, null); } if (needsSemicolon(expression)) { VariableDeclarationStatement varStatement = ast.newVariableDeclarationStatement(newDeclFrag); varStatement.setType(type); rewrite.replace(expression, varStatement, null); } else { // trick for bug 43248: use an VariableDeclarationExpression and keep the ExpressionStatement VariableDeclarationExpression varExpression = ast.newVariableDeclarationExpression(newDeclFrag); varExpression.setType(type); rewrite.replace(expression, varExpression, null); } addLinkedPosition(rewrite.track(newDeclFrag.getName()), true, KEY_NAME); addLinkedPosition(rewrite.track(type), false, KEY_TYPE); setEndPosition(rewrite.track(fNodeToAssign)); // set cursor after expression statement return rewrite; }
private VariableReference retrieveVariableReference( ClassInstanceCreation instanceCreation, Class<?> varType) { if ((instanceCreation.getParent() instanceof MethodInvocation) || (instanceCreation.getParent() instanceof ClassInstanceCreation)) { VariableReference result = new ValidVariableReference( testCase.getReference(), retrieveTypeClass(instanceCreation.getType())); nestedCallResults.push(result); return result; } if ((instanceCreation.getParent() instanceof ExpressionStatement) && (instanceCreation.getParent().getParent() instanceof Block)) { if (varType == null) { varType = retrieveTypeClass(instanceCreation); } VariableReference varRef = new ValidVariableReference( testCase.getReference(), varType); return varRef; } return retrieveVariableReference(instanceCreation.getParent(), varType); }
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 void replaceSelectedExpressionWithTempDeclaration() throws CoreException { ASTRewrite rewrite= fCURewrite.getASTRewrite(); Expression selectedExpression= getSelectedExpression().getAssociatedExpression(); // whole expression selected Expression initializer= (Expression) rewrite.createMoveTarget(selectedExpression); ASTNode replacement= createTempDeclaration(initializer); // creates a VariableDeclarationStatement ExpressionStatement parent= (ExpressionStatement) selectedExpression.getParent(); if (ASTNodes.isControlStatementBody(parent.getLocationInParent())) { Block block= rewrite.getAST().newBlock(); block.statements().add(replacement); replacement= block; } rewrite.replace(parent, replacement, fCURewrite.createGroupDescription(RefactoringCoreMessages.ExtractTempRefactoring_declare_local_variable)); }
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()); }
private ASTNode prepareLambdaBody(Block body, List<Statement> statements) { ASTNode lambdaBody = body; if (statements.size() == 1) { // use short form with just an expression body if possible Statement statement = statements.get(0); if (statement instanceof ExpressionStatement) { lambdaBody = ((ExpressionStatement) statement).getExpression(); } else if (statement instanceof ReturnStatement) { Expression returnExpression = ((ReturnStatement) statement).getExpression(); if (returnExpression != null) { lambdaBody = returnExpression; } } } return lambdaBody; }
/** * Returns all statements within a method. * * @return Set of all statements */ private ArraySet<AbstractJavaStatement> statements() { final List<AbstractJavaStatement> list = new ArrayList<AbstractJavaStatement>(); methodDeclaration.accept(new ASTVisitor() { @Override public boolean visit(ExpressionStatement node) { if (node.getExpression() instanceof MethodInvocation) { MethodInvocation methodInvocation = (MethodInvocation) node.getExpression(); String methodName = methodInvocation.getName().toString(); if (null != methodInvocation.getExpression()) { ITypeBinding typeBinding = methodInvocation.getExpression().resolveTypeBinding(); if (null != typeBinding) { JavaCall javaCall = new JavaCall(node, methodName, typeBinding, JavaMethod.this); list.add(javaCall); } } } return false; } }); return new ArraySet<AbstractJavaStatement>(list.toArray(new JavaCall[list.size()]), JavaCall.class); }
/** * Returns all statements within a method. * * @return Set of all statements */ private ArraySet<AbstractJavaStatement> assignments() { final List<AbstractJavaStatement> list = new ArrayList<AbstractJavaStatement>(); methodDeclaration.accept(new ASTVisitor() { @Override public boolean visit(Assignment node) { Expression lhs = node.getLeftHandSide(); ITypeBinding typeBinding = lhs.resolveTypeBinding(); Expression rhs = node.getRightHandSide(); if (rhs instanceof ClassInstanceCreation && node.getParent() instanceof ExpressionStatement) { ExpressionStatement parent = (ExpressionStatement) node.getParent(); JavaAssignment assignment = new JavaAssignment(JavaMethod.this, parent, lhs.toString(), typeBinding, (ClassInstanceCreation) rhs); list.add(assignment); } // TODO SE: (Static) method invocations, e.g. call of another // factory are not supported. return false; } }); return new ArraySet<AbstractJavaStatement>(list.toArray(new JavaAssignment[list.size()]), JavaAssignment.class); }
public boolean visit(final ExpressionStatement node) { if (node.getExpression() instanceof MethodInvocation) { final MethodInvocation method = (MethodInvocation)node.getExpression(); Expression expression; for (expression = method.getExpression(); expression instanceof MethodInvocation; expression = ((MethodInvocation)expression).getExpression()) {} final IVariableBinding field = this.getLocalField(expression); if (field != null) { MethodAnalyzer.this.setFields.add(field); } int index = this.getVariableIndex(method.getExpression()); if (index != -1) { MethodAnalyzer.this.variables.get(index).setModified(true); } else { index = this.getParameterIndex(method.getExpression()); if (index != -1) { MethodAnalyzer.this.parameters.get(index).setModified(true); } } if (this.isLocalMethod(method)) { MethodAnalyzer.this.invokedLocalMethods.add(method.resolveMethodBinding()); } } return super.visit(node); }
private void splitUpDeclarations(ASTRewrite rewrite, TextEditGroup group, VariableDeclarationFragment frag, ListRewrite statementRewrite, VariableDeclarationStatement originalStatement) { Expression initializer = frag.getInitializer(); //keep constructors and method invocations if (initializer instanceof MethodInvocation || initializer instanceof ClassInstanceCreation){ Expression movedInitializer= (Expression) rewrite.createMoveTarget(initializer); ExpressionStatement newInitializer= rewrite.getAST().newExpressionStatement( movedInitializer); statementRewrite.insertAfter(newInitializer, originalStatement, group); VariableDeclarationStatement newDeclaration= null; List<VariableDeclarationFragment> fragments= originalStatement.fragments(); int fragIndex= fragments.indexOf(frag); ListIterator<VariableDeclarationFragment> fragmentIterator= fragments.listIterator(fragIndex+1); while (fragmentIterator.hasNext()) { VariableDeclarationFragment currentFragment= fragmentIterator.next(); VariableDeclarationFragment movedFragment= (VariableDeclarationFragment) rewrite.createMoveTarget(currentFragment); if (newDeclaration == null) { newDeclaration= rewrite.getAST().newVariableDeclarationStatement(movedFragment); Type copiedType= (Type) rewrite.createCopyTarget(originalStatement.getType()); newDeclaration.setType(copiedType); } else newDeclaration.fragments().add(movedFragment); } if (newDeclaration != null){ statementRewrite.insertAfter(newDeclaration, newInitializer, group); } if (originalStatement.fragments().size() == newDeclaration.fragments().size() + 1){ rewrite.remove(originalStatement, group); } } }