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

The following examples show how to use org.eclipse.jdt.core.dom.Statement. 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: GenerateHashCodeEqualsOperation.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 7 votes vote down vote up
private Statement createAddArrayHashCode(IVariableBinding binding) {
	MethodInvocation invoc= fAst.newMethodInvocation();
	if (JavaModelUtil.is50OrHigher(fRewrite.getCu().getJavaProject())) {
		invoc.setName(fAst.newSimpleName(METHODNAME_HASH_CODE));
		invoc.setExpression(getQualifiedName(JAVA_UTIL_ARRAYS));
		invoc.arguments().add(getThisAccessForHashCode(binding.getName()));
	} else {
		invoc.setName(fAst.newSimpleName(METHODNAME_HASH_CODE));
		final IJavaElement element= fType.getJavaElement();
		if (element != null && !"".equals(element.getElementName())) //$NON-NLS-1$
			invoc.setExpression(fAst.newSimpleName(element.getElementName()));
		invoc.arguments().add(getThisAccessForHashCode(binding.getName()));
		ITypeBinding type= binding.getType().getElementType();
		if (!Bindings.isVoidType(type)) {
			if (!type.isPrimitive() || binding.getType().getDimensions() >= 2)
				type= fAst.resolveWellKnownType(JAVA_LANG_OBJECT);
			if (!fCustomHashCodeTypes.contains(type))
				fCustomHashCodeTypes.add(type);
		}
	}
	return prepareAssignment(invoc);
}
 
Example #2
Source File: StringBuilderChainGenerator.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
@Override
protected void addMemberCheckNull(Object member, boolean addSeparator) {
	IfStatement ifStatement= fAst.newIfStatement();
	ifStatement.setExpression(createInfixExpression(createMemberAccessExpression(member, true, true), Operator.NOT_EQUALS, fAst.newNullLiteral()));
	Block thenBlock= fAst.newBlock();
	flushTemporaryExpression();
	String[] arrayString= getContext().getTemplateParser().getBody();
	for (int i= 0; i < arrayString.length; i++) {
		addElement(processElement(arrayString[i], member), thenBlock);
	}
	if (addSeparator)
		addElement(getContext().getTemplateParser().getSeparator(), thenBlock);
	flushTemporaryExpression();

	if (thenBlock.statements().size() == 1 && !getContext().isForceBlocks()) {
		ifStatement.setThenStatement((Statement)ASTNode.copySubtree(fAst, (ASTNode)thenBlock.statements().get(0)));
	} else {
		ifStatement.setThenStatement(thenBlock);
	}
	toStringMethod.getBody().statements().add(ifStatement);
}
 
Example #3
Source File: OptAltFragmentExporter.java    From txtUML with Eclipse Public License 1.0 6 votes vote down vote up
@Override
public boolean preNext(IfStatement curElement) {
	Statement thenStatement = curElement.getThenStatement();
	Statement elseStatement = curElement.getElseStatement();
	Expression condition = curElement.getExpression();

	if (elseStatement == null) {
		compiler.println("opt " + condition.toString());
		return true;
	} else {
		compiler.println("alt " + condition.toString());
		thenStatement.accept(compiler);
		if (elseStatement instanceof IfStatement) {
			processAltStatement((IfStatement) elseStatement);
		} else {
			compiler.println("else");
			elseStatement.accept(compiler);
		}
		return false;
	}
}
 
Example #4
Source File: DelegateMethodCreator.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Creates the corresponding statement for the method invocation, based on
 * the return type.
 *
 * @param declaration the method declaration where the invocation statement
 *            is inserted
 * @param invocation the method invocation being encapsulated by the
 *            resulting statement
 * @return the corresponding statement
 */
protected Statement createMethodInvocation(final MethodDeclaration declaration, final MethodInvocation invocation) {
	Assert.isNotNull(declaration);
	Assert.isNotNull(invocation);
	Statement statement= null;
	final Type type= declaration.getReturnType2();
	if (type == null)
		statement= createExpressionStatement(invocation);
	else {
		if (type instanceof PrimitiveType) {
			final PrimitiveType primitive= (PrimitiveType) type;
			if (primitive.getPrimitiveTypeCode().equals(PrimitiveType.VOID))
				statement= createExpressionStatement(invocation);
			else
				statement= createReturnStatement(invocation);
		} else
			statement= createReturnStatement(invocation);
	}
	return statement;
}
 
Example #5
Source File: TypeCheckElimination.java    From JDeodorant with MIT License 6 votes vote down vote up
public double getAverageNumberOfStatements() {
	if(averageNumberOfStatements == 0) {
		List<ArrayList<Statement>> typeCheckStatements = new ArrayList<ArrayList<Statement>>(getTypeCheckStatements());
		ArrayList<Statement> defaultCaseStatements = getDefaultCaseStatements();
		if(!defaultCaseStatements.isEmpty())
			typeCheckStatements.add(defaultCaseStatements);
		StatementExtractor statementExtractor = new StatementExtractor();
		int numberOfCases = typeCheckStatements.size();
		int totalNumberOfStatements = 0;
		for(ArrayList<Statement> statements : typeCheckStatements) {
			for(Statement statement : statements) {
				totalNumberOfStatements += statementExtractor.getTotalNumberOfStatements(statement);
			}
		}
		averageNumberOfStatements = (double)totalNumberOfStatements/(double)numberOfCases;
	}
	return averageNumberOfStatements;
}
 
Example #6
Source File: ConvertForLoopOperation.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public void rewriteAST(CompilationUnitRewrite cuRewrite, LinkedProposalModel positionGroups) throws CoreException {
	TextEditGroup group= createTextEditGroup(FixMessages.Java50Fix_ConvertToEnhancedForLoop_description, cuRewrite);
	ASTRewrite rewrite= cuRewrite.getASTRewrite();

	TightSourceRangeComputer rangeComputer;
	if (rewrite.getExtendedSourceRangeComputer() instanceof TightSourceRangeComputer) {
		rangeComputer= (TightSourceRangeComputer)rewrite.getExtendedSourceRangeComputer();
	} else {
		rangeComputer= new TightSourceRangeComputer();
	}
	rangeComputer.addTightSourceNode(getForStatement());
	rewrite.setTargetSourceRangeComputer(rangeComputer);

	Statement statement= convert(cuRewrite, group, positionGroups);
	rewrite.replace(getForStatement(), statement, group);
}
 
Example #7
Source File: MethodObject.java    From JDeodorant with MIT License 6 votes vote down vote up
public FieldInstructionObject isGetter() {
	if(getMethodBody() != null) {
 	List<AbstractStatement> abstractStatements = getMethodBody().getCompositeStatement().getStatements();
 	if(abstractStatements.size() == 1 && abstractStatements.get(0) instanceof StatementObject) {
 		StatementObject statementObject = (StatementObject)abstractStatements.get(0);
 		Statement statement = statementObject.getStatement();
 		if(statement instanceof ReturnStatement) {
 			ReturnStatement returnStatement = (ReturnStatement) statement;
 			if((returnStatement.getExpression() instanceof SimpleName || returnStatement.getExpression() instanceof FieldAccess) && statementObject.getFieldInstructions().size() == 1 && statementObject.getMethodInvocations().size() == 0 &&
  				statementObject.getLocalVariableDeclarations().size() == 0 && statementObject.getLocalVariableInstructions().size() == 0 && this.constructorObject.parameterList.size() == 0) {
 				return statementObject.getFieldInstructions().get(0);
 			}
 		}
 	}
	}
	return null;
}
 
Example #8
Source File: ASTNodeMatcher.java    From JDeodorant with MIT License 6 votes vote down vote up
private static List<SimpleName> getOccurrencesOfSimpleName(ASTNode node, SimpleName simpleName)
{
	List<SimpleName> returnList = new ArrayList<SimpleName>();
	ExpressionExtractor expressionExtractor = new ExpressionExtractor();
	List<Expression> simpleNames = new ArrayList<Expression>();
	if (node instanceof Expression)
	{
		simpleNames.addAll(expressionExtractor.getVariableInstructions((Expression)node));
	}
	else if (node instanceof Statement)
	{
		simpleNames.addAll(expressionExtractor.getVariableInstructions((Statement)node));
	}
	for (Expression currentExpression : simpleNames)
	{
		SimpleName currentSimpleName = (SimpleName)currentExpression;
		IBinding currentSimpleNameBinding = currentSimpleName.resolveBinding();
		if (currentSimpleNameBinding != null && currentSimpleNameBinding.isEqualTo(simpleName.resolveBinding()))
		{
			returnList.add(currentSimpleName);
		}
	}
	return returnList;
}
 
Example #9
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 #10
Source File: PDG.java    From JDeodorant with MIT License 6 votes vote down vote up
private PDGNode findParentOfBlockNode(PDGBlockNode blockNode) {
	Statement statement = blockNode.getASTStatement();
	ASTNode parent = statement.getParent();
	while(parent instanceof Block) {
		parent = parent.getParent();
	}
	if(entryNode.getMethod().getMethodDeclaration().equals(parent)) {
		return entryNode;
	}
	for(GraphNode node : nodes) {
		PDGNode pdgNode = (PDGNode)node;
		if(pdgNode.getASTStatement().equals(parent)) {
			return pdgNode;
		}
	}
	return null;
}
 
Example #11
Source File: ExtractMethodAnalyzer.java    From eclipse.jdt.ls with Eclipse Public License 2.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 #12
Source File: SequenceDiagramVisitor.java    From txtUML with Eclipse Public License 1.0 6 votes vote down vote up
private boolean checkSendOrFragmentInBlock(Block block) {
	List<Statement> statements = (List<Statement>) block.statements();
	List<Statement> loops = Utils.getLoopNodes(statements);
	loops.forEach(loop -> {
		checkSendInLoopNode(loop);
	});
	List<IfStatement> ifNodes = Utils.getIfNodes(statements);
	ifNodes.forEach(ifNode -> {
		checkSendInIfNode(ifNode);
	});
	List<MethodInvocation> parFragments = Utils.getParFragments(statements);
	parFragments.forEach(parFragment -> {
		checkSendInPar(parFragment);
	});
	List<MethodInvocation> methodInvocations = Utils.getMethodInvocations(statements);
	final List<Boolean> containsSendOrFragment = new ArrayList<>();
	methodInvocations.forEach(methodInvocation -> {
		containsSendOrFragment.add(checkSendOrFragmentInMethodInvocation(methodInvocation));
	});
	boolean isLeaf = loops.isEmpty() && ifNodes.isEmpty() && parFragments.isEmpty();
	return !isLeaf || containsSendOrFragment.contains(true);
}
 
Example #13
Source File: SequenceDiagramVisitor.java    From txtUML with Eclipse Public License 1.0 6 votes vote down vote up
private void checkSendInIfNode(IfStatement ifNode) {
	boolean showErrorHere = placeOfError == ifNode;
	Statement thenStatement = ifNode.getThenStatement();
	if (showErrorHere) {
		placeOfError = thenStatement;
	}
	if (thenStatement instanceof Block) {
		checkSendInBlock((Block) thenStatement, showErrorHere);
	} else {
		checkSendInStatement(thenStatement);
	}
	Statement elseStatement = ifNode.getElseStatement();
	if (showErrorHere) {
		placeOfError = elseStatement;
	}
	if (elseStatement == null) {
		return;
	}
	if (elseStatement instanceof IfStatement) {
		checkSendInIfNode((IfStatement) elseStatement);
	} else if (elseStatement instanceof Block) {
		checkSendInBlock((Block) elseStatement, showErrorHere);
	} else {
		checkSendInStatement(elseStatement);
	}
}
 
Example #14
Source File: AbstractControlStructureUtilities.java    From JDeodorant with MIT License 6 votes vote down vote up
public static List<Statement> unBlock(List<Statement> statements)
{
	List<Statement> returnList = new ArrayList<Statement>();
	for (Statement currentStatement : statements)
	{
		if (currentStatement instanceof Block)
		{
			List<Statement> subList = ((Block)currentStatement).statements();
			returnList.addAll(unBlock(subList));
		}
		else
		{
			returnList.add(currentStatement);
		}
	}
	return returnList;
}
 
Example #15
Source File: StatementObject.java    From JDeodorant with MIT License 6 votes vote down vote up
public StatementObject(Statement statement, StatementType type, AbstractMethodFragment parent) {
	super(statement, type, parent);
	
	ExpressionExtractor expressionExtractor = new ExpressionExtractor();
       List<Expression> assignments = expressionExtractor.getAssignments(statement);
       List<Expression> postfixExpressions = expressionExtractor.getPostfixExpressions(statement);
       List<Expression> prefixExpressions = expressionExtractor.getPrefixExpressions(statement);
       processVariables(expressionExtractor.getVariableInstructions(statement), assignments, postfixExpressions, prefixExpressions);
	processMethodInvocations(expressionExtractor.getMethodInvocations(statement));
	processClassInstanceCreations(expressionExtractor.getClassInstanceCreations(statement));
	processArrayCreations(expressionExtractor.getArrayCreations(statement));
	//processArrayAccesses(expressionExtractor.getArrayAccesses(statement));
	processLiterals(expressionExtractor.getLiterals(statement));
	if(statement instanceof ThrowStatement) {
		processThrowStatement((ThrowStatement)statement);
	}
	if(statement instanceof ConstructorInvocation) {
		processConstructorInvocation((ConstructorInvocation)statement);
	}
}
 
Example #16
Source File: TernaryControlStructure.java    From JDeodorant with MIT License 6 votes vote down vote up
private void initializeFields(Statement node)
{
	ConditionalExpression conditionalExpression = AbstractControlStructureUtilities.hasOneConditionalExpression(node);
	if (conditionalExpression != null)
	{
		this.conditionalExpression = conditionalExpression;
		this.condition             = conditionalExpression.getExpression();
		this.thenExpression        = conditionalExpression.getThenExpression();
		this.elseExpression        = conditionalExpression.getElseExpression();
	}
	else
	{
		this.conditionalExpression = null;
		this.condition             = null;
		this.thenExpression        = null;
		this.elseExpression        = null;
	}
}
 
Example #17
Source File: StringBuilderGenerator.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
@Override
protected void addMemberCheckNull(Object member, boolean addSeparator) {
	IfStatement ifStatement= fAst.newIfStatement();
	ifStatement.setExpression(createInfixExpression(createMemberAccessExpression(member, true, true), Operator.NOT_EQUALS, fAst.newNullLiteral()));
	Block thenBlock= fAst.newBlock();
	flushBuffer(null);
	String[] arrayString= getContext().getTemplateParser().getBody();
	for (int i= 0; i < arrayString.length; i++) {
		addElement(processElement(arrayString[i], member), thenBlock);
	}
	if (addSeparator)
		addElement(getContext().getTemplateParser().getSeparator(), thenBlock);
	flushBuffer(thenBlock);

	if (thenBlock.statements().size() == 1 && !getContext().isForceBlocks()) {
		ifStatement.setThenStatement((Statement)ASTNode.copySubtree(fAst, (ASTNode)thenBlock.statements().get(0)));
	} else {
		ifStatement.setThenStatement(thenBlock);
	}
	toStringMethod.getBody().statements().add(ifStatement);
}
 
Example #18
Source File: ConvertIterableLoopOperation.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public void rewriteAST(CompilationUnitRewrite cuRewrite, LinkedProposalModel positionGroups) throws CoreException {
	final TextEditGroup group= createTextEditGroup(FixMessages.Java50Fix_ConvertToEnhancedForLoop_description, cuRewrite);

	final ASTRewrite astRewrite= cuRewrite.getASTRewrite();

	TightSourceRangeComputer rangeComputer;
	if (astRewrite.getExtendedSourceRangeComputer() instanceof TightSourceRangeComputer) {
		rangeComputer= (TightSourceRangeComputer)astRewrite.getExtendedSourceRangeComputer();
	} else {
		rangeComputer= new TightSourceRangeComputer();
	}
	rangeComputer.addTightSourceNode(getForStatement());
	astRewrite.setTargetSourceRangeComputer(rangeComputer);

	Statement statement= convert(cuRewrite, group, positionGroups);
	astRewrite.replace(getForStatement(), statement, group);
}
 
Example #19
Source File: Utils.java    From txtUML with Eclipse Public License 1.0 5 votes vote down vote up
public static List<MethodInvocation> getParFragments(List<Statement> statements) {
	List<MethodInvocation> parFragments = statements.stream().map(Utils::getMethodInvocationFromStatement)
			.filter(inv -> inv != null && inv.resolveMethodBinding() != null
					&& inv.resolveMethodBinding().getName().equals("par")
					&& isSequenceMethod(inv.resolveMethodBinding()))
			.collect(toList());
	return parFragments;
}
 
Example #20
Source File: ASTResolving.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
public static boolean isInsideConstructorInvocation(MethodDeclaration methodDeclaration, ASTNode node) {
	if (methodDeclaration.isConstructor()) {
		Statement statement= ASTResolving.findParentStatement(node);
		if (statement instanceof ConstructorInvocation || statement instanceof SuperConstructorInvocation) {
			return true; // argument in a this or super call
		}
	}
	return false;
}
 
Example #21
Source File: ASTSlice.java    From JDeodorant with MIT License 5 votes vote down vote up
public boolean isVariableCriterionDeclarationStatementIsDeeperNestedThanExtractedMethodInvocationInsertionStatement() {
	Statement variableCriterionDeclarationStatement = getVariableCriterionDeclarationStatement();
	if(variableCriterionDeclarationStatement != null) {
		int depthOfNestingForVariableCriterionDeclarationStatement = depthOfNesting(variableCriterionDeclarationStatement);
		Statement extractedMethodInvocationInsertionStatement = getExtractedMethodInvocationInsertionStatement();
		int depthOfNestingForExtractedMethodInvocationInsertionStatement = depthOfNesting(extractedMethodInvocationInsertionStatement);
		if(depthOfNestingForVariableCriterionDeclarationStatement > depthOfNestingForExtractedMethodInvocationInsertionStatement)
			return true;
		if(depthOfNestingForVariableCriterionDeclarationStatement == depthOfNestingForExtractedMethodInvocationInsertionStatement &&
				variableCriterionDeclarationStatement instanceof TryStatement)
			return true;
	}
	return false;
}
 
Example #22
Source File: SwitchControlStructure.java    From JDeodorant with MIT License 5 votes vote down vote up
private static List<AbstractControlCase> addToAll(Statement statement, List<AbstractControlCase> caseList)
{
	for (AbstractControlCase currentCase : caseList)
	{
		currentCase.addBodyStatement(statement);
	}
	return caseList;
}
 
Example #23
Source File: QuickAssistProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private static void setCatchClauseBody(CatchClause newCatchClause, ASTRewrite rewrite, CatchClause catchClause) {
		// Workaround for https://bugs.eclipse.org/bugs/show_bug.cgi?id=350285
		
//		newCatchClause.setBody((Block) rewrite.createCopyTarget(catchClause.getBody()));
		
		//newCatchClause#setBody() destroys the formatting, hence copy statement by statement.
		List<Statement> statements= catchClause.getBody().statements();
		for (Iterator<Statement> iterator2= statements.iterator(); iterator2.hasNext();) {
			newCatchClause.getBody().statements().add(rewrite.createCopyTarget(iterator2.next()));
		}
	}
 
Example #24
Source File: CompositeStatementObject.java    From RefactoringMiner with MIT License 5 votes vote down vote up
public CompositeStatementObject(CompilationUnit cu, String filePath, Statement statement, int depth, CodeElementType codeElementType) {
	super();
	this.setDepth(depth);
	this.locationInfo = new LocationInfo(cu, filePath, statement, codeElementType);
	this.statementList = new ArrayList<AbstractStatement>();
	this.expressionList = new ArrayList<AbstractExpression>();
	this.variableDeclarations = new ArrayList<VariableDeclaration>();
}
 
Example #25
Source File: SourceProvider.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
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;
			}
		}
	}
}
 
Example #26
Source File: OperationBody.java    From RefactoringMiner with MIT License 5 votes vote down vote up
public OperationBody(CompilationUnit cu, String filePath, Block methodBody) {
	this.compositeStatement = new CompositeStatementObject(cu, filePath, methodBody, 0, CodeElementType.BLOCK);
	List<Statement> statements = methodBody.statements();
	for(Statement statement : statements) {
		processStatement(cu, filePath, compositeStatement, statement);
	}
}
 
Example #27
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 #28
Source File: PreconditionExaminer.java    From JDeodorant with MIT License 5 votes vote down vote up
private boolean isExpressionUnderStatement(ASTNode expression, Statement statement) {
	ASTNode parent = expression.getParent();
	if(parent.equals(statement))
		return true;
	if(!(parent instanceof Statement) && !(parent instanceof BodyDeclaration))
		return isExpressionUnderStatement(parent, statement);
	else
		return false;
}
 
Example #29
Source File: StatementAnalyzer.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private static List<SwitchCase> getSwitchCases(SwitchStatement node) {
	List<SwitchCase> result= new ArrayList<SwitchCase>();
	for (Iterator<Statement> iter= node.statements().iterator(); iter.hasNext(); ) {
		Object element= iter.next();
		if (element instanceof SwitchCase)
			result.add((SwitchCase) element);
	}
	return result;
}
 
Example #30
Source File: AstUtils.java    From RefactoringMiner with MIT License 5 votes vote down vote up
public static Statement getEnclosingStatement(ASTNode node) {
    do {
        if (node instanceof Statement) {
            return (Statement) node;
        } else {
            node = node.getParent();
        }
    } while (node != null);
    return null;
}