@Override public Tree visitLambdaExpression(LambdaExpressionTree node, Element elementToFind) { if (workingCopy.getTreeUtilities().isSynthetic(getCurrentPath())) { return super.visitLambdaExpression(node, elementToFind); } Trees trees = workingCopy.getTrees(); Types types = workingCopy.getTypes(); TypeMirror type1 = trees.getTypeMirror(getCurrentPath()); if(type1 == null) { return super.visitLambdaExpression(node, elementToFind); } type1 = types.erasure(type1); TypeMirror type2 = elementToFind.asType(); type2 = types.erasure(type2); if (types.isSameType(type1, type2) || (recursive && isSubtype(type1, type2))) { addUsage(getCurrentPath()); } return super.visitLambdaExpression(node, elementToFind); }
public void performRewriteToLambda() { LambdaExpressionTree lambdaTree = getLambdaTreeFromAnonymous(newClassTree, copy); if (lambdaTree == null) { return; } if (preconditionChecker.foundShadowedVariable()) { TreePath pathToLambda = new TreePath(pathToNewClassTree, lambdaTree); renameShadowedVariables(pathToLambda); } ExpressionTree convertedTree = lambdaTree; if (preconditionChecker.needsCastToExpectedType()) { convertedTree = getTreeWithCastPrepended(lambdaTree, newClassTree.getIdentifier()); } copy.rewrite(newClassTree, convertedTree); }
@Hint(displayName="#DN_expression2Return", description="#DESC_expression2Return", category="suggestions", hintKind=Hint.Kind.ACTION, minSourceVersion = "8") @Messages({ "DN_expression2Return=Convert Lambda Body to Use a Block", "DESC_expression2Return=Converts lambda bodies to use blocks rather than expressions", "ERR_expression2Return=", "FIX_expression2Return=Use block as the lambda's body" }) @TriggerPattern("($args$) -> $lambdaExpression") public static ErrorDescription expression2Return(HintContext ctx) { if (((LambdaExpressionTree) ctx.getPath().getLeaf()).getBodyKind() != BodyKind.EXPRESSION) { return null; } TypeMirror lambdaExpressionType = ctx.getInfo().getTrees().getTypeMirror(ctx.getVariables().get("$lambdaExpression")); String target = lambdaExpressionType == null || lambdaExpressionType.getKind() != TypeKind.VOID ? "($args$) -> { return $lambdaExpression; }" : "($args$) -> { $lambdaExpression; }"; return ErrorDescriptionFactory.forTree(ctx, ctx.getPath(), Bundle.ERR_expression2Return(), JavaFixUtilities.rewriteFix(ctx, Bundle.FIX_expression2Return(), ctx.getPath(), target)); }
@Hint(displayName="#DN_addExplicitLambdaParameters", description="#DESC_addExplicitLambdaParameters", category="suggestions", hintKind=Hint.Kind.ACTION) @Messages({ "DN_addExplicitLambdaParameters=Convert Lambda to Use Explicit Parameter Types", "DESC_addExplicitLambdaParameters=Converts lambdas to use explicit parameter types", "ERR_addExplicitLambdaParameters=", "FIX_addExplicitLambdaParameters=Use explicit parameter types" }) @TriggerTreeKind(Kind.LAMBDA_EXPRESSION) public static ErrorDescription explicitParameterTypes(HintContext ctx) { LambdaExpressionTree let = (LambdaExpressionTree) ctx.getPath().getLeaf(); boolean hasSyntheticParameterName = false; for (VariableTree var : let.getParameters()) { hasSyntheticParameterName |= var.getType() == null || ctx.getInfo().getTreeUtilities().isSynthetic(TreePath.getPath(ctx.getPath(), var.getType())); } if (!hasSyntheticParameterName) { return null; } return ErrorDescriptionFactory.forName(ctx, ctx.getPath(), Bundle.ERR_addExplicitLambdaParameters(), new AddExplicitLambdaParameterTypes(ctx.getInfo(), ctx.getPath()).toEditorFix()); }
/** * find the enclosing method, lambda expression or initializer block for the leaf of some tree * path * * @param path the tree path * @return the closest enclosing method / lambda */ @Nullable public static TreePath findEnclosingMethodOrLambdaOrInitializer(TreePath path) { while (path != null) { if (path.getLeaf() instanceof MethodTree || path.getLeaf() instanceof LambdaExpressionTree) { return path; } TreePath parent = path.getParentPath(); if (parent != null && parent.getLeaf() instanceof ClassTree) { if (path.getLeaf() instanceof BlockTree) { // found initializer block return path; } if (path.getLeaf() instanceof VariableTree && ((VariableTree) path.getLeaf()).getInitializer() != null) { // found field with an inline initializer return path; } } path = parent; } return null; }
@Override public void onMatchLambdaExpression( NullAway analysis, LambdaExpressionTree tree, VisitorState state, Symbol.MethodSymbol methodSymbol) { if (filterMethodOrLambdaSet.contains(tree) && tree.getBodyKind().equals(LambdaExpressionTree.BodyKind.EXPRESSION)) { expressionBodyToFilterLambda.put((ExpressionTree) tree.getBody(), tree); // Single expression lambda, onMatchReturn will not be triggered, force the dataflow analysis // here AccessPathNullnessAnalysis nullnessAnalysis = analysis.getNullnessAnalysis(state); nullnessAnalysis.forceRunOnMethod(state.getPath(), state.context); } if (mapToFilterMap.containsKey(tree)) { bodyToMethodOrLambda.put(tree.getBody(), tree); } }
@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<Nullness> thenStore, NullnessStore<Nullness> 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 Description matchLambdaExpression(LambdaExpressionTree tree, VisitorState state) { Symbol.MethodSymbol methodSymbol = NullabilityUtil.getFunctionalInterfaceMethod(tree, state.getTypes()); handler.onMatchLambdaExpression(this, tree, state, methodSymbol); Description description = checkParamOverriding(tree, tree.getParameters(), methodSymbol, true); if (description != Description.NO_MATCH) { return description; } if (tree.getBodyKind() == LambdaExpressionTree.BodyKind.EXPRESSION && methodSymbol.getReturnType().getKind() != TypeKind.VOID) { ExpressionTree resExpr = (ExpressionTree) tree.getBody(); return checkReturnExpression(tree, resExpr, methodSymbol, state); } return Description.NO_MATCH; }
private boolean relevantInitializerMethodOrBlock( TreePath enclosingBlockPath, VisitorState state) { Tree methodLambdaOrBlock = enclosingBlockPath.getLeaf(); if (methodLambdaOrBlock instanceof LambdaExpressionTree) { return false; } else if (methodLambdaOrBlock instanceof MethodTree) { MethodTree methodTree = (MethodTree) methodLambdaOrBlock; if (isConstructor(methodTree) && !constructorInvokesAnother(methodTree, state)) return true; if (ASTHelpers.getSymbol(methodTree).isStatic()) { Set<MethodTree> staticInitializerMethods = class2Entities.get(enclosingClassSymbol(enclosingBlockPath)).staticInitializerMethods(); return staticInitializerMethods.size() == 1 && staticInitializerMethods.contains(methodTree); } else { Set<MethodTree> instanceInitializerMethods = class2Entities .get(enclosingClassSymbol(enclosingBlockPath)) .instanceInitializerMethods(); return instanceInitializerMethods.size() == 1 && instanceInitializerMethods.contains(methodTree); } } else { // initializer or field declaration return true; } }
private static <T> TreePath findEnclosingMethodOrLambdaOrInitializer(TreePath path) { while (path != null) { if (path.getLeaf() instanceof MethodTree) { return path; } TreePath parent = path.getParentPath(); if (parent != null) { if (parent.getLeaf() instanceof ClassTree) { if (path.getLeaf() instanceof BlockTree) { // this is a class or instance initializer block return path; } if (path.getLeaf() instanceof VariableTree && ((VariableTree) path.getLeaf()).getInitializer() != null) { // this is a field with an inline initializer return path; } } if (parent.getLeaf() instanceof LambdaExpressionTree) { return parent; } } path = parent; } return null; }
/** * Renders a ruby block with curly brace syntax. */ private void renderBlock(LambdaExpressionTree.BodyKind bodyKind, List<TypeInfo> parameterTypes, List<String> parameterNames, CodeModel body, CodeWriter writer) { append("{"); if (parameterNames.size() > 0) { append(" |"); for (int i = 0; i < parameterNames.size(); i++) { if (i > 0) { append(","); } append(parameterNames.get(i)); } append("|"); } append("\n"); indent(); body.render(this); if (bodyKind == LambdaExpressionTree.BodyKind.EXPRESSION) { append("\n"); } unindent(); append("}"); }
@Override public void renderLambda(LambdaExpressionTree.BodyKind bodyKind, List<TypeInfo> parameterTypes, List<String> parameterNames, CodeModel body){ append("("); IntStream.range(0, parameterNames.size()).forEach(i -> { if(i > 0) append(", "); append(parameterNames.get(i)); append(": "); append(parameterTypes.get(i).translateName("scala")); }); append(") => {\n"); indent(); body.render(this); if (bodyKind == LambdaExpressionTree.BodyKind.EXPRESSION) append("\n"); unindent(); append("}"); }
@Override public void renderLambda(LambdaExpressionTree.BodyKind bodyKind, List<TypeInfo> parameterTypes, List<String> parameterNames, CodeModel body) { append("{"); for (int i = 0; i < parameterNames.size(); i++) { if (i == 0) { append(" "); } else { append(", "); } append(parameterNames.get(i)); } append(" ->\n"); indent(); body.render(this); if (bodyKind == LambdaExpressionTree.BodyKind.EXPRESSION) { append("\n"); } unindent(); append("}"); }
@Override public void renderLambda(LambdaExpressionTree.BodyKind bodyKind, List<TypeInfo> parameterTypes, List<String> parameterNames, CodeModel body) { append("function ("); for (int i = 0; i < parameterNames.size(); i++) { if (i > 0) { append(", "); } append(parameterNames.get(i)); } append(") {\n"); indent(); body.render(this); if (bodyKind == LambdaExpressionTree.BodyKind.EXPRESSION) { append(";\n"); } unindent(); append("}"); }
@Override public void renderLambda(LambdaExpressionTree.BodyKind bodyKind, List<TypeInfo> parameterTypes, List<String> parameterNames, CodeModel body) { append("{"); if (!parameterNames.isEmpty()) { for (int i = 0; i < parameterNames.size(); i++) { if (i == 0) { append(" "); } else { append(", "); } append(parameterNames.get(i)); } append(" ->\n"); } else { append("\n"); } indent(); body.render(this); if (bodyKind == LambdaExpressionTree.BodyKind.EXPRESSION) { append("\n"); } unindent(); append("}"); }
@Override public Tree visitLambdaExpression(LambdaExpressionTree tree, Void p) { LambdaExpressionTree n = make.LambdaExpression(tree.getParameters(), tree.getBody()); model.setType(n, model.getType(tree)); comments.copyComments(tree, n); model.setPos(n, model.getPos(tree)); return n; }
@Override public Boolean visitLambdaExpression(LambdaExpressionTree node, TreePath p) { if (p == null) return super.visitLambdaExpression(node, p); LambdaExpressionTree t = (LambdaExpressionTree) p.getLeaf(); if (!checkLists(node.getParameters(), t.getParameters(), p)) { return false; } return scan(node.getBody(), t.getBody(), p); }
public void testAddFirstLambdaParam() 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 = () -> {};\n" + " }\n" + "}\n" ); String golden = "package hierbas.del.litoral;\n\n" + "public class Test {\n" + " public static void taragui() {\n" + " ChangeListener l = (e) -> {};\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) { workingCopy.rewrite(node, make.addLambdaParameter(node, make.Variable(make.Modifiers(EnumSet.noneOf(Modifier.class)), "e", null, null))); 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); }
public void testAddSecondLambdaParam() 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) -> {};\n" + " }\n" + "}\n" ); String golden = "package hierbas.del.litoral;\n\n" + "public class Test {\n" + " public static void taragui() {\n" + " ChangeListener l = (e, f) -> {};\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) { workingCopy.rewrite(node, make.addLambdaParameter(node, make.Variable(make.Modifiers(EnumSet.noneOf(Modifier.class)), "f", null, null))); 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); }
public void testAddSecondLambdaParamNoParenthesis() 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 -> {};\n" + " }\n" + "}\n" ); String golden = "package hierbas.del.litoral;\n\n" + "public class Test {\n" + " public static void taragui() {\n" + " ChangeListener l = (e, f) -> {};\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) { workingCopy.rewrite(node, make.addLambdaParameter(node, make.Variable(make.Modifiers(EnumSet.noneOf(Modifier.class)), "f", null, null))); 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); }
public void testPrependSecondLambdaParam() 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) -> {};\n" + " }\n" + "}\n" ); String golden = "package hierbas.del.litoral;\n\n" + "public class Test {\n" + " public static void taragui() {\n" + " ChangeListener l = (f, e) -> {};\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) { workingCopy.rewrite(node, make.insertLambdaParameter(node, 0, make.Variable(make.Modifiers(EnumSet.noneOf(Modifier.class)), "f", null, null))); 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); }
public void testRemoveFirstLambdaParam() 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, f) -> {};\n" + " }\n" + "}\n" ); String golden = "package hierbas.del.litoral;\n\n" + "public class Test {\n" + " public static void taragui() {\n" + " ChangeListener l = (f) -> {};\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) { workingCopy.rewrite(node, make.removeLambdaParameter(node, 0)); 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); }
public void testRemoveSecondLambdaParam() 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, f) -> {};\n" + " }\n" + "}\n" ); String golden = "package hierbas.del.litoral;\n\n" + "public class Test {\n" + " public static void taragui() {\n" + " ChangeListener l = (e) -> {};\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) { workingCopy.rewrite(node, make.removeLambdaParameter(node, 1)); 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); }
public void testOnlyLambdaParam() 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) -> {};\n" + " }\n" + "}\n" ); String golden = "package hierbas.del.litoral;\n\n" + "public class Test {\n" + " public static void taragui() {\n" + " ChangeListener l = () -> {};\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) { workingCopy.rewrite(node, make.removeLambdaParameter(node, 0)); 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); }
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); }
public void testLambdaExpression2FullBody() 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) -> 1;\n" + " }\n" + "}\n" ); String golden = "package hierbas.del.litoral;\n\n" + "public class Test {\n" + " public static void taragui() {\n" + " ChangeListener l = (e) -> {\n" + " return 1;\n" + " };\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) { workingCopy.rewrite(node, make.setLambdaBody(node, make.Block(Collections.singletonList(make.Return((ExpressionTree) node.getBody())), false))); 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); }
public void testAddSecondLambdaParamWithType() 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) -> {};\n" + " }\n" + "}\n" ); String golden = "package hierbas.del.litoral;\n\n" + "public class Test {\n" + " public static void taragui() {\n" + " ChangeListener l = (e, f) -> {};\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) { VariableTree vt = node.getParameters().get(0); workingCopy.rewrite(node, make.addLambdaParameter(node, make.Variable(vt.getModifiers(), "f", vt.getType(), vt.getInitializer()))); 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 Void visitLambdaExpression(LambdaExpressionTree node, EnumSet<UseTypes> p) { scan(node.getParameters(), EnumSet.of(UseTypes.WRITE)); if (node.getBodyKind() == LambdaExpressionTree.BodyKind.EXPRESSION) { scan(node.getBody(), EnumSet.of(UseTypes.READ)); } else { scan(node.getBody(), p); } return null; }
@Override public Number visitLambdaExpression(LambdaExpressionTree node, Void p) { List<? extends VariableTree> args = resolveMultiParameters(node.getParameters()); LambdaExpressionTree nue = make.LambdaExpression(args, node.getBody()); rewrite(node, nue); return super.visitLambdaExpression(node, p); }
@Override public Tree visitLambdaExpression(LambdaExpressionTree node, Element elementToFind) { Element type = elementToFind.getEnclosingElement(); if (type.getKind() == ElementKind.INTERFACE && workingCopy.getElements().isFunctionalInterface((TypeElement) type) && !workingCopy.getTreeUtilities().isSynthetic(getCurrentPath())) { TypeMirror typeMirror = workingCopy.getTrees().getTypeMirror(getCurrentPath()); if (typeMirror != null && workingCopy.getTypes().isSameType(typeMirror, type.asType())) { addUsage(getCurrentPath()); } } return super.visitLambdaExpression(node, elementToFind); }
@Override public Object visitLambdaExpression(LambdaExpressionTree node, Object p) { depth++; Object o = super.visitLambdaExpression(node, p); depth--; return o; }
@Override public Void visitLambdaExpression(LambdaExpressionTree tree, List<Node> d) { List<Node> below = new ArrayList<Node>(); addCorrespondingType(below); addCorrespondingComments(below); super.visitLambdaExpression(tree, below); d.add(new TreeNode(info, getCurrentPath(), below)); return null; }
private LambdaExpressionTree getLambdaTreeFromAnonymous(NewClassTree newClassTree, WorkingCopy copy) { TreeMaker make = copy.getTreeMaker(); MethodTree methodTree = getMethodFromFunctionalInterface(newClassTree); Tree lambdaBody = getLambdaBody(methodTree, copy); if (lambdaBody == null) { return null; } return make.LambdaExpression(methodTree.getParameters(), lambdaBody); }
@Override public Void visitLambdaExpression(LambdaExpressionTree node, Void p) { nesting++; super.visitLambdaExpression(node, p); nesting--; return null; }
private static List<? extends TypeMirror> computeLambdaRetrun(Set<ElementKind> types, CompilationInfo info, TreePath parent, Tree error, int offset) { LambdaExpressionTree let = (LambdaExpressionTree)parent.getLeaf(); if (let.getBody() != error) { return null; } TreePath parentParent = parent.getParentPath(); TypeMirror m = info.getTrees().getTypeMirror(parentParent); if (org.netbeans.modules.java.hints.errors.Utilities.isValidType(m)) { return Collections.singletonList(m); } return resolveType(types, info, parentParent, let, offset, null, null); }
@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); } }
@Override protected void performRewrite(TransformationContext ctx) throws Exception { LambdaExpressionTree let = (LambdaExpressionTree) ctx.getPath().getLeaf(); for (VariableTree var : let.getParameters()) { TreePath typePath = TreePath.getPath(ctx.getPath(), var.getType()); if (ctx.getWorkingCopy().getTreeUtilities().isSynthetic(typePath)) { Tree imported = ctx.getWorkingCopy().getTreeMaker().Type(ctx.getWorkingCopy().getTrees().getTypeMirror(typePath)); ctx.getWorkingCopy().rewrite(var.getType(), imported); } } }