Search in sources :

Example 51 with LambdaExpr

use of com.github.javaparser.ast.expr.LambdaExpr in project javaparser by javaparser.

the class Issue2482Test method commentBeforeLambda.

@Test
public void commentBeforeLambda() {
    LambdaExpr le = StaticJavaParser.parseExpression("// a comment before parent" + System.lineSeparator() + "()->{return 1;}");
    assertTrue(le.getComment().isPresent());
    assertTrue(le.getOrphanComments().isEmpty());
    assertEquals(0, le.getAllContainedComments().size());
}
Also used : LambdaExpr(com.github.javaparser.ast.expr.LambdaExpr) Test(org.junit.jupiter.api.Test)

Example 52 with LambdaExpr

use of com.github.javaparser.ast.expr.LambdaExpr in project javaparser by javaparser.

the class LambdaExprContextResolutionTest method solveParameterOfLambdaInCast.

@Test
void solveParameterOfLambdaInCast() {
    CompilationUnit cu = parseSample("Lambda");
    com.github.javaparser.ast.body.ClassOrInterfaceDeclaration clazz = Navigator.demandClass(cu, "Agenda");
    MethodDeclaration method = Navigator.demandMethod(clazz, "testCast");
    VariableDeclarator varDecl = Navigator.demandVariableDeclaration(method, "a").get();
    LambdaExpr lambdaExpr = ((CastExpr) varDecl.getInitializer().get()).getExpression().asLambdaExpr();
    Path src = adaptPath("src/test/resources");
    CombinedTypeSolver combinedTypeSolver = new CombinedTypeSolver();
    combinedTypeSolver.add(new ReflectionTypeSolver());
    combinedTypeSolver.add(new JavaParserTypeSolver(src, new LeanParserConfiguration()));
    Context context = new LambdaExprContext(lambdaExpr, combinedTypeSolver);
    Optional<Value> ref = context.solveSymbolAsValue("p");
    assertTrue(ref.isPresent());
    assertEquals("java.lang.String", ref.get().getType().describe());
}
Also used : CompilationUnit(com.github.javaparser.ast.CompilationUnit) Path(java.nio.file.Path) Context(com.github.javaparser.symbolsolver.core.resolution.Context) LambdaExprContext(com.github.javaparser.symbolsolver.javaparsermodel.contexts.LambdaExprContext) LeanParserConfiguration(com.github.javaparser.symbolsolver.utils.LeanParserConfiguration) MethodDeclaration(com.github.javaparser.ast.body.MethodDeclaration) LambdaExpr(com.github.javaparser.ast.expr.LambdaExpr) CombinedTypeSolver(com.github.javaparser.symbolsolver.resolution.typesolvers.CombinedTypeSolver) VariableDeclarator(com.github.javaparser.ast.body.VariableDeclarator) LambdaExprContext(com.github.javaparser.symbolsolver.javaparsermodel.contexts.LambdaExprContext) Value(com.github.javaparser.symbolsolver.model.resolution.Value) JavaParserTypeSolver(com.github.javaparser.symbolsolver.resolution.typesolvers.JavaParserTypeSolver) ReflectionTypeSolver(com.github.javaparser.symbolsolver.resolution.typesolvers.ReflectionTypeSolver) AbstractResolutionTest(com.github.javaparser.symbolsolver.resolution.AbstractResolutionTest) Test(org.junit.jupiter.api.Test)

Example 53 with LambdaExpr

use of com.github.javaparser.ast.expr.LambdaExpr in project javaparser by javaparser.

the class LambdaExprContextResolutionTest method solveParameterOfLambdaInMethodCallExpr.

@Test
void solveParameterOfLambdaInMethodCallExpr() {
    CompilationUnit cu = parseSample("Lambda");
    com.github.javaparser.ast.body.ClassOrInterfaceDeclaration clazz = Navigator.demandClass(cu, "Agenda");
    MethodDeclaration method = Navigator.demandMethod(clazz, "lambdaMap");
    ReturnStmt returnStmt = Navigator.demandReturnStmt(method);
    MethodCallExpr methodCallExpr = (MethodCallExpr) returnStmt.getExpression().get();
    LambdaExpr lambdaExpr = (LambdaExpr) methodCallExpr.getArguments().get(0);
    Context context = new LambdaExprContext(lambdaExpr, typeSolver);
    Optional<Value> ref = context.solveSymbolAsValue("p");
    assertTrue(ref.isPresent());
    assertEquals("? super java.lang.String", ref.get().getType().describe());
}
Also used : CompilationUnit(com.github.javaparser.ast.CompilationUnit) Context(com.github.javaparser.symbolsolver.core.resolution.Context) LambdaExprContext(com.github.javaparser.symbolsolver.javaparsermodel.contexts.LambdaExprContext) MethodDeclaration(com.github.javaparser.ast.body.MethodDeclaration) LambdaExpr(com.github.javaparser.ast.expr.LambdaExpr) LambdaExprContext(com.github.javaparser.symbolsolver.javaparsermodel.contexts.LambdaExprContext) Value(com.github.javaparser.symbolsolver.model.resolution.Value) ReturnStmt(com.github.javaparser.ast.stmt.ReturnStmt) MethodCallExpr(com.github.javaparser.ast.expr.MethodCallExpr) AbstractResolutionTest(com.github.javaparser.symbolsolver.resolution.AbstractResolutionTest) Test(org.junit.jupiter.api.Test)

Example 54 with LambdaExpr

use of com.github.javaparser.ast.expr.LambdaExpr in project javaparser by javaparser.

the class ExpressionCompatibleWithType method reduce.

@Override
public ReductionResult reduce(BoundSet currentBoundSet) {
    if (isProperType(T)) {
        if (isCompatibleInALooseInvocationContext(typeSolver, expression, T)) {
            return ReductionResult.trueResult();
        } else {
            return ReductionResult.falseResult();
        }
    }
    if (expression.isStandaloneExpression()) {
        ResolvedType s = JavaParserFacade.get(typeSolver).getType(expression, false);
        return ReductionResult.empty().withConstraint(new TypeCompatibleWithType(typeSolver, s, T));
    }
    if (expression.isPolyExpression()) {
        if (expression instanceof EnclosedExpr) {
            EnclosedExpr enclosedExpr = (EnclosedExpr) expression;
            return ReductionResult.oneConstraint(new ExpressionCompatibleWithType(typeSolver, enclosedExpr.getInner(), T));
        }
        if (expression instanceof ObjectCreationExpr) {
            BoundSet B3 = new TypeInference(typeSolver).invocationTypeInferenceBoundsSetB3();
            return ReductionResult.bounds(B3);
        }
        if (expression instanceof MethodCallExpr) {
            throw new UnsupportedOperationException();
        }
        if (expression instanceof ConditionalExpr) {
            ConditionalExpr conditionalExpr = (ConditionalExpr) expression;
            return ReductionResult.withConstraints(new ExpressionCompatibleWithType(typeSolver, conditionalExpr.getThenExpr(), T), new ExpressionCompatibleWithType(typeSolver, conditionalExpr.getElseExpr(), T));
        }
        if (expression instanceof LambdaExpr) {
            LambdaExpr lambdaExpr = (LambdaExpr) expression;
            if (!FunctionalInterfaceLogic.isFunctionalInterfaceType(T)) {
                return ReductionResult.falseResult();
            }
            // - Otherwise, let T' be the ground target type derived from T, as specified in §15.27.3. If §18.5.3
            // is used to derive a functional interface type which is parameterized, then the test that
            // F<A'1, ..., A'm> is a subtype of F<A1, ..., Am> is not performed (instead, it is asserted with a
            // constraint formula below). Let the target function type for the lambda expression be the
            // function type of T'. Then:
            Pair<ResolvedType, Boolean> result = TypeHelper.groundTargetTypeOfLambda(lambdaExpr, T, typeSolver);
            ResolvedType TFirst = result.a;
            MethodType targetFunctionType = TypeHelper.getFunctionType(TFirst);
            targetFunctionType = replaceTypeVariablesWithInferenceVariables(targetFunctionType);
            if (result.b) {
                throw new UnsupportedOperationException();
            }
            if (targetFunctionType.getFormalArgumentTypes().size() != lambdaExpr.getParameters().size()) {
                return ReductionResult.falseResult();
            }
            if (targetFunctionType.getReturnType().isVoid()) {
                throw new UnsupportedOperationException();
            }
            if (!targetFunctionType.getReturnType().isVoid() && lambdaExpr.getBody() instanceof BlockStmt && !isValueCompatibleBlock(lambdaExpr.getBody())) {
                return ReductionResult.falseResult();
            }
            // - Otherwise, the constraint reduces to all of the following constraint formulas:
            List<ConstraintFormula> constraints = new LinkedList<>();
            // - If the lambda parameters have explicitly declared types F1, ..., Fn and the function type
            // has parameter types G1, ..., Gn, then i) for all i (1 ≤ i ≤ n), ‹Fi = Gi›, and ii) ‹T' <: T›.
            boolean hasExplicitlyDeclaredTypes = lambdaExpr.getParameters().stream().anyMatch(p -> !(p.getType() instanceof UnknownType));
            if (hasExplicitlyDeclaredTypes) {
                throw new UnsupportedOperationException();
            }
            if (!targetFunctionType.getReturnType().isVoid()) {
                ResolvedType R = targetFunctionType.getReturnType();
                if (TypeHelper.isProperType(R)) {
                    if (lambdaExpr.getBody() instanceof BlockStmt) {
                        List<Expression> resultExpressions = ExpressionHelper.getResultExpressions((BlockStmt) lambdaExpr.getBody());
                        for (Expression e : resultExpressions) {
                            if (!ExpressionHelper.isCompatibleInAssignmentContext(e, R, typeSolver)) {
                                return ReductionResult.falseResult();
                            }
                        }
                    } else {
                        Expression e = ((ExpressionStmt) lambdaExpr.getBody()).getExpression();
                        if (!ExpressionHelper.isCompatibleInAssignmentContext(e, R, typeSolver)) {
                            return ReductionResult.falseResult();
                        }
                    }
                } else {
                    if (lambdaExpr.getBody() instanceof BlockStmt) {
                        getAllReturnExpressions((BlockStmt) lambdaExpr.getBody()).forEach(e -> constraints.add(new ExpressionCompatibleWithType(typeSolver, e, R)));
                    } else {
                        // FEDERICO: Added - Start
                        for (int i = 0; i < lambdaExpr.getParameters().size(); i++) {
                            ResolvedType paramType = targetFunctionType.getFormalArgumentTypes().get(i);
                            TypeInferenceCache.addRecord(typeSolver, lambdaExpr, lambdaExpr.getParameter(i).getNameAsString(), paramType);
                        }
                        // FEDERICO: Added - End
                        Expression e = ((ExpressionStmt) lambdaExpr.getBody()).getExpression();
                        constraints.add(new ExpressionCompatibleWithType(typeSolver, e, R));
                    }
                }
            }
            return ReductionResult.withConstraints(constraints);
        }
        if (expression instanceof MethodReferenceExpr) {
            throw new UnsupportedOperationException();
        }
        throw new RuntimeException("This should not happen");
    }
    throw new RuntimeException("This should not happen");
}
Also used : ObjectCreationExpr(com.github.javaparser.ast.expr.ObjectCreationExpr) MethodReferenceExpr(com.github.javaparser.ast.expr.MethodReferenceExpr) ConstraintFormula(com.github.javaparser.symbolsolver.resolution.typeinference.ConstraintFormula) ExpressionStmt(com.github.javaparser.ast.stmt.ExpressionStmt) TypeInference(com.github.javaparser.symbolsolver.resolution.typeinference.TypeInference) ResolvedType(com.github.javaparser.resolution.types.ResolvedType) BoundSet(com.github.javaparser.symbolsolver.resolution.typeinference.BoundSet) MethodType(com.github.javaparser.symbolsolver.resolution.typeinference.MethodType) LambdaExpr(com.github.javaparser.ast.expr.LambdaExpr) BlockStmt(com.github.javaparser.ast.stmt.BlockStmt) ConditionalExpr(com.github.javaparser.ast.expr.ConditionalExpr) LinkedList(java.util.LinkedList) UnknownType(com.github.javaparser.ast.type.UnknownType) Expression(com.github.javaparser.ast.expr.Expression) EnclosedExpr(com.github.javaparser.ast.expr.EnclosedExpr) MethodCallExpr(com.github.javaparser.ast.expr.MethodCallExpr)

Example 55 with LambdaExpr

use of com.github.javaparser.ast.expr.LambdaExpr in project javaparser by javaparser.

the class Issue3272Test method test1.

@Test
void test1() {
    // Source code
    String sourceCode = "import java.util.function.Consumer;" + "class A {" + "   Consumer<Integer> consumer;" + "   {" + "       consumer = item -> {};" + "   }" + "}";
    // Setup symbol solver
    ParserConfiguration configuration = new ParserConfiguration().setSymbolResolver(new JavaSymbolSolver(new CombinedTypeSolver(new ReflectionTypeSolver())));
    // Setup parser
    JavaParser parser = new JavaParser(configuration);
    CompilationUnit cu = parser.parse(sourceCode).getResult().get();
    // Test
    LambdaExpr expr = Navigator.demandNodeOfGivenClass(cu, LambdaExpr.class);
    ResolvedType type = expr.calculateResolvedType();
    assertEquals("java.util.function.Consumer<java.lang.Integer>", type.describe());
}
Also used : CompilationUnit(com.github.javaparser.ast.CompilationUnit) JavaParser(com.github.javaparser.JavaParser) LambdaExpr(com.github.javaparser.ast.expr.LambdaExpr) ReflectionTypeSolver(com.github.javaparser.symbolsolver.resolution.typesolvers.ReflectionTypeSolver) CombinedTypeSolver(com.github.javaparser.symbolsolver.resolution.typesolvers.CombinedTypeSolver) ResolvedType(com.github.javaparser.resolution.types.ResolvedType) ParserConfiguration(com.github.javaparser.ParserConfiguration) Test(org.junit.jupiter.api.Test)

Aggregations

LambdaExpr (com.github.javaparser.ast.expr.LambdaExpr)70 Parameter (com.github.javaparser.ast.body.Parameter)37 NameExpr (com.github.javaparser.ast.expr.NameExpr)30 MethodCallExpr (com.github.javaparser.ast.expr.MethodCallExpr)29 Expression (com.github.javaparser.ast.expr.Expression)27 BlockStmt (com.github.javaparser.ast.stmt.BlockStmt)25 UnknownType (com.github.javaparser.ast.type.UnknownType)24 StringLiteralExpr (com.github.javaparser.ast.expr.StringLiteralExpr)19 ExpressionStmt (com.github.javaparser.ast.stmt.ExpressionStmt)16 ReturnStmt (com.github.javaparser.ast.stmt.ReturnStmt)15 ClassOrInterfaceType (com.github.javaparser.ast.type.ClassOrInterfaceType)12 CompilationUnit (com.github.javaparser.ast.CompilationUnit)10 MethodDeclaration (com.github.javaparser.ast.body.MethodDeclaration)10 NullLiteralExpr (com.github.javaparser.ast.expr.NullLiteralExpr)10 Test (org.junit.jupiter.api.Test)10 VariableDeclarator (com.github.javaparser.ast.body.VariableDeclarator)9 LongLiteralExpr (com.github.javaparser.ast.expr.LongLiteralExpr)9 CastExpr (com.github.javaparser.ast.expr.CastExpr)8 ArrayList (java.util.ArrayList)8 TypedExpression (org.drools.modelcompiler.builder.generator.TypedExpression)8