下面列出了怎么用org.eclipse.jdt.core.dom.ForStatement的API类实例代码及写法,或者点击链接到github查看源代码。
public boolean visit(ForStatement node) {
int position = 0;
if(node.getExpression() != null){
position = node.getExpression().getStartPosition();
} else if(node.initializers() != null && node.initializers().size() > 0){
position = ((ASTNode)node.initializers().get(0)).getStartPosition();
} else if(node.updaters() != null && node.updaters().size() > 0){
position = ((ASTNode)node.updaters().get(0)).getStartPosition();
}
int start = _unit.getLineNumber(position);
if(start == _extendedLine){
_extendedStatement = node;
return false;
}
return true;
}
public boolean visit(VariableDeclarationExpression node) {
ASTNode parent = node.getParent();
while(parent != null){
if(parent instanceof Block || parent instanceof ForStatement){
break;
}
parent = parent.getParent();
}
if(parent != null) {
int start = _unit.getLineNumber(node.getStartPosition());
int end = _unit.getLineNumber(parent.getStartPosition() + parent.getLength());
for (Object o : node.fragments()) {
VariableDeclarationFragment vdf = (VariableDeclarationFragment) o;
Pair<String, Type> pair = new Pair<String, Type>(vdf.getName().getFullyQualifiedName(), node.getType());
Pair<Integer, Integer> range = new Pair<Integer, Integer>(start, end);
_tmpVars.put(pair, range);
}
}
return true;
}
public Statement getLoopBody()
{
if (loopStatement instanceof WhileStatement)
{
return ((WhileStatement)loopStatement).getBody();
}
else if (loopStatement instanceof ForStatement)
{
return ((ForStatement)loopStatement).getBody();
}
else if (loopStatement instanceof DoStatement)
{
return ((DoStatement)loopStatement).getBody();
}
else if (loopStatement instanceof EnhancedForStatement)
{
return ((EnhancedForStatement)loopStatement).getBody();
}
return null;
}
@Override
public boolean visit(final ForStatement it) {
this.appendToBuffer("for (");
this.visitAll(it.initializers());
this.appendToBuffer("; ");
Expression _expression = it.getExpression();
boolean _tripleNotEquals = (_expression != null);
if (_tripleNotEquals) {
it.getExpression().accept(this);
}
this.appendToBuffer("; ");
this.visitAll(it.updaters());
this.appendToBuffer(") ");
it.getBody().accept(this);
return false;
}
private void checkSendInLoopNode(Statement loopNode) {
Statement body;
if (loopNode instanceof WhileStatement) {
WhileStatement whileLoop = (WhileStatement) loopNode;
body = whileLoop.getBody();
} else if (loopNode instanceof ForStatement) {
ForStatement forLoop = (ForStatement) loopNode;
body = forLoop.getBody();
} else {
DoStatement doWhileLoop = (DoStatement) loopNode;
body = doWhileLoop.getBody();
}
boolean showErrorHere = placeOfError == loopNode;
if (showErrorHere) {
placeOfError = body;
}
if (body instanceof Block) {
checkSendInBlock((Block) body, showErrorHere);
} else {
checkSendInStatement(body);
}
}
private RefactoringStatus checkSelection(VariableDeclaration decl) {
ASTNode parent= decl.getParent();
if (parent instanceof MethodDeclaration) {
return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.InlineTempRefactoring_method_parameter);
}
if (parent instanceof CatchClause) {
return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.InlineTempRefactoring_exceptions_declared);
}
if (parent instanceof VariableDeclarationExpression && parent.getLocationInParent() == ForStatement.INITIALIZERS_PROPERTY) {
return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.InlineTempRefactoring_for_initializers);
}
if (parent instanceof VariableDeclarationExpression && parent.getLocationInParent() == TryStatement.RESOURCES_PROPERTY) {
return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.InlineTempRefactoring_resource_in_try_with_resources);
}
if (decl.getInitializer() == null) {
String message= Messages.format(RefactoringCoreMessages.InlineTempRefactoring_not_initialized, BasicElementLabels.getJavaElementName(decl.getName().getIdentifier()));
return RefactoringStatus.createFatalErrorStatus(message);
}
return checkAssignments(decl);
}
private boolean isSingleControlStatementWithoutBlock() {
List<Statement> statements= fDeclaration.getBody().statements();
int size= statements.size();
if (size != 1)
return false;
Statement statement= statements.get(size - 1);
int nodeType= statement.getNodeType();
if (nodeType == ASTNode.IF_STATEMENT) {
IfStatement ifStatement= (IfStatement) statement;
return !(ifStatement.getThenStatement() instanceof Block)
&& !(ifStatement.getElseStatement() instanceof Block);
} else if (nodeType == ASTNode.FOR_STATEMENT) {
return !(((ForStatement)statement).getBody() instanceof Block);
} else if (nodeType == ASTNode.WHILE_STATEMENT) {
return !(((WhileStatement)statement).getBody() instanceof Block);
}
return false;
}
private Statement getParentLoopBody(ASTNode node) {
Statement stmt= null;
ASTNode start= node;
while (start != null
&& !(start instanceof ForStatement)
&& !(start instanceof DoStatement)
&& !(start instanceof WhileStatement)
&& !(start instanceof EnhancedForStatement)
&& !(start instanceof SwitchStatement)) {
start= start.getParent();
}
if (start instanceof ForStatement) {
stmt= ((ForStatement)start).getBody();
} else if (start instanceof DoStatement) {
stmt= ((DoStatement)start).getBody();
} else if (start instanceof WhileStatement) {
stmt= ((WhileStatement)start).getBody();
} else if (start instanceof EnhancedForStatement) {
stmt= ((EnhancedForStatement)start).getBody();
}
if (start != null && start.getParent() instanceof LabeledStatement) {
LabeledStatement labeledStatement= (LabeledStatement)start.getParent();
fEnclosingLoopLabel= labeledStatement.getLabel();
}
return stmt;
}
/**
* Helper to generate an index based <code>for</code> loop to iterate over a {@link List}
* implementation.
*
* @param ast the current {@link AST} instance to generate the {@link ASTRewrite} for
* @return an applicable {@link ASTRewrite} instance
*/
private ASTRewrite generateIndexBasedForRewrite(AST ast) {
ASTRewrite rewrite= ASTRewrite.create(ast);
ForStatement loopStatement= ast.newForStatement();
SimpleName loopVariableName= resolveLinkedVariableNameWithProposals(rewrite, "int", null, true); //$NON-NLS-1$
loopStatement.initializers().add(getForInitializer(ast, loopVariableName));
MethodInvocation listSizeExpression= ast.newMethodInvocation();
listSizeExpression.setName(ast.newSimpleName("size")); //$NON-NLS-1$
Expression listExpression= (Expression) rewrite.createCopyTarget(fCurrentExpression);
listSizeExpression.setExpression(listExpression);
loopStatement.setExpression(getLinkedInfixExpression(rewrite, loopVariableName.getIdentifier(), listSizeExpression, InfixExpression.Operator.LESS));
loopStatement.updaters().add(getLinkedIncrementExpression(rewrite, loopVariableName.getIdentifier()));
Block forLoopBody= ast.newBlock();
forLoopBody.statements().add(ast.newExpressionStatement(getIndexBasedForBodyAssignment(rewrite, loopVariableName)));
forLoopBody.statements().add(createBlankLineStatementWithCursorPosition(rewrite));
loopStatement.setBody(forLoopBody);
rewrite.replace(fCurrentNode, loopStatement, null);
return rewrite;
}
@Override
public void endVisit(ForStatement node) {
ASTNode[] selectedNodes= getSelectedNodes();
if (doAfterValidation(node, selectedNodes)) {
boolean containsExpression= contains(selectedNodes, node.getExpression());
boolean containsUpdaters= contains(selectedNodes, node.updaters());
if (contains(selectedNodes, node.initializers()) && containsExpression) {
invalidSelection(RefactoringCoreMessages.StatementAnalyzer_for_initializer_expression);
} else if (containsExpression && containsUpdaters) {
invalidSelection(RefactoringCoreMessages.StatementAnalyzer_for_expression_updater);
} else if (containsUpdaters && contains(selectedNodes, node.getBody())) {
invalidSelection(RefactoringCoreMessages.StatementAnalyzer_for_updater_body);
}
}
super.endVisit(node);
}
private static boolean locationNeedsParentheses(StructuralPropertyDescriptor locationInParent) {
if (locationInParent instanceof ChildListPropertyDescriptor && locationInParent != InfixExpression.EXTENDED_OPERANDS_PROPERTY) {
// e.g. argument lists of MethodInvocation, ClassInstanceCreation, dimensions of ArrayCreation ...
return false;
}
if (locationInParent == VariableDeclarationFragment.INITIALIZER_PROPERTY
|| locationInParent == SingleVariableDeclaration.INITIALIZER_PROPERTY
|| locationInParent == ReturnStatement.EXPRESSION_PROPERTY
|| locationInParent == EnhancedForStatement.EXPRESSION_PROPERTY
|| locationInParent == ForStatement.EXPRESSION_PROPERTY
|| locationInParent == WhileStatement.EXPRESSION_PROPERTY
|| locationInParent == DoStatement.EXPRESSION_PROPERTY
|| locationInParent == AssertStatement.EXPRESSION_PROPERTY
|| locationInParent == AssertStatement.MESSAGE_PROPERTY
|| locationInParent == IfStatement.EXPRESSION_PROPERTY
|| locationInParent == SwitchStatement.EXPRESSION_PROPERTY
|| locationInParent == SwitchCase.EXPRESSION_PROPERTY
|| locationInParent == ArrayAccess.INDEX_PROPERTY
|| locationInParent == ThrowStatement.EXPRESSION_PROPERTY
|| locationInParent == SynchronizedStatement.EXPRESSION_PROPERTY
|| locationInParent == ParenthesizedExpression.EXPRESSION_PROPERTY) {
return false;
}
return true;
}
private ConvertLoopOperation getConvertOperation(ForStatement node) {
Collection<String> usedNamesCollection= fUsedNames.values();
String[] usedNames= usedNamesCollection.toArray(new String[usedNamesCollection.size()]);
ConvertLoopOperation convertForLoopOperation= new ConvertForLoopOperation(node, usedNames, fMakeFinal);
if (convertForLoopOperation.satisfiesPreconditions().isOK()) {
if (fFindForLoopsToConvert) {
fUsedNames.put(node, convertForLoopOperation.getIntroducedVariableName());
return convertForLoopOperation;
}
} else if (fConvertIterableForLoops) {
ConvertLoopOperation iterableConverter= new ConvertIterableLoopOperation(node, usedNames, fMakeFinal);
if (iterableConverter.satisfiesPreconditions().isOK()) {
fUsedNames.put(node, iterableConverter.getIntroducedVariableName());
return iterableConverter;
}
}
return null;
}
@Override
public IStatus satisfiesPreconditions() {
ForStatement statement= getForStatement();
CompilationUnit ast= (CompilationUnit)statement.getRoot();
IJavaElement javaElement= ast.getJavaElement();
if (javaElement == null)
return ERROR_STATUS;
if (!JavaModelUtil.is50OrHigher(javaElement.getJavaProject()))
return ERROR_STATUS;
if (!validateInitializers(statement))
return ERROR_STATUS;
if (!validateExpression(statement))
return ERROR_STATUS;
if (!validateUpdaters(statement))
return ERROR_STATUS;
if (!validateBody(statement))
return ERROR_STATUS;
return Status.OK_STATUS;
}
private static boolean getConvertForLoopProposal(IInvocationContext context, ASTNode node, Collection<ICommandAccess> resultingCollections) {
ForStatement forStatement= getEnclosingForStatementHeader(node);
if (forStatement == null)
return false;
if (resultingCollections == null)
return true;
IProposableFix fix= ConvertLoopFix.createConvertForLoopToEnhancedFix(context.getASTRoot(), forStatement);
if (fix == null)
return false;
Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE);
Map<String, String> options= new HashMap<String, String>();
options.put(CleanUpConstants.CONTROL_STATMENTS_CONVERT_FOR_LOOP_TO_ENHANCED, CleanUpOptions.TRUE);
ICleanUp cleanUp= new ConvertLoopCleanUp(options);
FixCorrectionProposal proposal= new FixCorrectionProposal(fix, cleanUp, IProposalRelevance.CONVERT_FOR_LOOP_TO_ENHANCED, image, context);
proposal.setCommandId(CONVERT_FOR_LOOP_ID);
resultingCollections.add(proposal);
return true;
}
private static boolean getConvertIterableLoopProposal(IInvocationContext context, ASTNode node, Collection<ICommandAccess> resultingCollections) {
ForStatement forStatement= getEnclosingForStatementHeader(node);
if (forStatement == null)
return false;
if (resultingCollections == null)
return true;
IProposableFix fix= ConvertLoopFix.createConvertIterableLoopToEnhancedFix(context.getASTRoot(), forStatement);
if (fix == null)
return false;
Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_CHANGE);
Map<String, String> options= new HashMap<String, String>();
options.put(CleanUpConstants.CONTROL_STATMENTS_CONVERT_FOR_LOOP_TO_ENHANCED, CleanUpOptions.TRUE);
ICleanUp cleanUp= new ConvertLoopCleanUp(options);
FixCorrectionProposal proposal= new FixCorrectionProposal(fix, cleanUp, IProposalRelevance.CONVERT_ITERABLE_LOOP_TO_ENHANCED, image, context);
proposal.setCommandId(CONVERT_FOR_LOOP_ID);
resultingCollections.add(proposal);
return true;
}
private static boolean isLastStatementInEnclosingMethodOrLambda(Statement statement) {
ASTNode currentStructure= statement;
ASTNode currentParent= statement.getParent();
while (!(currentParent instanceof MethodDeclaration || currentParent instanceof LambdaExpression)) {
// should not be in a loop
if (currentParent instanceof ForStatement || currentParent instanceof EnhancedForStatement
|| currentParent instanceof WhileStatement || currentParent instanceof DoStatement) {
return false;
}
if (currentParent instanceof Block) {
Block parentBlock= (Block) currentParent;
if (parentBlock.statements().indexOf(currentStructure) != parentBlock.statements().size() - 1) { // not last statement in the block
return false;
}
}
currentStructure= currentParent;
currentParent= currentParent.getParent();
}
return true;
}
/**
* Helper to generate an index based <code>for</code> loop to iterate over an array.
*
* @param ast the current {@link AST} instance to generate the {@link ASTRewrite} for
* @return an applicable {@link ASTRewrite} instance
*/
private ASTRewrite generateForRewrite(AST ast) {
ASTRewrite rewrite= ASTRewrite.create(ast);
ForStatement loopStatement= ast.newForStatement();
SimpleName loopVariableName= resolveLinkedVariableNameWithProposals(rewrite, "int", null, true); //$NON-NLS-1$
loopStatement.initializers().add(getForInitializer(ast, loopVariableName));
FieldAccess getArrayLengthExpression= ast.newFieldAccess();
getArrayLengthExpression.setExpression((Expression) rewrite.createCopyTarget(fCurrentExpression));
getArrayLengthExpression.setName(ast.newSimpleName("length")); //$NON-NLS-1$
loopStatement.setExpression(getLinkedInfixExpression(rewrite, loopVariableName.getIdentifier(), getArrayLengthExpression, InfixExpression.Operator.LESS));
loopStatement.updaters().add(getLinkedIncrementExpression(rewrite, loopVariableName.getIdentifier()));
Block forLoopBody= ast.newBlock();
forLoopBody.statements().add(ast.newExpressionStatement(getForBodyAssignment(rewrite, loopVariableName)));
forLoopBody.statements().add(createBlankLineStatementWithCursorPosition(rewrite));
loopStatement.setBody(forLoopBody);
rewrite.replace(fCurrentNode, loopStatement, null);
return rewrite;
}
@Override
public void endVisit(ForStatement node) {
if (skipNode(node)) {
return;
}
FlowInfo initInfo = createSequential(node.initializers());
FlowInfo conditionInfo = getFlowInfo(node.getExpression());
FlowInfo incrementInfo = createSequential(node.updaters());
FlowInfo actionInfo = getFlowInfo(node.getBody());
ForFlowInfo forInfo = createFor();
setFlowInfo(node, forInfo);
// the for statement is the outermost loop. In this case we only have
// to consider the increment, condition and action.
if (node == fLoopNode) {
forInfo.mergeIncrement(incrementInfo, fFlowContext);
forInfo.mergeCondition(conditionInfo, fFlowContext);
forInfo.mergeAction(actionInfo, fFlowContext);
} else {
// we have to merge two different cases. One if we reenter the for statement
// immediatelly (that means we have to consider increments, condition and action)
// and the other case if we reenter the for in the next loop of
// the outer loop. Then we have to consider initializations, condtion and action.
// For a conditional flow info that means:
// (initializations | increments) & condition & action.
GenericConditionalFlowInfo initIncr = new GenericConditionalFlowInfo();
initIncr.merge(initInfo, fFlowContext);
initIncr.merge(incrementInfo, fFlowContext);
forInfo.mergeAccessModeSequential(initIncr, fFlowContext);
forInfo.mergeCondition(conditionInfo, fFlowContext);
forInfo.mergeAction(actionInfo, fFlowContext);
}
forInfo.removeLabel(null);
}
private static boolean isUsedInForInitializerOrUpdater(Expression expression) {
ASTNode parent = expression.getParent();
if (parent instanceof ForStatement) {
ForStatement forStmt = (ForStatement) parent;
return forStmt.initializers().contains(expression) || forStmt.updaters().contains(expression);
}
return false;
}
private boolean isLoop(CompositeStatementObject compositeStatement) {
if(compositeStatement.getStatement() instanceof WhileStatement ||
compositeStatement.getStatement() instanceof ForStatement ||
compositeStatement.getStatement() instanceof EnhancedForStatement)
return true;
return false;
}
private static Expression getBooleanExpression(ASTNode node) {
if (!(node instanceof Expression)) {
return null;
}
// check if the node is a location where it can be negated
StructuralPropertyDescriptor locationInParent = node.getLocationInParent();
if (locationInParent == QualifiedName.NAME_PROPERTY) {
node = node.getParent();
locationInParent = node.getLocationInParent();
}
while (locationInParent == ParenthesizedExpression.EXPRESSION_PROPERTY) {
node = node.getParent();
locationInParent = node.getLocationInParent();
}
Expression expression = (Expression) node;
if (!isBoolean(expression)) {
return null;
}
if (expression.getParent() instanceof InfixExpression) {
return expression;
}
if (locationInParent == Assignment.RIGHT_HAND_SIDE_PROPERTY || locationInParent == IfStatement.EXPRESSION_PROPERTY || locationInParent == WhileStatement.EXPRESSION_PROPERTY || locationInParent == DoStatement.EXPRESSION_PROPERTY
|| locationInParent == ReturnStatement.EXPRESSION_PROPERTY || locationInParent == ForStatement.EXPRESSION_PROPERTY || locationInParent == AssertStatement.EXPRESSION_PROPERTY
|| locationInParent == MethodInvocation.ARGUMENTS_PROPERTY || locationInParent == ConstructorInvocation.ARGUMENTS_PROPERTY || locationInParent == SuperMethodInvocation.ARGUMENTS_PROPERTY
|| locationInParent == EnumConstantDeclaration.ARGUMENTS_PROPERTY || locationInParent == SuperConstructorInvocation.ARGUMENTS_PROPERTY || locationInParent == ClassInstanceCreation.ARGUMENTS_PROPERTY
|| locationInParent == ConditionalExpression.EXPRESSION_PROPERTY || locationInParent == PrefixExpression.OPERAND_PROPERTY) {
return expression;
}
return null;
}
private boolean isForStatementInit(Statement statement, SimpleName name) {
if (statement instanceof ForStatement) {
ForStatement forStatement= (ForStatement) statement;
List<Expression> list = forStatement.initializers();
if (list.size() == 1 && list.get(0) instanceof Assignment) {
Assignment assignment= (Assignment) list.get(0);
return assignment.getLeftHandSide() == name;
}
}
return false;
}
@Override
public void write(ForStatement forStatement) {
matchAndWrite("for");
copySpaceAndComments();
matchAndWrite("(");
writeCommaDelimitedNodes(forStatement.initializers());
copySpaceAndComments();
matchAndWrite(";");
Expression forExpression = forStatement.getExpression();
if (forExpression != null) {
copySpaceAndComments();
writeNode(forStatement.getExpression());
}
copySpaceAndComments();
matchAndWrite(";");
writeCommaDelimitedNodes(forStatement.updaters());
copySpaceAndComments();
matchAndWrite(")");
copySpaceAndComments();
writeNode(forStatement.getBody());
}
/**
* Handles for (int i = init; i < n; i++)
*
* We create this access explicitly to catch a boolean variable used in
* condition. Complicated expressions are handled in
* {@link #visit(InfixExpression)}
*/
@Override
public boolean visit(ForStatement node) {
if (importer.topFromContainerStack(Method.class) != null) {
importer.topFromContainerStack(Method.class).incCyclomaticComplexity();
importer.createAccessFromExpression((Expression) node.getExpression());
}
return true;
}
protected boolean isInfixExpressionWithCompositeParent(ASTNode node) {
if(node instanceof InfixExpression &&
(node.getParent() instanceof IfStatement || node.getParent() instanceof InfixExpression ||
node.getParent() instanceof WhileStatement || node.getParent() instanceof DoStatement ||
node.getParent() instanceof ForStatement)) {
return true;
}
return false;
}
@Override
public void endVisit(ForStatement node) {
if (skipNode(node))
return;
FlowInfo initInfo= createSequential(node.initializers());
FlowInfo conditionInfo= getFlowInfo(node.getExpression());
FlowInfo incrementInfo= createSequential(node.updaters());
FlowInfo actionInfo= getFlowInfo(node.getBody());
ForFlowInfo forInfo= createFor();
setFlowInfo(node, forInfo);
// the for statement is the outermost loop. In this case we only have
// to consider the increment, condition and action.
if (node == fLoopNode) {
forInfo.mergeIncrement(incrementInfo, fFlowContext);
forInfo.mergeCondition(conditionInfo, fFlowContext);
forInfo.mergeAction(actionInfo, fFlowContext);
} else {
// we have to merge two different cases. One if we reenter the for statement
// immediatelly (that means we have to consider increments, condition and action)
// and the other case if we reenter the for in the next loop of
// the outer loop. Then we have to consider initializations, condtion and action.
// For a conditional flow info that means:
// (initializations | increments) & condition & action.
GenericConditionalFlowInfo initIncr= new GenericConditionalFlowInfo();
initIncr.merge(initInfo, fFlowContext);
initIncr.merge(incrementInfo, fFlowContext);
forInfo.mergeAccessModeSequential(initIncr, fFlowContext);
forInfo.mergeCondition(conditionInfo, fFlowContext);
forInfo.mergeAction(actionInfo, fFlowContext);
}
forInfo.removeLabel(null);
}
@Override
public void endVisit(ForStatement node) {
if (skipNode(node))
return;
ForFlowInfo forInfo= createFor();
setFlowInfo(node, forInfo);
forInfo.mergeInitializer(createSequential(node.initializers()), fFlowContext);
forInfo.mergeCondition(getFlowInfo(node.getExpression()), fFlowContext);
forInfo.mergeAction(getFlowInfo(node.getBody()), fFlowContext);
// Increments are executed after the action.
forInfo.mergeIncrement(createSequential(node.updaters()), fFlowContext);
forInfo.removeLabel(null);
}
private static boolean isUsedInForInitializerOrUpdater(Expression expression) {
ASTNode parent= expression.getParent();
if (parent instanceof ForStatement) {
ForStatement forStmt= (ForStatement) parent;
return forStmt.initializers().contains(expression) || forStmt.updaters().contains(expression);
}
return false;
}
private void insertAt(ASTNode target, Statement declaration) {
ASTRewrite rewrite= fCURewrite.getASTRewrite();
TextEditGroup groupDescription= fCURewrite.createGroupDescription(RefactoringCoreMessages.ExtractTempRefactoring_declare_local_variable);
ASTNode parent= target.getParent();
StructuralPropertyDescriptor locationInParent= target.getLocationInParent();
while (locationInParent != Block.STATEMENTS_PROPERTY && locationInParent != SwitchStatement.STATEMENTS_PROPERTY) {
if (locationInParent == IfStatement.THEN_STATEMENT_PROPERTY
|| locationInParent == IfStatement.ELSE_STATEMENT_PROPERTY
|| locationInParent == ForStatement.BODY_PROPERTY
|| locationInParent == EnhancedForStatement.BODY_PROPERTY
|| locationInParent == DoStatement.BODY_PROPERTY
|| locationInParent == WhileStatement.BODY_PROPERTY) {
// create intermediate block if target was the body property of a control statement:
Block replacement= rewrite.getAST().newBlock();
ListRewrite replacementRewrite= rewrite.getListRewrite(replacement, Block.STATEMENTS_PROPERTY);
replacementRewrite.insertFirst(declaration, null);
replacementRewrite.insertLast(rewrite.createMoveTarget(target), null);
rewrite.replace(target, replacement, groupDescription);
return;
}
target= parent;
parent= parent.getParent();
locationInParent= target.getLocationInParent();
}
ListRewrite listRewrite= rewrite.getListRewrite(parent, (ChildListPropertyDescriptor)locationInParent);
listRewrite.insertBefore(declaration, target, groupDescription);
}
@Override
public void endVisit(ForStatement node) {
if (getSelection().getEndVisitSelectionMode(node) == Selection.AFTER) {
if (node.initializers().contains(getFirstSelectedNode())) {
invalidSelection(RefactoringCoreMessages.ExtractMethodAnalyzer_cannot_extract_for_initializer, JavaStatusContext.create(fCUnit, getSelection()));
} else if (node.updaters().contains(getLastSelectedNode())) {
invalidSelection(RefactoringCoreMessages.ExtractMethodAnalyzer_cannot_extract_for_updater, JavaStatusContext.create(fCUnit, getSelection()));
}
}
super.endVisit(node);
}