Java Code Examples for org.eclipse.jdt.core.dom.Block#statements()

The following examples show how to use org.eclipse.jdt.core.dom.Block#statements() . 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: 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 2
Source File: MethodDeclarationUtility.java    From JDeodorant with MIT License 6 votes vote down vote up
public static SimpleName isGetter(MethodDeclaration methodDeclaration) {
	Block methodBody = methodDeclaration.getBody();
	List<SingleVariableDeclaration> parameters = methodDeclaration.parameters();
	if(methodBody != null) {
		List<Statement> statements = methodBody.statements();
		if(statements.size() == 1 && parameters.size() == 0) {
			Statement statement = statements.get(0);
    		if(statement instanceof ReturnStatement) {
    			ReturnStatement returnStatement = (ReturnStatement)statement;
    			Expression returnStatementExpression = returnStatement.getExpression();
    			if(returnStatementExpression instanceof SimpleName) {
    				return (SimpleName)returnStatementExpression;
    			}
    			else if(returnStatementExpression instanceof FieldAccess) {
    				FieldAccess fieldAccess = (FieldAccess)returnStatementExpression;
    				return fieldAccess.getName();
    			}
    		}
		}
	}
	return null;
}
 
Example 3
Source File: ExpressionExtractor.java    From JDeodorant with MIT License 6 votes vote down vote up
private List<Expression> getExpressions(AnonymousClassDeclaration anonymousClassDeclaration) {
	List<Expression> expressionList = new ArrayList<Expression>();
	List<BodyDeclaration> bodyDeclarations = anonymousClassDeclaration.bodyDeclarations();
	for(BodyDeclaration bodyDeclaration : bodyDeclarations) {
		if(bodyDeclaration instanceof MethodDeclaration) {
			MethodDeclaration methodDeclaration = (MethodDeclaration)bodyDeclaration;
			Block body = methodDeclaration.getBody();
			if(body != null) {
				List<Statement> statements = body.statements();
				for(Statement statement : statements) {
					expressionList.addAll(getExpressions(statement));
				}
			}
		}
	}
	return expressionList;
}
 
Example 4
Source File: QuickAssistProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
public static ASTNode getCopyOfInner(ASTRewrite rewrite, ASTNode statement, boolean toControlStatementBody) {
	if (statement.getNodeType() == ASTNode.BLOCK) {
		Block block= (Block) statement;
		List<Statement> innerStatements= block.statements();
		int nStatements= innerStatements.size();
		if (nStatements == 1) {
			return rewrite.createCopyTarget(innerStatements.get(0));
		} else if (nStatements > 1) {
			if (toControlStatementBody) {
				return rewrite.createCopyTarget(block);
			}
			ListRewrite listRewrite= rewrite.getListRewrite(block, Block.STATEMENTS_PROPERTY);
			ASTNode first= innerStatements.get(0);
			ASTNode last= innerStatements.get(nStatements - 1);
			return listRewrite.createCopyTarget(first, last);
		}
		return null;
	} else {
		return rewrite.createCopyTarget(statement);
	}
}
 
Example 5
Source File: VariableDeclarationFix.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private boolean callsWritingConstructor(MethodDeclaration methodDeclaration, HashSet<IMethodBinding> writingConstructorBindings, Set<MethodDeclaration> visitedMethodDeclarations) {
	Block body= methodDeclaration.getBody();
	if (body == null)
		return false;

	List<Statement> statements= body.statements();
	if (statements.size() == 0)
		return false;

	Statement statement= statements.get(0);
	if (!(statement instanceof ConstructorInvocation))
		return false;

	ConstructorInvocation invocation= (ConstructorInvocation)statement;
	IMethodBinding constructorBinding= invocation.resolveConstructorBinding();
	if (constructorBinding == null)
		return false;

	if (writingConstructorBindings.contains(constructorBinding)) {
		return true;
	} else {
		ASTNode declaration= ASTNodes.findDeclaration(constructorBinding, methodDeclaration.getParent());
		if (!(declaration instanceof MethodDeclaration))
			return false;

		if (visitedMethodDeclarations.contains(declaration)) {
			return false;
		}
		visitedMethodDeclarations.add(methodDeclaration);
		return callsWritingConstructor((MethodDeclaration)declaration, writingConstructorBindings, visitedMethodDeclarations);
	}
}
 
Example 6
Source File: TypeCheckElimination.java    From JDeodorant with MIT License 5 votes vote down vote up
public boolean isTypeCheckMethodStateSetter() {
	InheritanceTree tree = null;
	if(existingInheritanceTree != null)
		tree = existingInheritanceTree;
	else if(inheritanceTreeMatchingWithStaticTypes != null)
		tree = inheritanceTreeMatchingWithStaticTypes;
	if(tree != null) {
		DefaultMutableTreeNode root = tree.getRootNode();
		DefaultMutableTreeNode leaf = root.getFirstLeaf();
		List<String> subclassNames = new ArrayList<String>();
		while(leaf != null) {
			subclassNames.add((String)leaf.getUserObject());
			leaf = leaf.getNextLeaf();
		}
		Block typeCheckMethodBody = typeCheckMethod.getBody();
		List<Statement> statements = typeCheckMethodBody.statements();
		if(statements.size() > 0 && statements.get(0) instanceof SwitchStatement) {
			SwitchStatement switchStatement = (SwitchStatement)statements.get(0);
			List<Statement> statements2 = switchStatement.statements();
			ExpressionExtractor expressionExtractor = new ExpressionExtractor();
			int matchCounter = 0;
			for(Statement statement2 : statements2) {
				if(!(statement2 instanceof SwitchCase) && !(statement2 instanceof BreakStatement)) {
					List<Expression> classInstanceCreations = expressionExtractor.getClassInstanceCreations(statement2);
					if(classInstanceCreations.size() == 1) {
						ClassInstanceCreation classInstanceCreation = (ClassInstanceCreation)classInstanceCreations.get(0);
						Type classInstanceCreationType = classInstanceCreation.getType();
						if(subclassNames.contains(classInstanceCreationType.resolveBinding().getQualifiedName())) {
							matchCounter++;
						}
					}
				}
			}
			if(matchCounter == subclassNames.size())
				return true;
		}
	}
	return false;
}
 
Example 7
Source File: MethodBodyObject.java    From JDeodorant with MIT License 5 votes vote down vote up
public MethodBodyObject(Block methodBody) {
	this.compositeStatement = new CompositeStatementObject(methodBody, StatementType.BLOCK, null);
       List<Statement> statements = methodBody.statements();
	for(Statement statement : statements) {
		processStatement(compositeStatement, statement);
	}
}
 
Example 8
Source File: MethodDeclarationUtility.java    From JDeodorant with MIT License 5 votes vote down vote up
public static SimpleName isSetter(MethodDeclaration methodDeclaration) {
	Block methodBody = methodDeclaration.getBody();
	List<SingleVariableDeclaration> parameters = methodDeclaration.parameters();
	if(methodBody != null) {
		List<Statement> statements = methodBody.statements();
		if(statements.size() == 1 && parameters.size() == 1) {
			Statement statement = statements.get(0);
    		if(statement instanceof ExpressionStatement) {
    			ExpressionStatement expressionStatement = (ExpressionStatement)statement;
    			Expression expressionStatementExpression = expressionStatement.getExpression();
    			if(expressionStatementExpression instanceof Assignment) {
    				Assignment assignment = (Assignment)expressionStatementExpression;
    				Expression rightHandSide = assignment.getRightHandSide();
    				if(rightHandSide instanceof SimpleName) {
    					SimpleName rightHandSideSimpleName = (SimpleName)rightHandSide;
    					if(rightHandSideSimpleName.resolveBinding().isEqualTo(parameters.get(0).resolveBinding())) {
    						Expression leftHandSide = assignment.getLeftHandSide();
    						if(leftHandSide instanceof SimpleName) {
    		    				return (SimpleName)leftHandSide;
    		    			}
    		    			else if(leftHandSide instanceof FieldAccess) {
    		    				FieldAccess fieldAccess = (FieldAccess)leftHandSide;
    		    				return fieldAccess.getName();
    		    			}
    					}
    				}
    			}
    		}
		}
	}
	return null;
}
 
Example 9
Source File: MethodExitsFinder.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private void markReferences() {
	fCaughtExceptions= new ArrayList<ITypeBinding>();
	boolean isVoid= true;
	Type returnType= fMethodDeclaration.getReturnType2();
	if (returnType != null) {
		ITypeBinding returnTypeBinding= returnType.resolveBinding();
		isVoid= returnTypeBinding != null && Bindings.isVoidType(returnTypeBinding);
	}
	fMethodDeclaration.accept(this);
	Block block= fMethodDeclaration.getBody();
	if (block != null) {
		List<Statement> statements= block.statements();
		if (statements.size() > 0) {
			Statement last= statements.get(statements.size() - 1);
			int maxVariableId= LocalVariableIndex.perform(fMethodDeclaration);
			FlowContext flowContext= new FlowContext(0, maxVariableId + 1);
			flowContext.setConsiderAccessMode(false);
			flowContext.setComputeMode(FlowContext.ARGUMENTS);
			InOutFlowAnalyzer flowAnalyzer= new InOutFlowAnalyzer(flowContext);
			FlowInfo info= flowAnalyzer.perform(new ASTNode[] {last});
			if (!info.isNoReturn() && !isVoid) {
				if (!info.isPartialReturn())
					return;
			}
		}
		int offset= fMethodDeclaration.getStartPosition() + fMethodDeclaration.getLength() - 1; // closing bracket
		fResult.add(new OccurrenceLocation(offset, 1, 0, fExitDescription));
	}
}
 
Example 10
Source File: ConstructorReferenceFinder.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private static SuperConstructorInvocation getSuperConstructorCallNode(IMethod constructor, CompilationUnit cuNode) throws JavaModelException {
	Assert.isTrue(constructor.isConstructor());
	MethodDeclaration constructorNode= ASTNodeSearchUtil.getMethodDeclarationNode(constructor, cuNode);
	Assert.isTrue(constructorNode.isConstructor());
	Block body= constructorNode.getBody();
	Assert.isNotNull(body);
	List<Statement> statements= body.statements();
	if (! statements.isEmpty() && statements.get(0) instanceof SuperConstructorInvocation)
		return (SuperConstructorInvocation)statements.get(0);
	return null;
}
 
Example 11
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 12
Source File: CodeBlock.java    From SimFix with GNU General Public License v2.0 5 votes vote down vote up
private Blk visit(Block node) {
	int startLine = _cunit.getLineNumber(node.getStartPosition());
	int endLine  = _cunit.getLineNumber(node.getStartPosition() + node.getLength());
	Blk blk = new Blk(startLine, endLine, node);
	List<Stmt> stmts = new ArrayList<>();
	for(Object object : node.statements()){
		Stmt stmt = (Stmt) process((ASTNode) object);
		stmt.setParent(blk);
		stmts.add(stmt);
	}
	blk.setStatement(stmts);
	return blk;
}
 
Example 13
Source File: BuggyCode.java    From SimFix with GNU General Public License v2.0 4 votes vote down vote up
public boolean process(Statement statement) {

			// TODO : wait for completing ...
			
			int start = _unit.getLineNumber(statement.getStartPosition());
			int end = _unit.getLineNumber(statement.getStartPosition() + statement.getLength());

			if (start <= _buggyLine && _buggyLine <= end) {
				if (statement instanceof IfStatement || statement instanceof ForStatement
						|| statement instanceof WhileStatement || statement instanceof DoStatement
						|| statement instanceof EnhancedForStatement) {
					_nodes.add(statement);
					return false;
				} else if(statement instanceof Block){
					if(statement.getParent() instanceof IfStatement && (end - start) < Constant.MAX_BLOCK_LINE){
						_nodes.add(statement.getParent());
						return true;
					}
					Block block = (Block) statement;
					for(Object object : block.statements()){
						process((Statement)object);
					}
				} else if(statement instanceof SwitchStatement){
					SwitchStatement switchStmt = (SwitchStatement) statement;
					for(int i = 0; i < switchStmt.statements().size(); i++){
						Statement stmt = (Statement) switchStmt.statements().get(i);
						int s = _unit.getLineNumber(stmt.getStartPosition());
						int e = _unit.getLineNumber(stmt.getStartPosition() + stmt.getLength());
						if(s <= _buggyLine && _buggyLine <= e){
							_nodes.add(stmt);
							if(stmt instanceof SwitchCase){
								for(int j = i + 1 ; j < switchStmt.statements().size(); j++){
									Statement SC = (Statement) switchStmt.statements().get(j);
									if(SC instanceof SwitchCase){
										return false;
									} else {
										_nodes.add(SC);
									}
								}
							} else {
								_nodes.add(stmt);
								return false;
							}
						}
					}
					
				} else {
					_nodes.add(statement);
					return false;
				}
			}

			return true;
		}
 
Example 14
Source File: ControlStatementsFix.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
private static boolean satisfiesPrecondition(Statement controlStatement, ChildPropertyDescriptor childDescriptor, boolean onlyReturnAndThrows, boolean cleanUpCheck) {
	Object child= controlStatement.getStructuralProperty(childDescriptor);

	if (!(child instanceof Block))
		return false;

	Block block= (Block)child;
	List<Statement> list= block.statements();
	if (list.size() != 1)
		return false;

	ASTNode singleStatement= list.get(0);

	if (onlyReturnAndThrows)
		if (!(singleStatement instanceof ReturnStatement) && !(singleStatement instanceof ThrowStatement))
			return false;

	if (controlStatement instanceof IfStatement) {
		// if (true) {
		//  while (true)
		// 	 if (false)
		//    ;
		// } else
		//   ;

		if (((IfStatement)controlStatement).getThenStatement() != child)
			return true;//can always remove blocks in else part

		IfStatement ifStatement= (IfStatement)controlStatement;
		if (ifStatement.getElseStatement() == null)
			return true;//can always remove if no else part

		return !hasUnblockedIf((Statement)singleStatement, onlyReturnAndThrows, cleanUpCheck);
	} else {
		//if (true)
		// while (true) {
		//  if (false)
		//   ;
		// }
		//else
		// ;
		if (!hasUnblockedIf((Statement)singleStatement, onlyReturnAndThrows, cleanUpCheck))
			return true;

		ASTNode currentChild= controlStatement;
		ASTNode parent= currentChild.getParent();
		while (true) {
			Statement body= null;
			if (parent instanceof IfStatement) {
				body= ((IfStatement)parent).getThenStatement();
				if (body == currentChild && ((IfStatement)parent).getElseStatement() != null)//->currentChild is an unblocked then part
					return false;
			} else if (parent instanceof WhileStatement) {
				body= ((WhileStatement)parent).getBody();
			} else if (parent instanceof DoStatement) {
				body= ((DoStatement)parent).getBody();
			} else if (parent instanceof ForStatement) {
				body= ((ForStatement)parent).getBody();
			} else if (parent instanceof EnhancedForStatement) {
				body= ((EnhancedForStatement)parent).getBody();
			} else {
				return true;
			}
			if (body != currentChild)//->parents child is a block
				return true;

			currentChild= parent;
			parent= currentChild.getParent();
		}
	}
}
 
Example 15
Source File: LambdaExpressionsFix.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
/**
		 * {@inheritDoc}
		 */
		@Override
		public void rewriteAST(CompilationUnitRewrite cuRewrite, LinkedProposalModel model) throws CoreException {

			ASTRewrite rewrite= cuRewrite.getASTRewrite();
			ImportRemover importRemover= cuRewrite.getImportRemover();
			AST ast= rewrite.getAST();

			HashMap<ClassInstanceCreation, HashSet<String>> cicToNewNames= new HashMap<ClassInstanceCreation, HashSet<String>>();
			for (int i= 0; i < fExpressions.size(); i++) {
				ClassInstanceCreation classInstanceCreation= fExpressions.get(i);
				TextEditGroup group= createTextEditGroup(FixMessages.LambdaExpressionsFix_convert_to_lambda_expression, cuRewrite);

				AnonymousClassDeclaration anonymTypeDecl= classInstanceCreation.getAnonymousClassDeclaration();
				List<BodyDeclaration> bodyDeclarations= anonymTypeDecl.bodyDeclarations();

				Object object= bodyDeclarations.get(0);
				if (!(object instanceof MethodDeclaration))
					continue;
				MethodDeclaration methodDeclaration= (MethodDeclaration) object;
				HashSet<String> excludedNames= new HashSet<String>();
				if (i != 0) {
					for (ClassInstanceCreation convertedCic : fExpressions.subList(0, i)) {
						if (ASTNodes.isParent(classInstanceCreation, convertedCic)) {
							excludedNames.addAll(cicToNewNames.get(convertedCic));
						}
					}
				}
				HashSet<String> newNames= makeNamesUnique(excludedNames, methodDeclaration, rewrite, group);
				cicToNewNames.put(classInstanceCreation, new HashSet<String>(newNames));
				List<SingleVariableDeclaration> methodParameters= methodDeclaration.parameters();

				// use short form with inferred parameter types and without parentheses if possible
				LambdaExpression lambdaExpression= ast.newLambdaExpression();
				List<VariableDeclaration> lambdaParameters= lambdaExpression.parameters();
				lambdaExpression.setParentheses(methodParameters.size() != 1);
				for (SingleVariableDeclaration methodParameter : methodParameters) {
					VariableDeclarationFragment lambdaParameter= ast.newVariableDeclarationFragment();
					lambdaParameter.setName((SimpleName) rewrite.createCopyTarget(methodParameter.getName()));
					lambdaParameters.add(lambdaParameter);
				}
				
				Block body= methodDeclaration.getBody();
				List<Statement> statements= body.statements();
				ASTNode lambdaBody= body;
				if (statements.size() == 1) {
					// use short form with just an expression body if possible
					Statement statement= statements.get(0);
					if (statement instanceof ExpressionStatement) {
						lambdaBody= ((ExpressionStatement) statement).getExpression();
					} else if (statement instanceof ReturnStatement) {
						Expression returnExpression= ((ReturnStatement) statement).getExpression();
						if (returnExpression != null) {
							lambdaBody= returnExpression;
						}
					}
				}
				//TODO: Bug 421479: [1.8][clean up][quick assist] convert anonymous to lambda must consider lost scope of interface
//				lambdaBody.accept(new InterfaceAccessQualifier(rewrite, classInstanceCreation.getType().resolveBinding())); //TODO: maybe need a separate ASTRewrite and string placeholder
				
				lambdaExpression.setBody(rewrite.createCopyTarget(lambdaBody));
				Expression replacement= lambdaExpression;
				if (ASTNodes.isTargetAmbiguous(classInstanceCreation, lambdaParameters.isEmpty())) {
					CastExpression cast= ast.newCastExpression();
					cast.setExpression(lambdaExpression);
					ImportRewrite importRewrite= cuRewrite.getImportRewrite();
					ImportRewriteContext importRewriteContext= new ContextSensitiveImportRewriteContext(classInstanceCreation, importRewrite);
					Type castType= importRewrite.addImport(classInstanceCreation.getType().resolveBinding(), ast, importRewriteContext);
					cast.setType(castType);
					importRemover.registerAddedImports(castType);
					replacement= cast;
				}
				rewrite.replace(classInstanceCreation, replacement, group);

				importRemover.registerRemovedNode(classInstanceCreation);
				importRemover.registerRetainedNode(lambdaBody);
			}
		}
 
Example 16
Source File: IntroduceFactoryRefactoring.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
/**
 * Creates and returns a new MethodDeclaration that represents the factory method to be used in
 * place of direct calls to the constructor in question.
 * 
 * @param ast An AST used as a factory for various AST nodes
 * @param ctorBinding binding for the constructor being wrapped
 * @param unitRewriter the ASTRewrite to be used
 * @return the new method declaration
 * @throws CoreException if an exception occurs while accessing its corresponding resource
 */
private MethodDeclaration createFactoryMethod(AST ast, IMethodBinding ctorBinding, ASTRewrite unitRewriter) throws CoreException{
	MethodDeclaration		newMethod= ast.newMethodDeclaration();
	SimpleName				newMethodName= ast.newSimpleName(fNewMethodName);
	ClassInstanceCreation	newCtorCall= ast.newClassInstanceCreation();
	ReturnStatement			ret= ast.newReturnStatement();
	Block		body= ast.newBlock();
	List<Statement>		stmts= body.statements();
	String		retTypeName= ctorBinding.getName();

	createFactoryMethodSignature(ast, newMethod);

	newMethod.setName(newMethodName);
	newMethod.setBody(body);

	ITypeBinding declaringClass= fCtorBinding.getDeclaringClass();
	ITypeBinding[] ctorOwnerTypeParameters= declaringClass.getTypeParameters();

	setMethodReturnType(newMethod, retTypeName, ctorOwnerTypeParameters, ast);

	newMethod.modifiers().addAll(ASTNodeFactory.newModifiers(ast, Modifier.STATIC | Modifier.PUBLIC));

	setCtorTypeArguments(newCtorCall, retTypeName, ctorOwnerTypeParameters, ast);

	createFactoryMethodConstructorArgs(ast, newCtorCall);

	if (Modifier.isAbstract(declaringClass.getModifiers())) {
		AnonymousClassDeclaration decl= ast.newAnonymousClassDeclaration();
		IMethodBinding[] unimplementedMethods= getUnimplementedMethods(declaringClass);
		CodeGenerationSettings settings= JavaPreferencesSettings.getCodeGenerationSettings(fCUHandle.getJavaProject());
		ImportRewriteContext context= new ContextSensitiveImportRewriteContext(fFactoryCU, decl.getStartPosition(), fImportRewriter);
		for (int i= 0; i < unimplementedMethods.length; i++) {
			IMethodBinding unImplementedMethod= unimplementedMethods[i];
			MethodDeclaration newMethodDecl= StubUtility2.createImplementationStub(fCUHandle, unitRewriter, fImportRewriter, context, unImplementedMethod, unImplementedMethod.getDeclaringClass()
					.getName(), settings, false);
			decl.bodyDeclarations().add(newMethodDecl);
		}
		newCtorCall.setAnonymousClassDeclaration(decl);
	}

	ret.setExpression(newCtorCall);
	stmts.add(ret);

	return newMethod;
}
 
Example 17
Source File: SequenceDiagramVisitor.java    From txtUML with Eclipse Public License 1.0 4 votes vote down vote up
private void checkSendInBlock(Block block, boolean showErrorHere) {
	List<Statement> statements = (List<Statement>) block.statements();
	List<Statement> loops = Utils.getLoopNodes(statements);
	loops.forEach(loop -> {
		if (showErrorHere) {
			placeOfError = loop;
		}
		checkSendInLoopNode(loop);
	});
	List<IfStatement> ifNodes = Utils.getIfNodes(statements);
	ifNodes.forEach(ifNode -> {
		if (showErrorHere) {
			placeOfError = ifNode;
		}
		checkSendInIfNode(ifNode);
	});
	List<MethodInvocation> parFragments = Utils.getParFragments(statements);
	parFragments.forEach(parFragment -> {
		if (showErrorHere) {
			placeOfError = parFragment.getParent();
		}
		checkSendInPar(parFragment);
	});
	List<MethodInvocation> methodInvocations = Utils.getMethodInvocations(statements);
	final List<Boolean> containsSendOrFragment = new ArrayList<>();
	methodInvocations.forEach(methodInvocation -> {
		if (showErrorHere) {
			placeOfError = methodInvocation;
		}
		containsSendOrFragment.add(checkSendOrFragmentInMethodInvocation(methodInvocation));
	});
	List<SuperMethodInvocation> superMethodInvocations = Utils.getSuperMethodInvocations(statements);
	superMethodInvocations.forEach(invocation -> {
		if (showErrorHere) {
			placeOfError = invocation;
		}
		containsSendOrFragment.add(checkSendOrFragmentInSuperMethodInvocation(invocation));
	});
	if (showErrorHere) {
		placeOfError = block;
	}
	boolean isLeaf = loops.isEmpty() && ifNodes.isEmpty() && parFragments.isEmpty();
	if (isLeaf && !containsSendOrFragment.contains(true)) {
		collector.report(SequenceErrors.SEND_EXPECTED.create(collector.getSourceInfo(), placeOfError));
	}
}
 
Example 18
Source File: ReplaceTypeCodeWithStateStrategy.java    From JDeodorant with MIT License 4 votes vote down vote up
private boolean typeObjectGetterMethodAlreadyExists() {
	InheritanceTree tree = typeCheckElimination.getInheritanceTreeMatchingWithStaticTypes();
	if(tree != null) {
		MethodDeclaration[] contextMethods = sourceTypeDeclaration.getMethods();
		DefaultMutableTreeNode rootNode = tree.getRootNode();
		String rootClassName = (String)rootNode.getUserObject();
		DefaultMutableTreeNode leaf = rootNode.getFirstLeaf();
		List<String> subclassNames = new ArrayList<String>();
		while(leaf != null) {
			subclassNames.add((String)leaf.getUserObject());
			leaf = leaf.getNextLeaf();
		}
		for(MethodDeclaration contextMethod : contextMethods) {
			Type returnType = contextMethod.getReturnType2();
			if(returnType != null) {
				if(returnType.resolveBinding().getQualifiedName().equals(rootClassName)) {
					Block contextMethodBody = contextMethod.getBody();
					if(contextMethodBody != null) {
						List<Statement> statements = contextMethodBody.statements();
						if(statements.size() > 0 && statements.get(0) instanceof SwitchStatement) {
							SwitchStatement switchStatement = (SwitchStatement)statements.get(0);
							List<Statement> statements2 = switchStatement.statements();
							int matchCounter = 0;
							for(Statement statement2 : statements2) {
								if(statement2 instanceof ReturnStatement) {
									ReturnStatement returnStatement = (ReturnStatement)statement2;
									Expression returnStatementExpression = returnStatement.getExpression();
									if(returnStatementExpression instanceof ClassInstanceCreation) {
										ClassInstanceCreation classInstanceCreation = (ClassInstanceCreation)returnStatementExpression;
										Type classInstanceCreationType = classInstanceCreation.getType();
										if(subclassNames.contains(classInstanceCreationType.resolveBinding().getQualifiedName())) {
											matchCounter++;
										}
									}
								}
							}
							if(matchCounter == subclassNames.size())
								return true;
						}
					}
				}
			}
		}
	}
	return false;
}