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

The following examples show how to use org.eclipse.jdt.core.dom.TryStatement. 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: ASTNodeMatcher.java    From JDeodorant with MIT License 6 votes vote down vote up
public boolean match(TryStatement node, Object other) {
	if (!(other instanceof TryStatement)) {
		return false;
	}
	TryStatement o = (TryStatement) other;
	if(isNestedUnderAnonymousClassDeclaration(node) && isNestedUnderAnonymousClassDeclaration(o)) {
		return super.match(node, o);
	}
	boolean resourceMatch = safeSubtreeListMatch(node.resources(), o.resources());
	boolean catchClauseMatch = safeSubtreeListMatch(node.catchClauses(), o.catchClauses());
	boolean finallyMatch;
	if(node.getFinally() == null && o.getFinally() == null)
		finallyMatch = true;
	else if(node.getFinally() != null && o.getFinally() != null)
		finallyMatch = safeSubtreeListMatch(node.getFinally().statements(), o.getFinally().statements());
	else
		finallyMatch = false;
	return resourceMatch && catchClauseMatch && finallyMatch;
}
 
Example #2
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(TryStatement node) {
	ASTNode firstSelectedNode= getFirstSelectedNode();
	if (getSelection().getEndVisitSelectionMode(node) == Selection.AFTER) {
		if (firstSelectedNode == node.getBody() || firstSelectedNode == node.getFinally()) {
			invalidSelection(RefactoringCoreMessages.StatementAnalyzer_try_statement);
		} else {
			List<CatchClause> catchClauses= node.catchClauses();
			for (Iterator<CatchClause> iterator= catchClauses.iterator(); iterator.hasNext();) {
				CatchClause element= iterator.next();
				if (element == firstSelectedNode || element.getBody() == firstSelectedNode) {
					invalidSelection(RefactoringCoreMessages.StatementAnalyzer_try_statement);
				} else if (element.getException() == firstSelectedNode) {
					invalidSelection(RefactoringCoreMessages.StatementAnalyzer_catch_argument);
				}
			}
		}
	}
	super.endVisit(node);
}
 
Example #3
Source File: QuickAssistProcessor.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
private static boolean getAddFinallyProposals(IInvocationContext context, ASTNode node, Collection<ICommandAccess> resultingCollections) {
	TryStatement tryStatement= ASTResolving.findParentTryStatement(node);
	if (tryStatement == null || tryStatement.getFinally() != null) {
		return false;
	}
	Statement statement= ASTResolving.findParentStatement(node);
	if (tryStatement != statement && tryStatement.getBody() != statement) {
		return false; // an node inside a catch or finally block
	}

	if (resultingCollections == null) {
		return true;
	}

	AST ast= tryStatement.getAST();
	ASTRewrite rewrite= ASTRewrite.create(ast);
	Block finallyBody= ast.newBlock();

	rewrite.set(tryStatement, TryStatement.FINALLY_PROPERTY, finallyBody, null);

	String label= CorrectionMessages.QuickAssistProcessor_addfinallyblock_description;
	Image image= JavaPluginImages.get(JavaPluginImages.IMG_CORRECTION_ADD);
	ASTRewriteCorrectionProposal proposal= new ASTRewriteCorrectionProposal(label, context.getCompilationUnit(), rewrite, IProposalRelevance.ADD_FINALLY_BLOCK, image);
	resultingCollections.add(proposal);
	return true;
}
 
Example #4
Source File: ExtractTempRefactoring.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
private RefactoringStatus checkExpression() throws JavaModelException {
	Expression selectedExpression= getSelectedExpression().getAssociatedExpression();
	if (selectedExpression != null) {
		final ASTNode parent= selectedExpression.getParent();
		if (selectedExpression instanceof NullLiteral) {
			return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.ExtractTempRefactoring_null_literals);
		} else if (selectedExpression instanceof ArrayInitializer) {
			return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.ExtractTempRefactoring_array_initializer);
		} else if (selectedExpression instanceof Assignment) {
			if (parent instanceof Expression && !(parent instanceof ParenthesizedExpression))
				return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.ExtractTempRefactoring_assignment);
			else
				return null;
		} else if (selectedExpression instanceof SimpleName) {
			if ((((SimpleName) selectedExpression)).isDeclaration())
				return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.ExtractTempRefactoring_names_in_declarations);
			if (parent instanceof QualifiedName && selectedExpression.getLocationInParent() == QualifiedName.NAME_PROPERTY || parent instanceof FieldAccess && selectedExpression.getLocationInParent() == FieldAccess.NAME_PROPERTY)
				return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.ExtractTempRefactoring_select_expression);
		} else if (selectedExpression instanceof VariableDeclarationExpression && parent instanceof TryStatement) {
			return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.ExtractTempRefactoring_resource_in_try_with_resources);
		}
	}

	return null;
}
 
Example #5
Source File: FlowAnalyzer.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
@Override
public boolean visit(TryStatement node) {
	if (traverseNode(node)) {
		fFlowContext.pushExcptions(node);
		node.getBody().accept(this);
		fFlowContext.popExceptions();
		List<CatchClause> catchClauses= node.catchClauses();
		for (Iterator<CatchClause> iter= catchClauses.iterator(); iter.hasNext();) {
			iter.next().accept(this);
		}
		Block finallyBlock= node.getFinally();
		if (finallyBlock != null) {
			finallyBlock.accept(this);
		}
	}
	return false;
}
 
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: ExtractMethodFragmentRefactoring.java    From JDeodorant with MIT License 6 votes vote down vote up
protected ListRewrite createTryStatementIfNeeded(ASTRewrite sourceRewriter, AST ast, ListRewrite bodyRewrite, PDGNode node) {
	Statement statement = node.getASTStatement();
	ASTNode statementParent = statement.getParent();
	if(statementParent != null && statementParent instanceof Block)
		statementParent = statementParent.getParent();
	if(statementParent != null && statementParent instanceof TryStatement) {
		TryStatement tryStatementParent = (TryStatement)statementParent;
		if(tryStatementsToBeRemoved.contains(tryStatementParent) || tryStatementsToBeCopied.contains(tryStatementParent)) {
			if(tryStatementBodyRewriteMap.containsKey(tryStatementParent)) {
				bodyRewrite = tryStatementBodyRewriteMap.get(tryStatementParent);
			}
			else {
				TryStatement newTryStatement = copyTryStatement(sourceRewriter, ast, tryStatementParent);
				Block tryMethodBody = ast.newBlock();
				sourceRewriter.set(newTryStatement, TryStatement.BODY_PROPERTY, tryMethodBody, null);
				ListRewrite tryBodyRewrite = sourceRewriter.getListRewrite(tryMethodBody, Block.STATEMENTS_PROPERTY);
				tryStatementBodyRewriteMap.put(tryStatementParent, tryBodyRewrite);
				bodyRewrite.insertLast(newTryStatement, null);
				bodyRewrite = tryBodyRewrite;
			}
		}
	}
	return bodyRewrite;
}
 
Example #8
Source File: ExtractMethodFragmentRefactoring.java    From JDeodorant with MIT License 6 votes vote down vote up
protected TryStatement copyTryStatement(ASTRewrite sourceRewriter, AST ast, TryStatement tryStatementParent) {
	TryStatement newTryStatement = ast.newTryStatement();
	ListRewrite resourceRewrite = sourceRewriter.getListRewrite(newTryStatement, TryStatement.RESOURCES_PROPERTY);
	List<VariableDeclarationExpression> resources = tryStatementParent.resources();
	for(VariableDeclarationExpression expression : resources) {
		resourceRewrite.insertLast(expression, null);
	}
	ListRewrite catchClauseRewrite = sourceRewriter.getListRewrite(newTryStatement, TryStatement.CATCH_CLAUSES_PROPERTY);
	List<CatchClause> catchClauses = tryStatementParent.catchClauses();
	for(CatchClause catchClause : catchClauses) {
		catchClauseRewrite.insertLast(catchClause, null);
	}
	if(tryStatementParent.getFinally() != null) {
		sourceRewriter.set(newTryStatement, TryStatement.FINALLY_PROPERTY, tryStatementParent.getFinally(), null);
	}
	return newTryStatement;
}
 
Example #9
Source File: FlowAnalyzer.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
@Override
public boolean visit(TryStatement node) {
	if (traverseNode(node)) {
		fFlowContext.pushExcptions(node);
		for (Iterator<VariableDeclarationExpression> iterator = node.resources().iterator(); iterator.hasNext();) {
			iterator.next().accept(this);
		}
		node.getBody().accept(this);
		fFlowContext.popExceptions();
		List<CatchClause> catchClauses = node.catchClauses();
		for (Iterator<CatchClause> iter = catchClauses.iterator(); iter.hasNext();) {
			iter.next().accept(this);
		}
		Block finallyBlock = node.getFinally();
		if (finallyBlock != null) {
			finallyBlock.accept(this);
		}
	}
	return false;
}
 
Example #10
Source File: StyledStringVisitor.java    From JDeodorant with MIT License 6 votes vote down vote up
public boolean visit(TryStatement stmnt){
	/*
	 * JLS 4:
	 * 	try [ ( Resources ) ]
	        Block
        	    [ { CatchClause } ]
        	    [ finally Block ]
	 */
	styledString.append("try", new StyledStringStyler(keywordStyle));
	if(!stmnt.resources().isEmpty()) {
		appendSpace();
		appendOpenParenthesis();
		for(int i=0; i<stmnt.resources().size(); i++) {
			handleExpression((VariableDeclarationExpression) stmnt.resources().get(i));
			if(i < stmnt.resources().size() - 1) {
				appendSemicolon();
				appendSpace();
			}
		}
		appendClosedParenthesis();
	}
	return false;
}
 
Example #11
Source File: FlowAnalyzer.java    From eclipse.jdt.ls with Eclipse Public License 2.0 6 votes vote down vote up
@Override
public void endVisit(TryStatement node) {
	if (skipNode(node)) {
		return;
	}
	TryFlowInfo info = createTry();
	setFlowInfo(node, info);
	for (Iterator<VariableDeclarationExpression> iterator = node.resources().iterator(); iterator.hasNext();) {
		info.mergeResources(getFlowInfo(iterator.next()), fFlowContext);
	}
	info.mergeTry(getFlowInfo(node.getBody()), fFlowContext);
	for (Iterator<CatchClause> iter = node.catchClauses().iterator(); iter.hasNext();) {
		CatchClause element = iter.next();
		info.mergeCatch(getFlowInfo(element), fFlowContext);
	}
	info.mergeFinally(getFlowInfo(node.getFinally()), fFlowContext);
}
 
Example #12
Source File: ExtractMethodRefactoring.java    From JDeodorant with MIT License 6 votes vote down vote up
private void processTryStatement(TryStatement tryStatement) {
	List<Statement> nestedStatements = getStatements(tryStatement);
	Set<Statement> removableStatements = slice.getRemovableStatements();
	Set<Statement> sliceStatements = slice.getSliceStatements();
	boolean allNestedStatementsAreRemovable = true;
	boolean sliceStatementThrowsException = false;
	for(Statement nestedStatement : nestedStatements) {
		if(!removableStatements.contains(nestedStatement)) {
			allNestedStatementsAreRemovable = false;
		}
		if(sliceStatements.contains(nestedStatement)) {
			Set<ITypeBinding> thrownExceptionTypes = getThrownExceptionTypes(nestedStatement);
			if(thrownExceptionTypes.size() > 0)
				sliceStatementThrowsException = true;
		}
	}
	if(slice.getSliceStatements().contains(tryStatement)) {
		if(allNestedStatementsAreRemovable)
			tryStatementsToBeRemoved.add(tryStatement);
		else if(sliceStatementThrowsException)
			tryStatementsToBeCopied.add(tryStatement);
	}
}
 
Example #13
Source File: CloneInstanceMapper.java    From JDeodorant with MIT License 5 votes vote down vote up
private boolean isFinallyBlockOfTryStatement(ASTNode node) {
	ASTNode parent = node.getParent();
	if(parent != null && parent instanceof TryStatement) {
		TryStatement tryStatement = (TryStatement)parent;
		Block finallyBlock = tryStatement.getFinally();
		if(node instanceof Block && finallyBlock != null) {
			return finallyBlock.equals((Block)node);
		}
	}
	return false;
}
 
Example #14
Source File: TryPurifyByException.java    From SimFix with GNU General Public License v2.0 5 votes vote down vote up
private ASTNode tryCatchStmt(AST ast, ASTNode node){
	Block block = ast.newBlock();
	block.statements().add(ASTNode.copySubtree(ast, node));
	TryStatement tryStatement = ast.newTryStatement();
	tryStatement.setBody(block);
	CatchClause catchClause = ast.newCatchClause();
	SingleVariableDeclaration svd = ast.newSingleVariableDeclaration();
	svd.setType(ast.newSimpleType(ast.newSimpleName("Exception")));
	svd.setName(ast.newSimpleName("mException"));
	catchClause.setException(svd);
	tryStatement.catchClauses().add(catchClause);
	return tryStatement;
}
 
Example #15
Source File: ExceptionOccurrencesFinder.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
private void handleResourceDeclarations(TryStatement tryStatement) {
	List<VariableDeclarationExpression> resources= tryStatement.resources();
	for (Iterator<VariableDeclarationExpression> iterator= resources.iterator(); iterator.hasNext();) {
		iterator.next().accept(this);
	}

	//check if the exception is thrown as a result of resource#close()
	boolean exitMarked= false;
	for (VariableDeclarationExpression variable : resources) {
		Type type= variable.getType();
		IMethodBinding methodBinding= Bindings.findMethodInHierarchy(type.resolveBinding(), "close", new ITypeBinding[0]); //$NON-NLS-1$
		if (methodBinding != null) {
			ITypeBinding[] exceptionTypes= methodBinding.getExceptionTypes();
			for (int j= 0; j < exceptionTypes.length; j++) {
				if (matches(exceptionTypes[j])) { // a close() throws the caught exception
					// mark name of resource
					for (VariableDeclarationFragment fragment : (List<VariableDeclarationFragment>) variable.fragments()) {
						SimpleName name= fragment.getName();
						fResult.add(new OccurrenceLocation(name.getStartPosition(), name.getLength(), 0, fDescription));
					}
					if (!exitMarked) {
						// mark exit position
						exitMarked= true;
						Block body= tryStatement.getBody();
						int offset= body.getStartPosition() + body.getLength() - 1; // closing bracket of try block
						fResult.add(new OccurrenceLocation(offset, 1, 0, Messages.format(SearchMessages.ExceptionOccurrencesFinder_occurrence_implicit_close_description,
								BasicElementLabels.getJavaElementName(fException.getName()))));
					}
				}
			}
		}
	}
}
 
Example #16
Source File: ExceptionOccurrencesFinder.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public boolean visit(TryStatement node) {
	int currentSize= fCaughtExceptions.size();
	List<CatchClause> catchClauses= node.catchClauses();
	for (Iterator<CatchClause> iter= catchClauses.iterator(); iter.hasNext();) {
		Type type= iter.next().getException().getType();
		if (type instanceof UnionType) {
			List<Type> types= ((UnionType) type).types();
			for (Iterator<Type> iterator= types.iterator(); iterator.hasNext();) {
				addCaughtException(iterator.next());
			}
		} else {
			addCaughtException(type);
		}
	}

	node.getBody().accept(this);

	handleResourceDeclarations(node);

	int toRemove= fCaughtExceptions.size() - currentSize;
	for (int i= toRemove; i > 0; i--) {
		fCaughtExceptions.remove(currentSize);
	}

	// visit catch and finally
	for (Iterator<CatchClause> iter= catchClauses.iterator(); iter.hasNext();) {
		iter.next().accept(this);
	}
	if (node.getFinally() != null)
		node.getFinally().accept(this);

	// return false. We have visited the body by ourselves.
	return false;
}
 
Example #17
Source File: ASTResolving.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
public static TryStatement findParentTryStatement(ASTNode node) {
	while ((node != null) && (!(node instanceof TryStatement))) {
		node= node.getParent();
		if (node instanceof BodyDeclaration) {
			return null;
		}
	}
	return (TryStatement) node;
}
 
Example #18
Source File: TryStatementWriter.java    From juniversal with MIT License 5 votes vote down vote up
@Override
public void write(TryStatement tryStatement) {
    if (tryStatement.resources().size() > 0)
        writeTryWithResources(tryStatement);
    else {
        matchAndWrite("try");

        copySpaceAndComments();
        writeNode(tryStatement.getBody());

        forEach(tryStatement.catchClauses(), (CatchClause catchClause) -> {
            copySpaceAndComments();
            matchAndWrite("catch");

            copySpaceAndComments();
            matchAndWrite("(");

            copySpaceAndComments();
            writeNode(catchClause.getException());

            copySpaceAndComments();
            matchAndWrite(")");

            copySpaceAndComments();
            writeNode(catchClause.getBody());
        });

        @Nullable Block finallyBlock = tryStatement.getFinally();
        if (finallyBlock != null) {
            copySpaceAndComments();
            matchAndWrite("finally");

            copySpaceAndComments();
            writeNode(finallyBlock);
        }
    }
}
 
Example #19
Source File: NodeInfoStore.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Creates a placeholder node of the given type. <code>null</code> if the type is not supported
 * @param nodeType Type of the node to create. Use the type constants in {@link NodeInfoStore}.
 * @return Returns a place holder node.
 */
public final ASTNode newPlaceholderNode(int nodeType) {
	try {
		ASTNode node= this.ast.createInstance(nodeType);
		switch (node.getNodeType()) {
			case ASTNode.FIELD_DECLARATION:
				((FieldDeclaration) node).fragments().add(this.ast.newVariableDeclarationFragment());
				break;
			case ASTNode.MODIFIER:
				((Modifier) node).setKeyword(Modifier.ModifierKeyword.ABSTRACT_KEYWORD);
				break;
			case ASTNode.TRY_STATEMENT :
				((TryStatement) node).setFinally(this.ast.newBlock()); // have to set at least a finally block to be legal code
				break;
			case ASTNode.VARIABLE_DECLARATION_EXPRESSION :
				((VariableDeclarationExpression) node).fragments().add(this.ast.newVariableDeclarationFragment());
				break;
			case ASTNode.VARIABLE_DECLARATION_STATEMENT :
				((VariableDeclarationStatement) node).fragments().add(this.ast.newVariableDeclarationFragment());
				break;
			case ASTNode.PARAMETERIZED_TYPE :
				((ParameterizedType) node).typeArguments().add(this.ast.newWildcardType());
				break;
		}
		return node;
	} catch (IllegalArgumentException e) {
		return null;
	}
	}
 
Example #20
Source File: StatementCollector.java    From JDeodorant with MIT License 5 votes vote down vote up
public boolean visit(Block node) {
	if(node.getParent() instanceof TryStatement) {
		TryStatement statement = (TryStatement) node.getParent();
		Block finallyBlock = statement.getFinally();
		if(finallyBlock != null && finallyBlock.equals(node))
			return false;
	}
	return true;
}
 
Example #21
Source File: ExtractMethodRefactoring.java    From JDeodorant with MIT License 5 votes vote down vote up
public ExtractMethodRefactoring(CompilationUnit sourceCompilationUnit, ASTSlice slice) {
	super();
	this.slice = slice;
	this.sourceCompilationUnit = sourceCompilationUnit;
	this.sourceTypeDeclaration = slice.getSourceTypeDeclaration();
	this.sourceMethodDeclaration = slice.getSourceMethodDeclaration();
	ICompilationUnit sourceICompilationUnit = (ICompilationUnit)sourceCompilationUnit.getJavaElement();
	this.compilationUnitChange = new CompilationUnitChange("", sourceICompilationUnit);
	this.exceptionTypesThatShouldBeThrownByExtractedMethod = new LinkedHashSet<ITypeBinding>();
	for(PDGNode pdgNode : slice.getSliceNodes()) {
		CFGNode cfgNode = pdgNode.getCFGNode();
		if(cfgNode instanceof CFGBranchDoLoopNode) {
			CFGBranchDoLoopNode cfgDoLoopNode = (CFGBranchDoLoopNode)cfgNode;
			doLoopNodes.add(cfgDoLoopNode);
		}
	}
	StatementExtractor statementExtractor = new StatementExtractor();
	List<Statement> tryStatements = statementExtractor.getTryStatements(sourceMethodDeclaration.getBody());
	for(Statement tryStatement : tryStatements) {
		processTryStatement((TryStatement)tryStatement);
	}
	for(Statement sliceStatement : slice.getSliceStatements()) {
		Set<ITypeBinding> thrownExceptionTypes = getThrownExceptionTypes(sliceStatement);
		if(thrownExceptionTypes.size() > 0) {
			TryStatement surroundingTryBlock = surroundingTryBlock(sliceStatement);
			if(surroundingTryBlock == null || !slice.getSliceStatements().contains(surroundingTryBlock)) {
				exceptionTypesThatShouldBeThrownByExtractedMethod.addAll(thrownExceptionTypes);
			}
			if(surroundingTryBlock != null && slice.getSliceStatements().contains(surroundingTryBlock)) {
				for(ITypeBinding thrownExceptionType : thrownExceptionTypes) {
					if(!tryBlockCatchesExceptionType(surroundingTryBlock, thrownExceptionType))
						exceptionTypesThatShouldBeThrownByExtractedMethod.add(thrownExceptionType);
				}
			}
		}
	}
}
 
Example #22
Source File: ExtractStatementsVisitor.java    From JDeodorant with MIT License 5 votes vote down vote up
public boolean visit(Block node) {
	if(node.getParent() instanceof TryStatement) {
		TryStatement statement = (TryStatement) node.getParent();
		Block finallyBlock = statement.getFinally();
		if(finallyBlock != null && finallyBlock.equals(node))
			return false;
	}
	return true;
}
 
Example #23
Source File: ASTNodeDifference.java    From JDeodorant with MIT License 5 votes vote down vote up
private boolean isExpressionOfIfStatementNestedAtLevelZero() {
	if(expression1.getExpression().getParent() instanceof IfStatement &&
			expression2.getExpression().getParent() instanceof IfStatement) {
		IfStatement if1 = (IfStatement)expression1.getExpression().getParent();
		IfStatement if2 = (IfStatement)expression2.getExpression().getParent();
		boolean noElsePart = if1.getElseStatement() == null && if2.getElseStatement() == null;
		ASTNode parent1 = if1.getParent();
		while(parent1 instanceof Block) {
			parent1 = parent1.getParent();
		}
		ASTNode parent2 = if2.getParent();
		while(parent2 instanceof Block) {
			parent2 = parent2.getParent();
		}
		if(parent1 instanceof MethodDeclaration && parent2 instanceof MethodDeclaration) {
			return noElsePart;
		}
		if(parent1 instanceof TryStatement && parent2 instanceof TryStatement) {
			TryStatement try1 = (TryStatement)parent1;
			TryStatement try2 = (TryStatement)parent2;
			parent1 = try1.getParent();
			while(parent1 instanceof Block) {
				parent1 = parent1.getParent();
			}
			parent2 = try2.getParent();
			while(parent2 instanceof Block) {
				parent2 = parent2.getParent();
			}
			if(parent1 instanceof MethodDeclaration && parent2 instanceof MethodDeclaration) {
				return noElsePart;
			}
		}
	}
	return false;
}
 
Example #24
Source File: TryStatementWriter.java    From juniversal with MIT License 5 votes vote down vote up
private void writeTryWithResources(TryStatement tryStatement) {
    matchAndWrite("try", "using");

    copySpaceAndComments();
    matchAndWrite("(");

    // TODO: Check handling multiple variables, with same type, included as part of single declaration
    forEach(tryStatement.resources(), (VariableDeclarationExpression resourceDeclaration, boolean first) -> {
        if (!first) {
            copySpaceAndComments();
            matchAndWrite(";", ",");
        }

        writeNode(resourceDeclaration);
    });

    copySpaceAndComments();
    matchAndWrite(")");

    copySpaceAndComments();
    writeNode(tryStatement.getBody());

    if (tryStatement.catchClauses().size() > 0)
        throw sourceNotSupported("try-with-resources with a catch clause isn't supported; use nested try statements instead");

    if (tryStatement.getFinally() != null)
        throw sourceNotSupported("try-with-resources with a finally clause isn't supported; use nested try statements instead");
}
 
Example #25
Source File: ASTNodeMatcher.java    From JDeodorant with MIT License 5 votes vote down vote up
private boolean isFinallyBlockOfTryStatement(ASTNode node) {
	ASTNode parent = node.getParent();
	if(parent != null && parent instanceof TryStatement) {
		TryStatement tryStatement = (TryStatement)parent;
		Block finallyBlock = tryStatement.getFinally();
		if(node instanceof Block && finallyBlock != null) {
			return finallyBlock.equals((Block)node);
		}
	}
	return false;
}
 
Example #26
Source File: ExtractMethodFragmentRefactoring.java    From JDeodorant with MIT License 5 votes vote down vote up
public ExtractMethodFragmentRefactoring() {
	this.tryStatementsToBeRemoved = new LinkedHashSet<TryStatement>();
	this.tryStatementsToBeCopied = new LinkedHashSet<TryStatement>();
	this.tryStatementBodyRewriteMap = new LinkedHashMap<TryStatement, ListRewrite>();
	this.doLoopNodes = new ArrayList<CFGBranchDoLoopNode>();
	this.labeledStatementsToBeRemoved = new LinkedHashSet<LabeledStatement>();
}
 
Example #27
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 #28
Source File: ExtractMethodFragmentRefactoring.java    From JDeodorant with MIT License 5 votes vote down vote up
protected TryStatement surroundingTryBlock(ASTNode statement) {
	ASTNode parent = statement.getParent();
	while(!(parent instanceof MethodDeclaration)) {
		if(parent instanceof TryStatement)
			return (TryStatement)parent;
		parent = parent.getParent();
	}
	return null;
}
 
Example #29
Source File: ExtractTempRefactoring.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
private RefactoringStatus checkExpression() throws JavaModelException {
	Expression selectedExpression = getSelectedExpression().getAssociatedExpression();
	if (selectedExpression != null) {
		final ASTNode parent = selectedExpression.getParent();
		if (selectedExpression instanceof NullLiteral) {
			return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.ExtractTempRefactoring_null_literals);
		} else if (selectedExpression instanceof ArrayInitializer) {
			return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.ExtractTempRefactoring_array_initializer);
		} else if (selectedExpression instanceof Assignment) {
			if (parent instanceof Expression && !(parent instanceof ParenthesizedExpression)) {
				return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.ExtractTempRefactoring_assignment);
			} else {
				return null;
			}
		} else if (selectedExpression instanceof SimpleName) {
			if ((((SimpleName) selectedExpression)).isDeclaration()) {
				return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.ExtractTempRefactoring_names_in_declarations);
			}
			if (parent instanceof QualifiedName && selectedExpression.getLocationInParent() == QualifiedName.NAME_PROPERTY || parent instanceof FieldAccess && selectedExpression.getLocationInParent() == FieldAccess.NAME_PROPERTY) {
				return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.ExtractTempRefactoring_select_expression);
			}
		} else if (selectedExpression instanceof VariableDeclarationExpression && parent instanceof TryStatement) {
			return RefactoringStatus.createFatalErrorStatus(RefactoringCoreMessages.ExtractTempRefactoring_resource_in_try_with_resources);
		}
	}

	return null;
}
 
Example #30
Source File: AbstractExceptionAnalyzer.java    From eclipse.jdt.ls with Eclipse Public License 2.0 5 votes vote down vote up
@Override
public boolean visit(TryStatement node) {
	fCurrentExceptions = new ArrayList<>(1);
	fTryStack.push(fCurrentExceptions);

	// visit try block
	node.getBody().accept(this);

	List<VariableDeclarationExpression> resources = node.resources();
	for (Iterator<VariableDeclarationExpression> iterator = resources.iterator(); iterator.hasNext();) {
		iterator.next().accept(this);
	}

	// Remove those exceptions that get catch by following catch blocks
	List<CatchClause> catchClauses = node.catchClauses();
	if (!catchClauses.isEmpty()) {
		handleCatchArguments(catchClauses);
	}
	List<ITypeBinding> current = fTryStack.pop();
	fCurrentExceptions = fTryStack.peek();
	for (Iterator<ITypeBinding> iter = current.iterator(); iter.hasNext();) {
		addException(iter.next(), node.getAST());
	}

	// visit catch and finally
	for (Iterator<CatchClause> iter = catchClauses.iterator(); iter.hasNext();) {
		iter.next().accept(this);
	}
	if (node.getFinally() != null) {
		node.getFinally().accept(this);
	}

	// return false. We have visited the body by ourselves.
	return false;
}