下面列出了怎么用org.eclipse.jdt.core.dom.EnhancedForStatement的API类实例代码及写法,或者点击链接到github查看源代码。
public boolean visit(SingleVariableDeclaration node){
ASTNode parent = node.getParent();
while(parent != null){
if(parent instanceof Block || parent instanceof ForStatement || parent instanceof IfStatement || parent instanceof EnhancedForStatement || parent instanceof WhileStatement){
break;
}
parent = parent.getParent();
}
if(parent != null) {
int start = _unit.getLineNumber(node.getStartPosition());
int end = _unit.getLineNumber(parent.getStartPosition() + parent.getLength());
Pair<String, Type> pair = new Pair<String, Type>(node.getName().getFullyQualifiedName(), node.getType());
Pair<Integer, Integer> range = new Pair<Integer, Integer>(start, end);
_tmpVars.put(pair, range);
}
return true;
}
private EnhancedForStmt visit(EnhancedForStatement node) {
int startLine = _cunit.getLineNumber(node.getStartPosition());
int endLine = _cunit.getLineNumber(node.getStartPosition() + node.getLength());
EnhancedForStmt enhancedForStmt = new EnhancedForStmt(startLine, endLine, node);
Svd svd = (Svd) process(node.getParameter());
svd.setParent(enhancedForStmt);
enhancedForStmt.setParameter(svd);
Expr expression = (Expr) process(node.getExpression());
expression.setParent(enhancedForStmt);
enhancedForStmt.setExpression(expression);
Stmt body = (Stmt) process(node.getBody());
body.setParent(enhancedForStmt);
enhancedForStmt.setBody(body);
return enhancedForStmt;
}
@Override
public void endVisit(EnhancedForStatement node) {
if (skipNode(node)) {
return;
}
FlowInfo paramInfo = getFlowInfo(node.getParameter());
FlowInfo expressionInfo = getFlowInfo(node.getExpression());
FlowInfo actionInfo = getFlowInfo(node.getBody());
EnhancedForFlowInfo forInfo = createEnhancedFor();
setFlowInfo(node, forInfo);
// If the for statement is the outermost loop then we only have to consider
// the action. The parameter and expression are only evaluated once.
if (node == fLoopNode) {
forInfo.mergeAction(actionInfo, fFlowContext);
} else {
// Inner for loops are evaluated in the sequence expression, parameter,
// action.
forInfo.mergeExpression(expressionInfo, fFlowContext);
forInfo.mergeParameter(paramInfo, fFlowContext);
forInfo.mergeAction(actionInfo, fFlowContext);
}
forInfo.removeLabel(null);
}
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;
}
private static void addEnhancedForWithoutTypeProposals(ICompilationUnit cu, ASTNode selectedNode,
Collection<ChangeCorrectionProposal> proposals) {
if (selectedNode instanceof SimpleName && (selectedNode.getLocationInParent() == SimpleType.NAME_PROPERTY || selectedNode.getLocationInParent() == NameQualifiedType.NAME_PROPERTY)) {
ASTNode type= selectedNode.getParent();
if (type.getLocationInParent() == SingleVariableDeclaration.TYPE_PROPERTY) {
SingleVariableDeclaration svd= (SingleVariableDeclaration) type.getParent();
if (svd.getLocationInParent() == EnhancedForStatement.PARAMETER_PROPERTY) {
if (svd.getName().getLength() == 0) {
SimpleName simpleName= (SimpleName) selectedNode;
String name= simpleName.getIdentifier();
int relevance= StubUtility.hasLocalVariableName(cu.getJavaProject(), name) ? 10 : 7;
String label= Messages.format(CorrectionMessages.UnresolvedElementsSubProcessor_create_loop_variable_description, BasicElementLabels.getJavaElementName(name));
proposals.add(new NewVariableCorrectionProposal(label, cu, NewVariableCorrectionProposal.LOCAL,
simpleName, null, relevance));
}
}
}
}
}
@Override
public boolean preNext(Statement curElement) {
switch (curElement.getNodeType()) {
case ASTNode.WHILE_STATEMENT:
exportWhile((WhileStatement) curElement);
break;
case ASTNode.FOR_STATEMENT:
exportFor((ForStatement) curElement);
break;
case ASTNode.ENHANCED_FOR_STATEMENT:
exportForEach((EnhancedForStatement) curElement);
break;
case ASTNode.DO_STATEMENT:
exportDoWhileStatement((DoStatement) curElement);
break;
}
return true;
}
@Override
public void endVisit(EnhancedForStatement node) {
if (skipNode(node))
return;
FlowInfo paramInfo= getFlowInfo(node.getParameter());
FlowInfo expressionInfo= getFlowInfo(node.getExpression());
FlowInfo actionInfo= getFlowInfo(node.getBody());
EnhancedForFlowInfo forInfo= createEnhancedFor();
setFlowInfo(node, forInfo);
// If the for statement is the outermost loop then we only have to consider
// the action. The parameter and expression are only evaluated once.
if (node == fLoopNode) {
forInfo.mergeAction(actionInfo, fFlowContext);
} else {
// Inner for loops are evaluated in the sequence expression, parameter,
// action.
forInfo.mergeExpression(expressionInfo, fFlowContext);
forInfo.mergeParameter(paramInfo, fFlowContext);
forInfo.mergeAction(actionInfo, fFlowContext);
}
forInfo.removeLabel(null);
}
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;
}
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 static void addEnhancedForWithoutTypeProposals(ICompilationUnit cu, ASTNode selectedNode, Collection<ICommandAccess> proposals) {
if (selectedNode instanceof SimpleName && (selectedNode.getLocationInParent() == SimpleType.NAME_PROPERTY || selectedNode.getLocationInParent() == NameQualifiedType.NAME_PROPERTY)) {
ASTNode type= selectedNode.getParent();
if (type.getLocationInParent() == SingleVariableDeclaration.TYPE_PROPERTY) {
SingleVariableDeclaration svd= (SingleVariableDeclaration) type.getParent();
if (svd.getLocationInParent() == EnhancedForStatement.PARAMETER_PROPERTY) {
if (svd.getName().getLength() == 0) {
SimpleName simpleName= (SimpleName) selectedNode;
String name= simpleName.getIdentifier();
int relevance= StubUtility.hasLocalVariableName(cu.getJavaProject(), name) ? 10 : 7;
String label= Messages.format(CorrectionMessages.UnresolvedElementsSubProcessor_create_loop_variable_description, BasicElementLabels.getJavaElementName(name));
Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_LOCAL);
proposals.add(new NewVariableCorrectionProposal(label, cu, NewVariableCorrectionProposal.LOCAL, simpleName, null, relevance, image));
}
}
}
}
}
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;
}
public boolean match(EnhancedForStatement node, Object other) {
if (other instanceof EnhancedForStatement)
{
EnhancedForStatement o = (EnhancedForStatement) other;
if(isNestedUnderAnonymousClassDeclaration(node) && isNestedUnderAnonymousClassDeclaration(o)) {
return super.match(node, o);
}
boolean paramMatch = safeSubtreeMatch(node.getParameter(), o.getParameter());
boolean expMatch = safeSubtreeMatch(node.getExpression(), o.getExpression());
if (paramMatch && expMatch)
{
return true;
}
}
EnhancedForLoop nodeEnhancedForLoop = new EnhancedForLoop(node);
return loopMatch(nodeEnhancedForLoop, other);
}
private static AbstractLoop generateAbstractLoop(Object object)
{
if (object instanceof ForStatement)
{
return new ConditionalLoop((ForStatement) object);
}
else if (object instanceof WhileStatement)
{
return new ConditionalLoop((WhileStatement) object);
}
else if (object instanceof DoStatement)
{
return new ConditionalLoop((DoStatement) object);
}
else if (object instanceof EnhancedForStatement)
{
return new EnhancedForLoop((EnhancedForStatement) object);
}
return null;
}
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;
}
public boolean visit(EnhancedForStatement stmnt) {
/*
* for ( FormalParameter : Expression )
Statement
*/
styledString.append("for", new StyledStringStyler(keywordStyle));
appendSpace();
appendOpenParenthesis();
SingleVariableDeclaration variableDeclaration = stmnt.getParameter();
handleType(variableDeclaration.getType());
appendSpace();
handleExpression(variableDeclaration.getName());
appendSpace();
appendColon();
appendSpace();
handleExpression(stmnt.getExpression());
appendClosedParenthesis();
return false;
}
public boolean visit(EnhancedForStatement node) {
int start = _unit.getLineNumber(node.getExpression().getStartPosition());
if(start == _extendedLine){
_extendedStatement = node;
return false;
}
return true;
}
@Override
public void endVisit(EnhancedForStatement node) {
if (skipNode(node)) {
return;
}
EnhancedForFlowInfo forInfo = createEnhancedFor();
setFlowInfo(node, forInfo);
forInfo.mergeParameter(getFlowInfo(node.getParameter()), fFlowContext);
forInfo.mergeExpression(getFlowInfo(node.getExpression()), fFlowContext);
forInfo.mergeAction(getFlowInfo(node.getBody()), fFlowContext);
forInfo.removeLabel(null);
}
@Override
public void endVisit(EnhancedForStatement node) {
if (getSelection().getEndVisitSelectionMode(node) == Selection.AFTER) {
if (node.getParameter() == getFirstSelectedNode()) {
invalidSelection(RefactoringCoreMessages.ExtractMethodAnalyzer_cannot_extract_for_initializer, JavaStatusContext.create(fCUnit, getSelection()));
}
}
super.endVisit(node);
}
private boolean isEnhancedForStatementVariable(Statement statement, SimpleName name) {
if (statement instanceof EnhancedForStatement) {
EnhancedForStatement forStatement= (EnhancedForStatement) statement;
SingleVariableDeclaration param= forStatement.getParameter();
return param.getType() == name.getParent(); // strange recovery, see https://bugs.eclipse.org/180456
}
return false;
}
@Override
public boolean visit(final SingleVariableDeclaration it) {
if ((((it.getParent() instanceof MethodDeclaration) || (it.getParent() instanceof CatchClause)) ||
(it.getParent() instanceof EnhancedForStatement))) {
final Function1<IExtendedModifier, Boolean> _function = (IExtendedModifier it_1) -> {
return Boolean.valueOf(it_1.isAnnotation());
};
this.appendModifiers(it, IterableExtensions.<IExtendedModifier>filter(Iterables.<IExtendedModifier>filter(it.modifiers(), IExtendedModifier.class), _function));
} else {
this.appendModifiers(it, it.modifiers());
}
it.getType().accept(this);
this.appendExtraDimensions(it.getExtraDimensions());
boolean _isVarargs = it.isVarargs();
if (_isVarargs) {
this.appendToBuffer("...");
}
this.appendSpaceToBuffer();
it.getName().accept(this);
Expression _initializer = it.getInitializer();
boolean _tripleNotEquals = (_initializer != null);
if (_tripleNotEquals) {
this.appendToBuffer("=");
it.getInitializer().accept(this);
}
return false;
}
@Override
public boolean visit(final EnhancedForStatement node) {
this.appendToBuffer("for (");
node.getParameter().accept(this);
this.appendToBuffer(" : ");
node.getExpression().accept(this);
this.appendToBuffer(") ");
node.getBody().accept(this);
return false;
}
private EnhancedForStatement findParentEnhancedForStatement(ASTNode node) {
ASTNode parent = node.getParent();
while(parent != null) {
if(parent instanceof EnhancedForStatement) {
return (EnhancedForStatement)parent;
}
parent = parent.getParent();
}
return null;
}
/**
* Handles for ( Object x : list ) 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(EnhancedForStatement node) {
if (importer.topFromContainerStack(Method.class) != null) {
importer.topFromContainerStack(Method.class).incCyclomaticComplexity();
importer.createAccessFromExpression((Expression) node.getExpression());
}
return true;
}
public boolean isDangligIf() {
List<Statement> statements= fDeclaration.getBody().statements();
if (statements.size() != 1)
return false;
ASTNode p= statements.get(0);
while (true) {
if (p instanceof IfStatement) {
return ((IfStatement) p).getElseStatement() == null;
} else {
ChildPropertyDescriptor childD;
if (p instanceof WhileStatement) {
childD= WhileStatement.BODY_PROPERTY;
} else if (p instanceof ForStatement) {
childD= ForStatement.BODY_PROPERTY;
} else if (p instanceof EnhancedForStatement) {
childD= EnhancedForStatement.BODY_PROPERTY;
} else if (p instanceof DoStatement) {
childD= DoStatement.BODY_PROPERTY;
} else if (p instanceof LabeledStatement) {
childD= LabeledStatement.BODY_PROPERTY;
} else {
return false;
}
Statement body= (Statement) p.getStructuralProperty(childD);
if (body instanceof Block) {
return false;
} else {
p= body;
}
}
}
}
@Override
public void endVisit(EnhancedForStatement node) {
if (skipNode(node))
return;
EnhancedForFlowInfo forInfo= createEnhancedFor();
setFlowInfo(node, forInfo);
forInfo.mergeParameter(getFlowInfo(node.getParameter()), fFlowContext);
forInfo.mergeExpression(getFlowInfo(node.getExpression()), fFlowContext);
forInfo.mergeAction(getFlowInfo(node.getBody()), fFlowContext);
forInfo.removeLabel(null);
}
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(EnhancedForStatement node) {
if (getSelection().getEndVisitSelectionMode(node) == Selection.AFTER) {
if (node.getParameter() == getFirstSelectedNode()) {
invalidSelection(RefactoringCoreMessages.ExtractMethodAnalyzer_cannot_extract_for_initializer, JavaStatusContext.create(fCUnit, getSelection()));
}
}
super.endVisit(node);
}
/**
* Returns true if a node at a given location is a body of a control statement. Such body nodes are
* interesting as when replacing them, it has to be evaluates if a Block is needed instead.
* E.g. <code> if (x) do(); -> if (x) { do1(); do2() } </code>
*
* @param locationInParent Location of the body node
* @return Returns true if the location is a body node location of a control statement.
*/
public static boolean isControlStatementBody(StructuralPropertyDescriptor locationInParent) {
return locationInParent == IfStatement.THEN_STATEMENT_PROPERTY
|| locationInParent == IfStatement.ELSE_STATEMENT_PROPERTY
|| locationInParent == ForStatement.BODY_PROPERTY
|| locationInParent == EnhancedForStatement.BODY_PROPERTY
|| locationInParent == WhileStatement.BODY_PROPERTY
|| locationInParent == DoStatement.BODY_PROPERTY;
}
/**
* {@inheritDoc}
*/
@Override
public boolean visit(EnhancedForStatement node) {
handle(node.getBody(), EnhancedForStatement.BODY_PROPERTY);
return super.visit(node);
}
@Override
protected Statement convert(CompilationUnitRewrite cuRewrite, TextEditGroup group, LinkedProposalModel positionGroups) throws CoreException {
ASTRewrite rewrite= cuRewrite.getASTRewrite();
ImportRewrite importRewrite= cuRewrite.getImportRewrite();
ForStatement forStatement= getForStatement();
IJavaProject javaProject= ((CompilationUnit)forStatement.getRoot()).getJavaElement().getJavaProject();
String[] proposals= getVariableNameProposals(fArrayAccess.resolveTypeBinding(), javaProject);
String parameterName;
if (fElementDeclaration != null) {
parameterName= fElementDeclaration.getName().getIdentifier();
} else {
parameterName= proposals[0];
}
LinkedProposalPositionGroup pg= positionGroups.getPositionGroup(parameterName, true);
if (fElementDeclaration != null)
pg.addProposal(parameterName, null, 10);
for (int i= 0; i < proposals.length; i++) {
pg.addProposal(proposals[i], null, 10);
}
AST ast= forStatement.getAST();
EnhancedForStatement result= ast.newEnhancedForStatement();
SingleVariableDeclaration parameterDeclaration= createParameterDeclaration(parameterName, fElementDeclaration, fArrayAccess, forStatement, importRewrite, rewrite, group, pg, fMakeFinal);
result.setParameter(parameterDeclaration);
result.setExpression((Expression)rewrite.createCopyTarget(fArrayAccess));
convertBody(forStatement.getBody(), fIndexBinding, fArrayBinding, parameterName, rewrite, group, pg);
result.setBody(getBody(cuRewrite, group, positionGroups));
positionGroups.setEndPosition(rewrite.track(result));
return result;
}