下面列出了怎么用org.eclipse.jdt.core.dom.ReturnStatement的API类实例代码及写法,或者点击链接到github查看源代码。
private void extractReturnTypeBinding(PDGNode pdgNode, List<ITypeBinding> returnedTypeBindings) {
if(pdgNode instanceof PDGExitNode) {
PDGExitNode exitNode = (PDGExitNode)pdgNode;
ReturnStatement returnStatement = (ReturnStatement)exitNode.getASTStatement();
Expression returnedExpression = returnStatement.getExpression();
if(returnedExpression != null && !(returnedExpression instanceof NullLiteral)) {
ITypeBinding typeBinding = returnedExpression.resolveTypeBinding();
if(typeBinding != null) {
boolean alreadyContained = false;
for(ITypeBinding binding : returnedTypeBindings) {
if(binding.isEqualTo(typeBinding)) {
alreadyContained = true;
break;
}
}
if(!alreadyContained)
returnedTypeBindings.add(typeBinding);
}
}
}
}
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;
}
public ITypeBinding getTypeBinding(AST ast) {
boolean couldBeObject= false;
for (int i= 0; i < fResult.size(); i++) {
ReturnStatement node= fResult.get(i);
Expression expr= node.getExpression();
if (expr != null) {
ITypeBinding binding= Bindings.normalizeTypeBinding(expr.resolveTypeBinding());
if (binding != null) {
return binding;
} else {
couldBeObject= true;
}
} else {
return ast.resolveWellKnownType("void"); //$NON-NLS-1$
}
}
if (couldBeObject) {
return ast.resolveWellKnownType("java.lang.Object"); //$NON-NLS-1$
}
return ast.resolveWellKnownType("void"); //$NON-NLS-1$
}
public static void addMethodReturnsVoidProposals(IInvocationContext context, IProblemLocationCore problem, Collection<ChangeCorrectionProposal> proposals) throws JavaModelException {
CompilationUnit astRoot= context.getASTRoot();
ASTNode selectedNode= problem.getCoveringNode(astRoot);
if (!(selectedNode instanceof ReturnStatement)) {
return;
}
ReturnStatement returnStatement= (ReturnStatement) selectedNode;
Expression expression= returnStatement.getExpression();
if (expression == null) {
return;
}
BodyDeclaration decl= ASTResolving.findParentBodyDeclaration(selectedNode);
if (decl instanceof MethodDeclaration) {
MethodDeclaration methDecl= (MethodDeclaration) decl;
Type retType= methDecl.getReturnType2();
if (retType == null || retType.resolveBinding() == null) {
return;
}
TypeMismatchSubProcessor.addChangeSenderTypeProposals(context, expression, retType.resolveBinding(), false, IProposalRelevance.METHOD_RETURNS_VOID, proposals);
}
}
@Override
public boolean visit(final ReturnStatement node) {
this.appendToBuffer("return");
Expression _expression = node.getExpression();
boolean _tripleNotEquals = (_expression != null);
if (_tripleNotEquals) {
this.appendSpaceToBuffer();
node.getExpression().accept(this);
this.appendSpaceToBuffer();
} else {
final ASTNode parent = node.getParent();
final boolean isIfElse = ((parent instanceof IfStatement) && (((IfStatement) parent).getElseStatement() != null));
if (((!isIfElse) && (!(parent instanceof SwitchStatement)))) {
this.appendToBuffer(";");
}
}
return false;
}
public ITypeBinding getTypeBinding(AST ast) {
boolean couldBeObject= false;
for (int i= 0; i < fResult.size(); i++) {
ReturnStatement node= fResult.get(i);
Expression expr= node.getExpression();
if (expr != null) {
ITypeBinding binding= Bindings.normalizeTypeBinding(expr.resolveTypeBinding());
if (binding != null) {
return binding;
} else {
couldBeObject= true;
}
} else {
return ast.resolveWellKnownType("void"); //$NON-NLS-1$
}
}
if (couldBeObject) {
return ast.resolveWellKnownType("java.lang.Object"); //$NON-NLS-1$
}
return ast.resolveWellKnownType("void"); //$NON-NLS-1$
}
@Override
public void endVisit(ReturnStatement node) {
Expression expression= node.getExpression();
if (expression == null)
return;
ConstraintVariable2 expressionCv= getConstraintVariable(expression);
if (expressionCv == null)
return;
MethodDeclaration methodDeclaration= (MethodDeclaration) ASTNodes.getParent(node, ASTNode.METHOD_DECLARATION);
if (methodDeclaration == null)
return;
IMethodBinding methodBinding= methodDeclaration.resolveBinding();
if (methodBinding == null)
return;
ReturnTypeVariable2 returnTypeCv= fTCModel.makeReturnTypeVariable(methodBinding);
if (returnTypeCv == null)
return;
fTCModel.createElementEqualsConstraints(returnTypeCv, expressionCv);
}
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;
}
private CFGNode createNonCompositeNode(StatementObject statement) {
CFGNode currentNode;
Statement astStatement = statement.getStatement();
if(astStatement instanceof ReturnStatement)
currentNode = new CFGExitNode(statement);
else if(astStatement instanceof SwitchCase)
currentNode = new CFGSwitchCaseNode(statement);
else if(astStatement instanceof BreakStatement)
currentNode = new CFGBreakNode(statement);
else if(astStatement instanceof ContinueStatement)
currentNode = new CFGContinueNode(statement);
else if(astStatement instanceof ThrowStatement)
currentNode = new CFGThrowNode(statement);
else
currentNode = new CFGNode(statement);
directlyNestedNodeInBlock(currentNode);
return currentNode;
}
public static Set<PDGNode> extractConditionalReturnStatements(Set<? extends GraphNode> nodes) {
Set<PDGNode> conditionalReturnStatements = new TreeSet<PDGNode>();
for(GraphNode node : nodes) {
PDGNode pdgNode = (PDGNode)node;
CFGNode cfgNode = pdgNode.getCFGNode();
if(cfgNode instanceof CFGExitNode) {
ReturnStatement returnStatement = (ReturnStatement)cfgNode.getASTStatement();
Expression expression = returnStatement.getExpression();
if(expression != null) {
PDGNode controlParentNode = pdgNode.getControlDependenceParent();
if(controlParentNode instanceof PDGControlPredicateNode) {
conditionalReturnStatements.add(pdgNode);
}
}
}
}
return conditionalReturnStatements;
}
public static void addMethodRetunsVoidProposals(IInvocationContext context, IProblemLocation problem, Collection<ICommandAccess> proposals) throws JavaModelException {
CompilationUnit astRoot= context.getASTRoot();
ASTNode selectedNode= problem.getCoveringNode(astRoot);
if (!(selectedNode instanceof ReturnStatement)) {
return;
}
ReturnStatement returnStatement= (ReturnStatement) selectedNode;
Expression expression= returnStatement.getExpression();
if (expression == null) {
return;
}
BodyDeclaration decl= ASTResolving.findParentBodyDeclaration(selectedNode);
if (decl instanceof MethodDeclaration) {
MethodDeclaration methDecl= (MethodDeclaration) decl;
Type retType= methDecl.getReturnType2();
if (retType == null || retType.resolveBinding() == null) {
return;
}
TypeMismatchSubProcessor.addChangeSenderTypeProposals(context, expression, retType.resolveBinding(), false, IProposalRelevance.METHOD_RETURNS_VOID, proposals);
}
}
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;
}
@Override
protected void complete() throws CoreException {
super.complete();
ReturnStatement rStatement= fAst.newReturnStatement();
String formatClass;
if (getContext().is50orHigher())
formatClass= "java.lang.String"; //$NON-NLS-1$
else
formatClass= "java.text.MessageFormat"; //$NON-NLS-1$
MethodInvocation formatInvocation= createMethodInvocation(addImport(formatClass), "format", null); //$NON-NLS-1$
StringLiteral literal= fAst.newStringLiteral();
literal.setLiteralValue(buffer.toString());
formatInvocation.arguments().add(literal);
if (getContext().is50orHigher()) {
formatInvocation.arguments().addAll(arguments);
} else {
ArrayCreation arrayCreation= fAst.newArrayCreation();
arrayCreation.setType(fAst.newArrayType(fAst.newSimpleType(addImport("java.lang.Object")))); //$NON-NLS-1$
ArrayInitializer initializer= fAst.newArrayInitializer();
arrayCreation.setInitializer(initializer);
initializer.expressions().addAll(arguments);
formatInvocation.arguments().add(arrayCreation);
}
rStatement.setExpression(formatInvocation);
toStringMethod.getBody().statements().add(rStatement);
}
private MethodDeclaration createGetOuterHelper() {
String outerTypeName= fType.getDeclaringClass().getTypeDeclaration().getName();
MethodDeclaration helperMethod= fAst.newMethodDeclaration();
helperMethod.modifiers().addAll(ASTNodeFactory.newModifiers(fAst, Modifier.PRIVATE));
helperMethod.setName(fAst.newSimpleName(METHODNAME_OUTER_TYPE));
helperMethod.setConstructor(false);
helperMethod.setReturnType2(fAst.newSimpleType(fAst.newSimpleName(outerTypeName)));
Block body= fAst.newBlock();
helperMethod.setBody(body);
ThisExpression thisExpression= fAst.newThisExpression();
thisExpression.setQualifier(fAst.newSimpleName(outerTypeName));
ReturnStatement endReturn= fAst.newReturnStatement();
endReturn.setExpression(thisExpression);
body.statements().add(endReturn);
return helperMethod;
}
/**
* Returns a collection of return statements withing @param methodDeclaration.
* */
public static Collection<ReturnStatement> findReturns(IProgressMonitor progressMonitor, MethodDeclaration methodDeclaration, JavaProject project) {
progressMonitor.setTaskName("Looking for returns in " + methodDeclaration.getName());
final Collection<ReturnStatement> returns = new ArrayList<ReturnStatement>();
ASTVisitor finder = new ASTVisitor() {
public boolean visit(ReturnStatement node) {
return returns.add(node);
}
};
methodDeclaration.accept(finder);
return returns;
}
public boolean visit(ReturnStatement node) {
int start = _unit.getLineNumber(node.getStartPosition());
if(start == _extendedLine){
_extendedStatement = node;
return false;
}
return true;
}
public Block createBody(AST ast, TypeDeclaration originalType) {
ClassInstanceCreation newClassInstanceCreation = ast.newClassInstanceCreation();
newClassInstanceCreation.setType(ast.newSimpleType(ast.newName(originalType.getName().toString())));
newClassInstanceCreation.arguments().add(ast.newThisExpression());
ReturnStatement statement = ast.newReturnStatement();
statement.setExpression(newClassInstanceCreation);
Block block = ast.newBlock();
block.statements().add(statement);
return block;
}
public Block createReturnBlock(AST ast, TypeDeclaration builderType, String withName, String parameterName) {
Block builderMethodBlock = ast.newBlock();
ReturnStatement returnStatement = ast.newReturnStatement();
ClassInstanceCreation newClassInstanceCreation = ast.newClassInstanceCreation();
newClassInstanceCreation.setType(ast.newSimpleType(ast.newName(builderType.getName().toString())));
MethodInvocation withMethodInvocation = ast.newMethodInvocation();
withMethodInvocation.setExpression(newClassInstanceCreation);
withMethodInvocation.setName(ast.newSimpleName(withName));
withMethodInvocation.arguments().add(ast.newSimpleName(parameterName));
returnStatement.setExpression(withMethodInvocation);
builderMethodBlock.statements().add(returnStatement);
return builderMethodBlock;
}
public Block createReturnBlock(AST ast, TypeDeclaration builderType) {
Block builderMethodBlock = ast.newBlock();
ReturnStatement returnStatement = ast.newReturnStatement();
ClassInstanceCreation newClassInstanceCreation = ast.newClassInstanceCreation();
newClassInstanceCreation.setType(ast.newSimpleType(ast.newName(builderType.getName().toString())));
returnStatement.setExpression(newClassInstanceCreation);
builderMethodBlock.statements().add(returnStatement);
return builderMethodBlock;
}
private static Block getBlockBodyForLambda(Expression bodyExpr, ITypeBinding returnTypeBinding, AST ast) {
Statement statementInBlockBody;
if (ast.resolveWellKnownType("void").isEqualTo(returnTypeBinding)) { //$NON-NLS-1$
ExpressionStatement expressionStatement = ast.newExpressionStatement(bodyExpr);
statementInBlockBody = expressionStatement;
} else {
ReturnStatement returnStatement = ast.newReturnStatement();
returnStatement.setExpression(bodyExpr);
statementInBlockBody = returnStatement;
}
Block blockBody = ast.newBlock();
blockBody.statements().add(statementInBlockBody);
return blockBody;
}
private static AbstractControlStructure generateAbstractControlStructure(Object object)
{
if (object instanceof IfStatement)
{
return new IfControlStructure((IfStatement) object);
}
else if (object instanceof SwitchStatement)
{
return new SwitchControlStructure((SwitchStatement) object);
}
else if (object instanceof ExpressionStatement)
{
ExpressionStatement expressionStatement = (ExpressionStatement) object;
if (AbstractControlStructureUtilities.hasOneConditionalExpression(expressionStatement) != null)
{
return new TernaryControlStructure(expressionStatement);
}
}
else if (object instanceof ReturnStatement)
{
ReturnStatement returnStatement = (ReturnStatement) object;
if (returnStatement.getExpression() instanceof ConditionalExpression)
{
return new TernaryControlStructure(returnStatement);
}
}
return null;
}
private void replaceSelectedExpressionWithTempDeclaration() throws CoreException {
ASTRewrite rewrite = fCURewrite.getASTRewrite();
Expression selectedExpression = getSelectedExpression().getAssociatedExpression(); // whole expression selected
Expression initializer = (Expression) rewrite.createMoveTarget(selectedExpression);
VariableDeclarationStatement tempDeclaration = createTempDeclaration(initializer);
ASTNode replacement;
ASTNode parent = selectedExpression.getParent();
boolean isParentLambda = parent instanceof LambdaExpression;
AST ast = rewrite.getAST();
if (isParentLambda) {
Block blockBody = ast.newBlock();
blockBody.statements().add(tempDeclaration);
if (!Bindings.isVoidType(((LambdaExpression) parent).resolveMethodBinding().getReturnType())) {
List<VariableDeclarationFragment> fragments = tempDeclaration.fragments();
SimpleName varName = fragments.get(0).getName();
ReturnStatement returnStatement = ast.newReturnStatement();
returnStatement.setExpression(ast.newSimpleName(varName.getIdentifier()));
blockBody.statements().add(returnStatement);
}
replacement = blockBody;
} else if (ASTNodes.isControlStatementBody(parent.getLocationInParent())) {
Block block = ast.newBlock();
block.statements().add(tempDeclaration);
replacement = block;
} else {
replacement = tempDeclaration;
}
ASTNode replacee = isParentLambda || !ASTNodes.hasSemicolon((ExpressionStatement) parent, fCu) ? selectedExpression : parent;
rewrite.replace(replacee, replacement, fCURewrite.createGroupDescription(RefactoringCoreMessages.ExtractTempRefactoring_declare_local_variable));
}
private MethodDeclaration createGetterMethod(AST ast, ASTRewrite rewriter, String lineDelimiter) throws CoreException {
FieldDeclaration field = ASTNodes.getParent(fFieldDeclaration, FieldDeclaration.class);
Type type = field.getType();
MethodDeclaration result = ast.newMethodDeclaration();
result.setName(ast.newSimpleName(fGetterName));
result.modifiers().addAll(ASTNodeFactory.newModifiers(ast, createModifiers()));
Type returnType = DimensionRewrite.copyTypeAndAddDimensions(type, fFieldDeclaration.extraDimensions(), rewriter);
result.setReturnType2(returnType);
Block block = ast.newBlock();
result.setBody(block);
String body = CodeGeneration.getGetterMethodBodyContent(fField.getCompilationUnit(), getTypeName(field.getParent()), fGetterName, fField.getElementName(), lineDelimiter);
if (body != null) {
body = body.substring(0, body.lastIndexOf(lineDelimiter));
ASTNode getterNode = rewriter.createStringPlaceholder(body, ASTNode.BLOCK);
block.statements().add(getterNode);
} else {
ReturnStatement rs = ast.newReturnStatement();
rs.setExpression(ast.newSimpleName(fField.getElementName()));
block.statements().add(rs);
}
if (fGenerateJavadoc) {
String string = CodeGeneration.getGetterComment(fField.getCompilationUnit(), getTypeName(field.getParent()), fGetterName, fField.getElementName(), ASTNodes.asString(type), StubUtility.getBaseName(fField), lineDelimiter);
if (string != null) {
Javadoc javadoc = (Javadoc) fRewriter.createStringPlaceholder(string, ASTNode.JAVADOC);
result.setJavadoc(javadoc);
}
}
return result;
}
private boolean previousNodesContainBreakOrReturn(List<CFGNode> previousNodes, CompositeStatementObject composite) {
for(CFGNode previousNode : previousNodes) {
Statement statement = previousNode.getASTStatement();
if((statement instanceof BreakStatement || statement instanceof ReturnStatement) &&
directlyNestedNode(previousNode, composite))
return true;
}
return false;
}
private Block createRunMethodBody(ASTRewrite rewrite, ClassInstanceCreation classLoaderCreation) {
AST ast = rewrite.getAST();
Block methodBody = ast.newBlock();
ReturnStatement returnStatement = ast.newReturnStatement();
List<Statement> statements = checkedList(methodBody.statements());
statements.add(returnStatement);
returnStatement.setExpression((ClassInstanceCreation) rewrite.createCopyTarget(classLoaderCreation));
return methodBody;
}
private static Block createMethodStub(final MethodDeclaration method, final AST ast) {
final Block body= ast.newBlock();
final Expression expression= ASTNodeFactory.newDefaultExpression(ast, method.getReturnType2(), method.getExtraDimensions());
if (expression != null) {
final ReturnStatement returnStatement= ast.newReturnStatement();
returnStatement.setExpression(expression);
body.statements().add(returnStatement);
}
return body;
}
@Override
public boolean visit(ReturnStatement node) {
Expression expression= node.getExpression();
if (!(ASTNodes.isLiteral(expression) || expression instanceof Name)) {
fMustEvalReturnedExpression= true;
}
if (Invocations.isInvocation(expression) || expression instanceof ClassInstanceCreation) {
fReturnValueNeedsLocalVariable= false;
}
fReturnExpressions.add(expression);
return false;
}
public boolean needsReturnedExpressionParenthesis(ASTNode parent, StructuralPropertyDescriptor locationInParent) {
ASTNode last= getLastStatement();
if (last instanceof ReturnStatement) {
return NecessaryParenthesesChecker.needsParentheses(((ReturnStatement)last).getExpression(), parent, locationInParent);
}
return false;
}
public boolean match(ReturnStatement node, Object other) {
if (node.getExpression() instanceof ConditionalExpression && other instanceof IfStatement)
{
TernaryControlStructure nodeTernaryControlStructure = new TernaryControlStructure(node);
return ifMatch(nodeTernaryControlStructure, other);
}
return super.match(node, other);
}
private void conditionalReturnStatement(NodeMapping nodeMapping, PDGNode node) {
CFGNode cfgNode = node.getCFGNode();
if(cfgNode instanceof CFGExitNode) {
ReturnStatement returnStatement = (ReturnStatement)cfgNode.getASTStatement();
if(returnStatement.getExpression() == null) {
PreconditionViolation violation = new StatementPreconditionViolation(node.getStatement(),
PreconditionViolationType.CONDITIONAL_RETURN_STATEMENT);
nodeMapping.addPreconditionViolation(violation);
preconditionViolations.add(violation);
}
}
}