com.sun.source.tree.LambdaExpressionTree Java Examples

The following examples show how to use com.sun.source.tree.LambdaExpressionTree. 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: GroovyWriter.java    From vertx-codetrans with Apache License 2.0 6 votes vote down vote up
@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("}");
}
 
Example #2
Source File: ScalaCodeWriter.java    From vertx-codetrans with Apache License 2.0 6 votes vote down vote up
@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("}");
}
 
Example #3
Source File: FindSubtypesVisitor.java    From netbeans with Apache License 2.0 6 votes vote down vote up
@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);
}
 
Example #4
Source File: ConvertToLambdaConverter.java    From netbeans with Apache License 2.0 6 votes vote down vote up
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);
    }
 
Example #5
Source File: StreamNullabilityPropagator.java    From NullAway with MIT License 6 votes vote down vote up
@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);
  }
}
 
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: 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 #8
Source File: KotlinCodeWriter.java    From vertx-codetrans with Apache License 2.0 6 votes vote down vote up
@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("}");
}
 
Example #9
Source File: Lambda.java    From netbeans with Apache License 2.0 6 votes vote down vote up
@Hint(displayName = "#DN_ConvertVarLambdaParameters", description = "#DESC_ConvertVarLambdaParameters", category = "suggestions", hintKind = Hint.Kind.ACTION, minSourceVersion = "11")
@TriggerTreeKind(Kind.LAMBDA_EXPRESSION)
public static ErrorDescription implicitVarParameterTypes(HintContext ctx) {
    // hint will be enable only for JDK-11 or above.
    if (ctx.getInfo().getSourceVersion().compareTo(SourceVersion.RELEASE_9) < 2) {
        return null;
    }
    // Check invalid lambda parameter declaration
    if (ctx.getInfo().getTreeUtilities().hasError(ctx.getPath().getLeaf())) {
        return null;
    }
    // Check var parameter types
    LambdaExpressionTree let = (LambdaExpressionTree) ctx.getPath().getLeaf();
    if (let.getParameters() == null || let.getParameters().isEmpty()) {
        return null;
    }
    VariableTree var = let.getParameters().get(0);
    if (ctx.getInfo().getTreeUtilities().isVarType(new TreePath(ctx.getPath(), var))) {
        return null;
    }

    return ErrorDescriptionFactory.forName(ctx, ctx.getPath(), NbBundle.getMessage(Lambda.class, "ERR_ConvertVarLambdaParameters"), new AddVarLambdaParameterTypes(ctx.getInfo(), ctx.getPath()).toEditorFix());
}
 
Example #10
Source File: NullAway.java    From NullAway with MIT License 6 votes vote down vote up
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;
  }
}
 
Example #11
Source File: Lambda.java    From netbeans with Apache License 2.0 6 votes vote down vote up
@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));
}
 
Example #12
Source File: EnclosingEnvironmentNullness.java    From NullAway with MIT License 5 votes vote down vote up
/** Is t an anonymous inner class or a lambda? */
private boolean isValidTreeType(Tree t) {
  if (t instanceof LambdaExpressionTree) {
    return true;
  }
  if (t instanceof ClassTree) {
    NestingKind nestingKind = ASTHelpers.getSymbol((ClassTree) t).getNestingKind();
    return nestingKind.equals(NestingKind.ANONYMOUS) || nestingKind.equals(NestingKind.LOCAL);
  }
  return false;
}
 
Example #13
Source File: DataFlow.java    From NullAway with MIT License 5 votes vote down vote up
/**
 * Get the dataflow result at exit for a given method (or lambda, or initializer block)
 *
 * @param path path to method (or lambda, or initializer block)
 * @param context Javac context
 * @param transfer transfer functions
 * @param <A> values in abstraction
 * @param <S> store type
 * @param <T> transfer function type
 * @return dataflow result at exit of method
 */
public <A extends AbstractValue<A>, S extends Store<S>, T extends TransferFunction<A, S>>
    S finalResult(TreePath path, Context context, T transfer) {
  final Tree leaf = path.getLeaf();
  Preconditions.checkArgument(
      leaf instanceof MethodTree
          || leaf instanceof LambdaExpressionTree
          || leaf instanceof BlockTree
          || leaf instanceof VariableTree,
      "Leaf of methodPath must be of type MethodTree, LambdaExpressionTree, BlockTree, or VariableTree, but was %s",
      leaf.getClass().getName());

  return dataflow(path, context, transfer).getAnalysis().getRegularExitStore();
}
 
Example #14
Source File: StreamNullabilityPropagator.java    From NullAway with MIT License 5 votes vote down vote up
@Override
public void onDataflowVisitLambdaResultExpression(
    ExpressionTree tree, NullnessStore thenStore, NullnessStore elseStore) {
  if (expressionBodyToFilterLambda.containsKey(tree)) {
    LambdaExpressionTree filterTree = expressionBodyToFilterLambda.get(tree);
    if (canBooleanExpressionEvalToTrue(tree)) {
      filterToNSMap.put(filterTree, thenStore);
    }
  }
}
 
Example #15
Source File: BaseNoOpHandler.java    From NullAway with MIT License 5 votes vote down vote up
@Override
public void onMatchLambdaExpression(
    NullAway analysis,
    LambdaExpressionTree tree,
    VisitorState state,
    Symbol.MethodSymbol methodSymbol) {
  // NoOp
}
 
Example #16
Source File: Analyzer.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
@Override @DefinedBy(Api.COMPILER_TREE)
public JCTree visitLambdaExpression(LambdaExpressionTree node, Void _unused) {
    JCLambda oldLambda = (JCLambda)node;
    JCLambda newLambda = (JCLambda)super.visitLambdaExpression(node, _unused);
    if (oldLambda.paramKind == ParameterKind.IMPLICIT) {
        //reset implicit lambda parameters (whose type might have been set during attr)
        newLambda.paramKind = ParameterKind.IMPLICIT;
        newLambda.params.forEach(p -> p.vartype = null);
    }
    return newLambda;
}
 
Example #17
Source File: JavacParserTest.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
@Test
void testVoidLambdaParameter() throws IOException {
    String code = "package t; class Test { " +
            "Runnable r = (void v) -> { };" +
            "}";
    DiagnosticCollector<JavaFileObject> coll =
            new DiagnosticCollector<>();
    JavacTaskImpl ct = (JavacTaskImpl) tool.getTask(null, fm, coll, null,
            null, Arrays.asList(new MyFileObject(code)));

    CompilationUnitTree cut = ct.parse().iterator().next();
    ClassTree clazz = (ClassTree) cut.getTypeDecls().get(0);
    VariableTree field = (VariableTree) clazz.getMembers().get(0);

    assertEquals("actual kind: " + field.getInitializer().getKind(),
                 field.getInitializer().getKind(),
                 Kind.LAMBDA_EXPRESSION);

    LambdaExpressionTree lambda = (LambdaExpressionTree) field.getInitializer();

    assertEquals("actual parameters: " + lambda.getParameters().size(),
                 lambda.getParameters().size(),
                 1);

    Tree paramType = lambda.getParameters().get(0).getType();

    assertEquals("actual parameter type: " + paramType.getKind(),
                 paramType.getKind(),
                 Kind.PRIMITIVE_TYPE);

    TypeKind primitiveTypeKind = ((PrimitiveTypeTree) paramType).getPrimitiveTypeKind();

    assertEquals("actual parameter type: " + primitiveTypeKind,
                 primitiveTypeKind,
                 TypeKind.VOID);
}
 
Example #18
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 #19
Source File: LambdaTest.java    From netbeans with Apache License 2.0 5 votes vote down vote up
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);
}
 
Example #20
Source File: LambdaTest.java    From netbeans with Apache License 2.0 5 votes vote down vote up
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);
}
 
Example #21
Source File: LambdaScanner.java    From annotation-tools with MIT License 5 votes vote down vote up
@Override
public Void visitLambdaExpression(LambdaExpressionTree node, Void p) {
  if (!done) {
    index++;
  }
  if (tree == node) {
    done = true;
  }
  return super.visitLambdaExpression(node, p);
}
 
Example #22
Source File: LambdaTest.java    From netbeans with Apache License 2.0 5 votes vote down vote up
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);
}
 
Example #23
Source File: LambdaTest.java    From netbeans with Apache License 2.0 5 votes vote down vote up
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);
}
 
Example #24
Source File: LambdaTest.java    From netbeans with Apache License 2.0 5 votes vote down vote up
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);
}
 
Example #25
Source File: LambdaTest.java    From netbeans with Apache License 2.0 5 votes vote down vote up
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);
}
 
Example #26
Source File: ScanLocalVars.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@Override
public Void visitLambdaExpression(LambdaExpressionTree node, Void p) {
    nesting++;
    super.visitLambdaExpression(node, p);
    nesting--;
    return null;
}
 
Example #27
Source File: Lambda.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@Override
protected void performRewrite(JavaFix.TransformationContext ctx) throws Exception {
    if (ctx.getPath().getLeaf().getKind() == Kind.LAMBDA_EXPRESSION) {
        LambdaExpressionTree let = (LambdaExpressionTree) ctx.getPath().getLeaf();
        TreeMaker make = ctx.getWorkingCopy().getTreeMaker();
        let.getParameters().forEach((var) -> {
            ctx.getWorkingCopy().rewrite(var.getType(), make.Type("var")); // NOI18N
        });
    }
}
 
Example #28
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 {
    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);
        }
    }
}
 
Example #29
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 #30
Source File: Lambda.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@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();

    if (ctx.getInfo().getTreeUtilities().hasError(let)) {
        return null;
    }

    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());
}