下面列出了com.sun.source.tree.ThrowTree#com.sun.source.tree.ReturnTree 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
private static List<? extends TypeMirror> computeReturn(Set<ElementKind> types, CompilationInfo info, TreePath parent, Tree error, int offset) {
ReturnTree rt = (ReturnTree) parent.getLeaf();
if (rt.getExpression() == error) {
TreePath method = findMethod(parent);
if (method == null) {
return null;
}
Element el = info.getTrees().getElement(method);
if (el == null || el.getKind() != ElementKind.METHOD) {
return null;
}
types.add(ElementKind.PARAMETER);
types.add(ElementKind.LOCAL_VARIABLE);
types.add(ElementKind.FIELD);
return Collections.singletonList(((ExecutableElement) el).getReturnType());
}
return null;
}
@Override
protected void performRewrite(TransformationContext ctx) throws Exception {
TreePath retPath = ctx.getPath();
if (retPath.getLeaf().getKind() != Tree.Kind.RETURN) {
return;
}
ReturnTree rtt = (ReturnTree)retPath.getLeaf();
if (rtt.getExpression() == null) {
return;
}
WorkingCopy wc = ctx.getWorkingCopy();
ExpressionToStatement st = new ExpressionToStatement(wc.getTreeMaker(), wc);
st.scan(new TreePath(retPath, rtt.getExpression()), null);
if (st.remove || st.statements.isEmpty()) {
// error, but I don't have an utility to properly remove the statement
// from its parent now.
return;
}
Utilities.replaceStatement(wc, retPath, st.statements);
}
public void performRewriteToMemberReference() {
MethodTree methodTree = getMethodFromFunctionalInterface(newClassTree);
if (methodTree.getBody() == null || methodTree.getBody().getStatements().size() != 1)
return;
Tree tree = methodTree.getBody().getStatements().get(0);
if (tree.getKind() == Tree.Kind.EXPRESSION_STATEMENT) {
tree = ((ExpressionStatementTree)tree).getExpression();
} else if (tree.getKind() == Tree.Kind.RETURN) {
tree = ((ReturnTree)tree).getExpression();
} else {
return;
}
Tree changed = null;
if (tree.getKind() == Tree.Kind.METHOD_INVOCATION) {
changed = methodInvocationToMemberReference(copy, tree, pathToNewClassTree, methodTree.getParameters(),
preconditionChecker.needsCastToExpectedType());
} else if (tree.getKind() == Tree.Kind.NEW_CLASS) {
changed = newClassToConstructorReference(copy, tree, pathToNewClassTree, methodTree.getParameters(), preconditionChecker.needsCastToExpectedType());
}
if (changed != null) {
copy.rewrite(newClassTree, changed);
}
}
public Boolean visitReturn(ReturnTree node, ConstructorData p) {
super.visitReturn(node, p);
variable2State = new HashMap< Element, State>(variable2State);
if (pendingFinally.isEmpty()) {
//performance: limit amount of held variables and their mapping:
for ( Element ve : currentMethodVariables) {
variable2State.remove(ve);
}
}
resumeAfter(nearestMethod, variable2State);
removeAllDefinitions();
return null;
}
/**
* Replaces former exit points by returns and/or adds a return with value at the end of the method
*/
private void makeReturnsFromExtractedMethod(List<StatementTree> methodStatements) {
if (returnSingleValue) {
return;
}
if (resolvedExits != null) {
for (TreePath resolved : resolvedExits) {
ReturnTree r = makeExtractedReturn(true);
GeneratorUtilities.get(copy).copyComments(resolved.getLeaf(), r, false);
GeneratorUtilities.get(copy).copyComments(resolved.getLeaf(), r, true);
copy.rewrite(resolved.getLeaf(), r);
}
// the default exit path, should return false
if (outcomeVariable == null && !exitsFromAllBranches) {
methodStatements.add(make.Return(make.Literal(false)));
}
} else {
ReturnTree ret = makeExtractedReturn(false);
if (ret != null) {
methodStatements.add(ret);
}
}
}
private static List<? extends TypeMirror> computeReturn(Set<ElementKind> types, CompilationInfo info, TreePath parent, Tree error, int offset) {
ReturnTree rt = (ReturnTree) parent.getLeaf();
if (rt.getExpression() == error) {
TreePath method = findMethod(parent);
if (method == null) {
return null;
}
Element el = info.getTrees().getElement(method);
if (el == null || el.getKind() != ElementKind.METHOD) {
return null;
}
types.add(ElementKind.PARAMETER);
types.add(ElementKind.LOCAL_VARIABLE);
types.add(ElementKind.FIELD);
return Collections.singletonList(((ExecutableElement) el).getReturnType());
}
return null;
}
@Override
public List<? extends TypeMirror> visitReturn(ReturnTree node, Object p) {
if (node.getExpression() == null) {
return null;
}
if (theExpression == null) {
initExpression(node.getExpression());
}
TreePath parents = getCurrentPath();
while (parents != null && parents.getLeaf().getKind() != Tree.Kind.METHOD) {
parents = parents.getParentPath();
}
if (parents != null) {
Tree returnTypeTree = ((MethodTree) parents.getLeaf()).getReturnType();
if (returnTypeTree != null) {
return Collections.singletonList(info.getTrees().getTypeMirror(new TreePath(parents, returnTypeTree)));
}
}
return null;
}
@Override
public Void visitReturn(ReturnTree node, Void p) {
if (isMethodCode() /*&& phase == PHASE_INSIDE_SELECTION*/) {
hasReturns = true;
TypeMirror type = info.getTrees().getTypeMirror(new TreePath(getCurrentPath(), node.getExpression())); //.asType().toString();
if (type != null && type.getKind() != TypeKind.ERROR) {
returnTypes.add(type);
} else {
// Unresolved element
TypeElement object = info.getElements().getTypeElement("java.lang.Object");
if (object != null) {
returnTypes.add(object.asType());
}
}
}
return super.visitReturn(node, p);
}
private MethodTree createGetter(ModifiersTree mods, TypeMirror valueType) {
StringBuilder getterName = GeneratorUtils.getCapitalizedName(config.getName());
getterName.insert(0, valueType.getKind() == TypeKind.BOOLEAN ? "is" : "get");
ReturnTree returnTree = make.Return(make.MethodInvocation(Collections.emptyList(), make.MemberSelect(make.Identifier(config.getName()), hasGet ? "get" : "getValue"), Collections.emptyList()));
BlockTree getterBody = make.Block(Collections.singletonList(returnTree), false);
Tree valueTree;
if (valueType.getKind() == TypeKind.DECLARED) {
valueTree = make.QualIdent(((DeclaredType) valueType).asElement());
} else if (valueType.getKind().isPrimitive()) {
valueTree = make.PrimitiveType(valueType.getKind());
} else {
valueTree = make.Identifier(valueType.toString());
}
MethodTree getter = make.Method(mods, getterName, valueTree, Collections.emptyList(), Collections.emptyList(), Collections.emptyList(), getterBody, null);
return getter;
}
@Override
public void onMatchReturn(NullAway analysis, ReturnTree tree, VisitorState state) {
// Figure out the enclosing method node
TreePath enclosingMethodOrLambda =
NullabilityUtil.findEnclosingMethodOrLambdaOrInitializer(state.getPath());
if (enclosingMethodOrLambda == null) {
throw new RuntimeException("no enclosing method, lambda or initializer!");
}
if (!(enclosingMethodOrLambda.getLeaf() instanceof MethodTree
|| enclosingMethodOrLambda.getLeaf() instanceof LambdaExpressionTree)) {
throw new RuntimeException(
"return statement outside of a method or lambda! (e.g. in an initializer block)");
}
Tree leaf = enclosingMethodOrLambda.getLeaf();
if (filterMethodOrLambdaSet.contains(leaf)) {
returnToEnclosingMethodOrLambda.put(tree, leaf);
// We need to manually trigger the dataflow analysis to run on the filter method,
// this ensures onDataflowVisitReturn(...) gets called for all return statements in this
// method before
// onDataflowInitialStore(...) is called for all successor methods in the observable chain.
// Caching should prevent us from re-analyzing any given method.
AccessPathNullnessAnalysis nullnessAnalysis = analysis.getNullnessAnalysis(state);
nullnessAnalysis.forceRunOnMethod(new TreePath(state.getPath(), leaf), state.context);
}
}
@Override
public void onDataflowVisitReturn(
ReturnTree tree, NullnessStore thenStore, NullnessStore elseStore) {
if (returnToEnclosingMethodOrLambda.containsKey(tree)) {
Tree filterTree = returnToEnclosingMethodOrLambda.get(tree);
assert (filterTree instanceof MethodTree || filterTree instanceof LambdaExpressionTree);
ExpressionTree retExpression = tree.getExpression();
if (canBooleanExpressionEvalToTrue(retExpression)) {
if (filterToNSMap.containsKey(filterTree)) {
filterToNSMap.put(filterTree, filterToNSMap.get(filterTree).leastUpperBound(thenStore));
} else {
filterToNSMap.put(filterTree, thenStore);
}
}
}
}
@Override
public boolean matches(final Tree tree, final VisitorState state) {
if ((tree instanceof ReturnTree) && (((ReturnTree) tree).getExpression() != null)) {
return ((ReturnTree) tree).getExpression().getKind() == NULL_LITERAL;
}
return false;
}
@Override
public Void visitReturn(ReturnTree node, Void unused) {
sync(node);
token("return");
if (node.getExpression() != null) {
builder.space();
scan(node.getExpression(), null);
}
token(";");
return null;
}
@Override
public boolean matches(final Tree tree, final VisitorState state) {
if ((tree instanceof ReturnTree) && (((ReturnTree) tree).getExpression() != null)) {
return ((ReturnTree) tree).getExpression().getKind() == NULL_LITERAL;
}
return false;
}
@Override
public Description matchReturn(ReturnTree tree, VisitorState state) {
if (overLaps(tree, state)) {
return Description.NO_MATCH;
}
ExpressionTree et = tree.getExpression();
if (et != null && et.getKind().equals(Kind.BOOLEAN_LITERAL)) {
return Description.NO_MATCH;
}
Value x = evalExpr(et, state);
boolean update = false;
String replacementString = EMPTY;
if (x.equals(Value.TRUE)) {
update = true;
replacementString = TRUE;
} else if (x.equals(Value.FALSE)) {
update = true;
replacementString = FALSE;
}
if (update) {
Description.Builder builder = buildDescription(tree);
SuggestedFix.Builder fixBuilder = SuggestedFix.builder();
fixBuilder.replace(et, replacementString);
decrementAllSymbolUsages(et, state, fixBuilder);
builder.addFix(fixBuilder.build());
endPos = state.getEndPosition(tree);
return builder.build();
}
return Description.NO_MATCH;
}
/** Is the statement a return statement, or is it a block that ends in a return statement? */
private boolean endsWithReturn(StatementTree stmt) {
if (stmt instanceof ReturnTree) {
return true;
}
if (stmt instanceof BlockTree) {
List<? extends StatementTree> statements = ((BlockTree) stmt).getStatements();
return statements.size() > 0 && statements.get(statements.size() - 1) instanceof ReturnTree;
}
return false;
}
@Override
public Tree visitReturn(ReturnTree tree, Void p) {
ReturnTree n = make.Return(tree.getExpression());
model.setType(n, model.getType(tree));
comments.copyComments(tree, n);
model.setPos(n, model.getPos(tree));
return n;
}
public Boolean visitReturn(ReturnTree node, TreePath p) {
if (p == null) {
super.visitReturn(node, p);
return false;
}
ReturnTree at = (ReturnTree) p.getLeaf();
return scan(node.getExpression(), at.getExpression(), p);
}
public void testLambdaFullBody2Expression() throws Exception {
testFile = new File(getWorkDir(), "Test.java");
TestUtilities.copyStringToFile(testFile,
"package hierbas.del.litoral;\n\n" +
"public class Test {\n" +
" public static void taragui() {\n" +
" ChangeListener l = (e) -> {return 1;};\n" +
" }\n" +
"}\n"
);
String golden =
"package hierbas.del.litoral;\n\n" +
"public class Test {\n" +
" public static void taragui() {\n" +
" ChangeListener l = (e) -> 1;\n" +
" }\n" +
"}\n";
JavaSource src = getJavaSource(testFile);
Task<WorkingCopy> task = new Task<WorkingCopy>() {
public void run(final WorkingCopy workingCopy) throws IOException {
workingCopy.toPhase(Phase.RESOLVED);
final TreeMaker make = workingCopy.getTreeMaker();
new ErrorAwareTreeScanner<Void, Void>() {
@Override public Void visitLambdaExpression(LambdaExpressionTree node, Void p) {
ReturnTree t = (ReturnTree) ((BlockTree) node.getBody()).getStatements().get(0);
workingCopy.rewrite(node, make.setLambdaBody(node, t.getExpression()));
return super.visitLambdaExpression(node, p);
}
}.scan(workingCopy.getCompilationUnit(), null);
}
};
src.runModificationTask(task).commit();
String res = TestUtilities.copyFileToString(testFile);
//System.err.println(res);
assertEquals(golden, res);
}
@Override
public Boolean visitReturn(ReturnTree tree, Stack<Tree> d) {
if (exceptions == null) {
if (doExitPoints) {
addHighlightFor(tree);
}
}
super.visitReturn(tree, d);
return Boolean.TRUE;
}
@Override
public Object visitReturn(ReturnTree node, Object p) {
TreePath path = getCurrentPath();
TreePath parentPath = path.getParentPath();
if (suppress) {
return super.visitReturn(node, p);
}
if (ignoreGuards && parentPath != null) {
Tree parentTree = parentPath.getLeaf();
TreePath branchPath = path;
while (parentTree.getKind() == Tree.Kind.BLOCK) {
branchPath = parentPath;
parentPath = parentPath.getParentPath();
parentTree = parentPath.getLeaf();
}
if (parentTree.getKind() == Tree.Kind.IF) {
IfTree ifTree = (IfTree)parentTree;
StatementTree trueTree = ifTree.getThenStatement() == branchPath.getLeaf() ?
ifTree.getThenStatement() : ifTree.getElseStatement();
if (trueTree == node) {
return super.visitReturn(node, p);
}
if (trueTree.getKind() == Tree.Kind.BLOCK) {
BlockTree bt = (BlockTree)trueTree;
if (bt.getStatements().size() == 1) {
return super.visitReturn(node, p);
}
}
}
}
returnCount++;
return super.visitReturn(node, p);
}
@Override
public Void visitReturn(ReturnTree tree, List<Node> d) {
List<Node> below = new ArrayList<Node>();
addCorrespondingType(below);
addCorrespondingComments(below);
super.visitReturn(tree, below);
d.add(new TreeNode(info, getCurrentPath(), below));
return null;
}
private StatementTree propagateReturn( ProspectiveOperation lastOperation, MethodInvocationTree mi, TreeMaker treeMaker) {
ReturnTree returnExpre = null;
ExpressionTree pred = null;
if ("anyMatch".equals(lastOperation.getSuitableMethod())) {
pred = mi;
returnExpre = treeMaker.Return(treeMaker.Literal(true));
} else if ("noneMatch".equals(lastOperation.getSuitableMethod())) {
pred = treeMaker.Unary(Tree.Kind.LOGICAL_COMPLEMENT, mi);
returnExpre = treeMaker.Return(treeMaker.Literal(false));
}
return treeMaker.If(pred, returnExpre, null);
}
private List<ProspectiveOperation> getIfListRepresentation( StatementTree tree, boolean last) {
IfTree ifTree = (IfTree) tree;
List<ProspectiveOperation> ls = new ArrayList<ProspectiveOperation>();
if (ifTree.getElseStatement() == null) {
StatementTree then = ifTree.getThenStatement();
if (isOneStatementBlock(then)) {
then = ((BlockTree) then).getStatements().get(0);
}
if (then.getKind() == Tree.Kind.RETURN) {
ReturnTree returnTree = (ReturnTree) then;
ExpressionTree returnExpression = returnTree.getExpression();
if (returnExpression.getKind() == Tree.Kind.BOOLEAN_LITERAL && ((LiteralTree) returnExpression).getValue().equals(true)) {
ls.addAll(ProspectiveOperation.createOperator(ifTree, ProspectiveOperation.OperationType.ANYMATCH, this.preconditionsChecker, this.workingCopy));
} else if (returnExpression.getKind() == Tree.Kind.BOOLEAN_LITERAL && ((LiteralTree) returnExpression).getValue().equals(false)) {
ls.addAll(ProspectiveOperation.createOperator(ifTree, ProspectiveOperation.OperationType.NONEMATCH, this.preconditionsChecker, this.workingCopy));
}
} else {
ls.addAll(ProspectiveOperation.createOperator(ifTree, ProspectiveOperation.OperationType.FILTER, this.preconditionsChecker, this.workingCopy));
ls.addAll(getListRepresentation(ifTree.getThenStatement(), last));
}
} else {
ls.addAll(ProspectiveOperation.createOperator(ifTree, ProspectiveOperation.OperationType.MAP, this.preconditionsChecker, this.workingCopy));
}
return ls;
}
@Override
public Tree visitReturn(ReturnTree that, Trees trees) {
ExpressionTree thatExpression = that.getExpression();
if (!this.hasMatcherReturn && thatExpression != null && thatExpression.getKind() == Tree.Kind.BOOLEAN_LITERAL
&& thisIsMatcherReturn(that, this.getCurrentPath())) {
this.hasMatcherReturn = true;
} else {
this.hasReturns = true;
}
return super.visitReturn(that, trees);
}
@Override
public State visitReturn(ReturnTree node, Void p) {
State s;
if (returnIfRecurse(s = scan(node.getExpression(), p))) {
return s;
}
return knownResult = State.RETURN;
}
@Override
public Void visitReturn(ReturnTree node, Collection<TreePath> trees) {
if (!analyzeThrows) {
trees.add(getCurrentPath());
}
return null;
}
@Override
public Boolean visitReturn(ReturnTree node, Void p) {
if (scan(node.getExpression(), p) == Boolean.TRUE) {
returned = true;
}
return false;
}
/**
* Creates a return statement tree from the extracted method, depending on return type and/or branching
*/
private ReturnTree makeExtractedReturn(boolean forceReturn) {
if (outcomeVariable != null) {
return make.Return(make.Identifier(outcomeVariable.getSimpleName()));
} else if (forceReturn) {
return make.Return(exitsFromAllBranches ? null : make.Literal(true));
} else {
return null;
}
}
@Override
public Void visitReturn(ReturnTree node, Void p) {
if (isMethodCode() && phase == PHASE_INSIDE_SELECTION) {
selectionExits.add(getCurrentPath());
hasReturns = true;
}
return super.visitReturn(node, p);
}