org.eclipse.jdt.core.dom.ForStatement Java Examples

The following examples show how to use org.eclipse.jdt.core.dom.ForStatement. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: GenerateForLoopAssistProposal.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * 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;
}
 
Example #2
Source File: NodeUtils.java    From SimFix with GNU General Public License v2.0 6 votes vote down vote up
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;
}
 
Example #3
Source File: AbstractLoop.java    From JDeodorant with MIT License 6 votes vote down vote up
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;
}
 
Example #4
Source File: JavaASTFlattener.java    From xtext-xtend with Eclipse Public License 2.0 6 votes vote down vote up
@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;
}
 
Example #5
Source File: SequenceDiagramVisitor.java    From txtUML with Eclipse Public License 1.0 6 votes vote down vote up
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);
	}
}
 
Example #6
Source File: InlineTempRefactoring.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
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);
}
 
Example #7
Source File: SourceProvider.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
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;
}
 
Example #8
Source File: ExtractMethodAnalyzer.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
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;
}
 
Example #9
Source File: GenerateForLoopAssistProposal.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * 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;
}
 
Example #10
Source File: NecessaryParenthesesChecker.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
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;
}
 
Example #11
Source File: CodeSearch.java    From SimFix with GNU General Public License v2.0 6 votes vote down vote up
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;
}
 
Example #12
Source File: AdvancedQuickAssistProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
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;
}
 
Example #13
Source File: QuickAssistProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
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;
}
 
Example #14
Source File: ConvertForLoopOperation.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
@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;
}
 
Example #15
Source File: ConvertLoopFix.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
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;
		}
 
Example #16
Source File: QuickAssistProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
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;
}
 
Example #17
Source File: StatementAnalyzer.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
@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);
}
 
Example #18
Source File: ConvertForLoopOperation.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public String getIntroducedVariableName() {
	if (fElementDeclaration != null) {
		return fElementDeclaration.getName().getIdentifier();
	} else {
		ForStatement forStatement= getForStatement();
		IJavaProject javaProject= ((CompilationUnit)forStatement.getRoot()).getJavaElement().getJavaProject();
		String[] proposals= getVariableNameProposals(fArrayAccess.resolveTypeBinding(), javaProject);
		return proposals[0];
	}
}
 
Example #19
Source File: ConvertForLoopOperation.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private SingleVariableDeclaration createParameterDeclaration(String parameterName, VariableDeclarationFragment fragement, Expression arrayAccess, ForStatement statement, ImportRewrite importRewrite, ASTRewrite rewrite, TextEditGroup group, LinkedProposalPositionGroup pg, boolean makeFinal) {
	CompilationUnit compilationUnit= (CompilationUnit)arrayAccess.getRoot();
	AST ast= compilationUnit.getAST();

	SingleVariableDeclaration result= ast.newSingleVariableDeclaration();

	SimpleName name= ast.newSimpleName(parameterName);
	pg.addPosition(rewrite.track(name), true);
	result.setName(name);

	ITypeBinding arrayTypeBinding= arrayAccess.resolveTypeBinding();
	Type type= importType(arrayTypeBinding.getElementType(), statement, importRewrite, compilationUnit);
	if (arrayTypeBinding.getDimensions() != 1) {
		type= ast.newArrayType(type, arrayTypeBinding.getDimensions() - 1);
	}
	result.setType(type);

	if (fragement != null) {
		VariableDeclarationStatement declaration= (VariableDeclarationStatement)fragement.getParent();
		ModifierRewrite.create(rewrite, result).copyAllModifiers(declaration, group);
	}
	if (makeFinal && (fragement == null || ASTNodes.findModifierNode(Modifier.FINAL, ASTNodes.getModifiers(fragement)) == null)) {
		ModifierRewrite.create(rewrite, result).setModifiers(Modifier.FINAL, 0, group);
	}

	return result;
}
 
Example #20
Source File: ConvertForLoopOperation.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
@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;
}
 
Example #21
Source File: AdvancedQuickAssistProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
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;
}
 
Example #22
Source File: ConvertLoopFix.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public void endVisit(ForStatement node) {
	if (fFindForLoopsToConvert || fConvertIterableForLoops) {
		fUsedNames.remove(node);
	}
	super.endVisit(node);
}
 
Example #23
Source File: ConvertLoopFix.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
public ControlStatementFinder(boolean findForLoopsToConvert, boolean convertIterableForLoops, boolean makeFinal, List<ConvertLoopOperation> resultingCollection) {
	fFindForLoopsToConvert= findForLoopsToConvert;
	fConvertIterableForLoops= convertIterableForLoops;
	fMakeFinal= makeFinal;
	fResult= resultingCollection;
	fUsedNames= new Hashtable<ForStatement, String>();
}
 
Example #24
Source File: StyledStringVisitor.java    From JDeodorant with MIT License 5 votes vote down vote up
public boolean visit(ForStatement stmnt) {
	/*
	 * for (
                       [ ForInit ];
                       [ Expression ] ;
                       [ ForUpdate ] )
                       Statement
	 */
	styledString.append("for", new StyledStringStyler(keywordStyle));
	appendSpace();
	appendOpenParenthesis();
	// Handle Initializers
	for (int i = 0; i < stmnt.initializers().size(); i++) {
		handleExpression((Expression) stmnt.initializers().get(i));
		if(i < stmnt.initializers().size() - 1) {
			appendComma();
		}
	}
	appendSemicolon();
	appendSpace();
	handleExpression(stmnt.getExpression());
	appendSemicolon();
	appendSpace();
	// Handle Updaters
	for (int i = 0; i < stmnt.updaters().size(); i++) {
		handleExpression((Expression) stmnt.updaters().get(i));
		if(i < stmnt.updaters().size() - 1) {
			appendComma();
		}
	}
	appendClosedParenthesis();
	return false;
}
 
Example #25
Source File: ScopeAnalyzer.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public boolean visit(ForStatement node) {
	if (isInside(node)) {
		node.getBody().accept(this);
		visitBackwards(node.initializers());
	}
	return false;
}
 
Example #26
Source File: ExtractMethodAnalyzer.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
@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);
}
 
Example #27
Source File: ExtractTempRefactoring.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
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);
}
 
Example #28
Source File: ExtractTempRefactoring.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
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;
}
 
Example #29
Source File: FlowAnalyzer.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
@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);
}
 
Example #30
Source File: ConvertLoopFix.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
public static ConvertLoopFix createConvertIterableLoopToEnhancedFix(CompilationUnit compilationUnit, ForStatement loop) {
	ConvertIterableLoopOperation loopConverter= new ConvertIterableLoopOperation(loop);
	IStatus status= loopConverter.satisfiesPreconditions();
	if (status.getSeverity() == IStatus.ERROR)
		return null;

	return new ConvertLoopFix(FixMessages.Java50Fix_ConvertToEnhancedForLoop_description, compilationUnit, new CompilationUnitRewriteOperation[] {loopConverter}, status);
}