com.sun.source.tree.ReturnTree Java Examples

The following examples show how to use com.sun.source.tree.ReturnTree. 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: IntroduceMethodFix.java    From netbeans with Apache License 2.0 6 votes vote down vote up
/**
 * 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);
        }
    }
}
 
Example #2
Source File: Flow.java    From netbeans with Apache License 2.0 6 votes vote down vote up
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;
}
 
Example #3
Source File: CreateElementUtilities.java    From netbeans with Apache License 2.0 6 votes vote down vote up
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;
}
 
Example #4
Source File: ExpectedTypeResolver.java    From netbeans with Apache License 2.0 6 votes vote down vote up
@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;
}
 
Example #5
Source File: StreamNullabilityPropagator.java    From NullAway with MIT License 6 votes vote down vote up
@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);
      }
    }
  }
}
 
Example #6
Source File: StreamNullabilityPropagator.java    From NullAway with MIT License 6 votes vote down vote up
@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);
  }
}
 
Example #7
Source File: CreateElementUtilities.java    From netbeans with Apache License 2.0 6 votes vote down vote up
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;
}
 
Example #8
Source File: AddJavaFXPropertyMaker.java    From netbeans with Apache License 2.0 6 votes vote down vote up
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;
}
 
Example #9
Source File: ScanLocalVars.java    From netbeans with Apache License 2.0 6 votes vote down vote up
@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);
}
 
Example #10
Source File: RemoveUnnecessary.java    From netbeans with Apache License 2.0 6 votes vote down vote up
@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);
}
 
Example #11
Source File: ConvertToLambdaConverter.java    From netbeans with Apache License 2.0 6 votes vote down vote up
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);
    }
}
 
Example #12
Source File: LambdaTest.java    From netbeans with Apache License 2.0 5 votes vote down vote up
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);
}
 
Example #13
Source File: ScanStatement.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@Override
public Void visitReturn(ReturnTree node, Void p) {
    if (isMethodCode() && phase == PHASE_INSIDE_SELECTION) {
        selectionExits.add(getCurrentPath());
        hasReturns = true;
    }
    return super.visitReturn(node, p);
}
 
Example #14
Source File: Lambda.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@Override
protected void performRewrite(TransformationContext ctx) throws Exception {
    final WorkingCopy copy = ctx.getWorkingCopy();
    TypeMirror samType = copy.getTrees().getTypeMirror(ctx.getPath());
    if (samType == null || samType.getKind() != TypeKind.DECLARED) {
        // FIXME: report
        return ;
    }

    LambdaExpressionTree lambda = (LambdaExpressionTree) ctx.getPath().getLeaf();
    Tree tree = lambda.getBody();
    if (tree.getKind() == Tree.Kind.BLOCK) {
        if (((BlockTree)tree).getStatements().size() == 1) {
            tree = ((BlockTree)tree).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;
            }
        } else {
            return;
        }
    }

    Tree changed = null;
    if (tree.getKind() == Tree.Kind.METHOD_INVOCATION) {
        changed = ConvertToLambdaConverter.methodInvocationToMemberReference(copy, tree, ctx.getPath(), lambda.getParameters(), false);
    } else if (tree.getKind() == Tree.Kind.NEW_CLASS) {
        changed = ConvertToLambdaConverter.newClassToConstructorReference(copy, tree, ctx.getPath(), lambda.getParameters(), false);
    }
    if (changed != null) {
        copy.rewrite(lambda, changed);
    }
}
 
Example #15
Source File: RefFinderTest.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private void prepareStandardTest(String className, String methodName) throws Exception {
    if (methodName == null) {
         methodName = getName();
         methodName = Character.toLowerCase(methodName.charAt(4)) + 
         methodName.substring(5);
    }
    prepareFileTest(false, "Test.java", "Base.java");
    String pn = getMyPackageName();
    TypeElement tel = info.getElements().getTypeElement(pn + "." + className);
    for (ExecutableElement e : ElementFilter.methodsIn(tel.getEnclosedElements())) {
        if (e.getSimpleName().contentEquals(methodName)) {
            testMethod = e;
            
            MethodTree  mt = (MethodTree)info.getTrees().getTree(testMethod);
            testMethodTree = mt;
            List<? extends StatementTree> stmts = mt.getBody().getStatements();
            Tree t = stmts.get(0);
            if (t.getKind() == Tree.Kind.RETURN) {
                t = ((ReturnTree)t).getExpression();
            } else if (stmts.size() > 1) {
                t = mt.getBody();
            }
            this.expressionTree = t;
            return;
        }
    }
    fail("Testcase method source not found");
}
 
Example #16
Source File: ExpressionScanner.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@Override
public List<Tree> visitReturn(ReturnTree node, ExpressionsInfo p) {
    if (acceptsTree(node)) {
        return scan(node.getExpression(), p);
    } else {
        return null;
    }
}
 
Example #17
Source File: JavaInputAstVisitor.java    From java-n-IDE-for-Android with Apache License 2.0 5 votes vote down vote up
@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;
}
 
Example #18
Source File: AddJavaFXPropertyMaker.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private MethodTree createProperty(ModifiersTree mods, DeclaredType selectedType, ExecutableElement wrapperMethod) {
    String getterName = config.getName() + "Property";
    ExpressionTree expression;
    if (wrapperMethod == null) {
        expression = make.Identifier(config.getName());
    } else {
        expression = make.MethodInvocation(Collections.emptyList(), make.MemberSelect(make.Identifier(config.getName()), wrapperMethod.getSimpleName()), Collections.emptyList());
    }
    ReturnTree returnTree = make.Return(expression);
    BlockTree getterBody = make.Block(Collections.singletonList(returnTree), false);
    MethodTree getter = make.Method(mods, getterName, selectedType == null ? make.Identifier(config.getPropertyType()) : make.QualIdent(selectedType.asElement()), Collections.emptyList(), Collections.emptyList(), Collections.emptyList(), getterBody, null);
    return getter;
}
 
Example #19
Source File: CompositeHandler.java    From NullAway with MIT License 5 votes vote down vote up
@Override
public void onDataflowVisitReturn(
    ReturnTree tree, NullnessStore thenStore, NullnessStore elseStore) {
  for (Handler h : handlers) {
    h.onDataflowVisitReturn(tree, thenStore, elseStore);
  }
}
 
Example #20
Source File: NullAway.java    From NullAway with MIT License 5 votes vote down vote up
/**
 * We are trying to see if (1) we are in a method guaranteed to return something non-null, and (2)
 * this return statement can return something null.
 */
@Override
public Description matchReturn(ReturnTree tree, VisitorState state) {
  if (!matchWithinClass) {
    return Description.NO_MATCH;
  }
  handler.onMatchReturn(this, tree, state);
  ExpressionTree retExpr = tree.getExpression();
  // let's do quick checks on returned expression first
  if (retExpr == null) {
    return Description.NO_MATCH;
  }
  // now let's check the enclosing method
  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();
  Symbol.MethodSymbol methodSymbol;
  if (leaf instanceof MethodTree) {
    MethodTree enclosingMethod = (MethodTree) leaf;
    methodSymbol = ASTHelpers.getSymbol(enclosingMethod);
  } else {
    // we have a lambda
    methodSymbol =
        NullabilityUtil.getFunctionalInterfaceMethod(
            (LambdaExpressionTree) leaf, state.getTypes());
  }
  return checkReturnExpression(tree, retExpr, methodSymbol, state);
}
 
Example #21
Source File: JavaInputAstVisitor.java    From javaide with GNU General Public License v3.0 5 votes vote down vote up
@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;
}
 
Example #22
Source File: ExpressionToTypeInfo.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
@Override
public TreePath visitReturn(ReturnTree node, Boolean isTargetContext) {
    ExpressionTree tree = node.getExpression();
    TreePath tp = new TreePath(getCurrentPath(), tree);
    if (isTargetContext) {
        throw new Result(tp);
    } else {
        return null;
    }
}
 
Example #23
Source File: JavaInputAstVisitor.java    From google-java-format with Apache License 2.0 5 votes vote down vote up
@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;
}
 
Example #24
Source File: TreeDiffer.java    From compile-testing with Apache License 2.0 5 votes vote down vote up
@Override
public Void visitReturn(ReturnTree expected, Tree actual) {
  Optional<ReturnTree> other = checkTypeAndCast(expected, actual);
  if (!other.isPresent()) {
    addTypeMismatch(expected, actual);
    return null;
  }

  scan(expected.getExpression(), other.get().getExpression());
  return null;
}
 
Example #25
Source File: IntroduceMethodFix.java    From netbeans with Apache License 2.0 5 votes vote down vote up
/**
 * 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;
    }
}
 
Example #26
Source File: XPFlagCleaner.java    From piranha with Apache License 2.0 5 votes vote down vote up
@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;
}
 
Example #27
Source File: XPFlagCleaner.java    From piranha with Apache License 2.0 5 votes vote down vote up
/** 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;
}
 
Example #28
Source File: TreeDuplicator.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@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;
}
 
Example #29
Source File: DoNotReturnNullOptionals.java    From teku with Apache License 2.0 5 votes vote down vote up
@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;
}
 
Example #30
Source File: CopyFinder.java    From netbeans with Apache License 2.0 5 votes vote down vote up
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);
}