Search in sources :

Example 16 with ReturnStmt

use of com.github.javaparser.ast.stmt.ReturnStmt in project javaparser by javaparser.

the class MethodsResolutionTest method solveMethodAccessThroughSuper.

@Test
public void solveMethodAccessThroughSuper() {
    CompilationUnit cu = parseSample("AccessThroughSuper");
    com.github.javaparser.ast.body.ClassOrInterfaceDeclaration clazz = Navigator.demandClass(cu, "AccessThroughSuper.SubClass");
    MethodDeclaration method = Navigator.demandMethod(clazz, "methodTest");
    ReturnStmt returnStmt = (ReturnStmt) method.getBody().get().getStatements().get(0);
    Expression expression = returnStmt.getExpression().get();
    ResolvedType ref = JavaParserFacade.get(new ReflectionTypeSolver()).getType(expression);
    assertEquals("java.lang.String", ref.describe());
}
Also used : CompilationUnit(com.github.javaparser.ast.CompilationUnit) Expression(com.github.javaparser.ast.expr.Expression) ResolvedMethodDeclaration(com.github.javaparser.resolution.declarations.ResolvedMethodDeclaration) MethodDeclaration(com.github.javaparser.ast.body.MethodDeclaration) ReflectionTypeSolver(com.github.javaparser.symbolsolver.resolution.typesolvers.ReflectionTypeSolver) ClassOrInterfaceDeclaration(com.github.javaparser.ast.body.ClassOrInterfaceDeclaration) ReturnStmt(com.github.javaparser.ast.stmt.ReturnStmt) ResolvedType(com.github.javaparser.resolution.types.ResolvedType) Test(org.junit.Test)

Example 17 with ReturnStmt

use of com.github.javaparser.ast.stmt.ReturnStmt in project javaparser by javaparser.

the class SymbolResolutionResolutionTest method conditionalExpressionExample.

@Test
public void conditionalExpressionExample() {
    CompilationUnit cu = parseSample("JreConditionalExpression");
    ClassOrInterfaceDeclaration clazz = Navigator.demandClass(cu, "MyClass");
    MethodDeclaration method = Navigator.demandMethod(clazz, "foo1");
    ReturnStmt returnStmt = Navigator.findReturnStmt(method);
    Expression expression = returnStmt.getExpression().get();
    TypeSolver typeSolver = new ReflectionTypeSolver();
    ResolvedType ref = JavaParserFacade.get(typeSolver).getType(expression);
    assertEquals("java.lang.String", ref.describe());
}
Also used : CompilationUnit(com.github.javaparser.ast.CompilationUnit) ClassOrInterfaceDeclaration(com.github.javaparser.ast.body.ClassOrInterfaceDeclaration) Expression(com.github.javaparser.ast.expr.Expression) MethodDeclaration(com.github.javaparser.ast.body.MethodDeclaration) TypeSolver(com.github.javaparser.symbolsolver.model.resolution.TypeSolver) ReflectionTypeSolver(com.github.javaparser.symbolsolver.resolution.typesolvers.ReflectionTypeSolver) ReflectionTypeSolver(com.github.javaparser.symbolsolver.resolution.typesolvers.ReflectionTypeSolver) ReturnStmt(com.github.javaparser.ast.stmt.ReturnStmt) ResolvedType(com.github.javaparser.resolution.types.ResolvedType) AbstractResolutionTest(com.github.javaparser.symbolsolver.resolution.AbstractResolutionTest) Test(org.junit.Test)

Example 18 with ReturnStmt

use of com.github.javaparser.ast.stmt.ReturnStmt in project javaparser by javaparser.

the class FieldDeclaration method createGetter.

/**
 * Create a getter for this field, <b>will only work if this field declares only 1 identifier and if this field is
 * already added to a ClassOrInterfaceDeclaration</b>
 *
 * @return the {@link MethodDeclaration} created
 * @throws IllegalStateException if there is more than 1 variable identifier or if this field isn't attached to a
 *             class or enum
 */
public MethodDeclaration createGetter() {
    if (getVariables().size() != 1)
        throw new IllegalStateException("You can use this only when the field declares only 1 variable name");
    ClassOrInterfaceDeclaration parentClass = getParentNodeOfType(ClassOrInterfaceDeclaration.class);
    EnumDeclaration parentEnum = getParentNodeOfType(EnumDeclaration.class);
    if ((parentClass == null && parentEnum == null) || (parentClass != null && parentClass.isInterface()))
        throw new IllegalStateException("You can use this only when the field is attached to a class or an enum");
    VariableDeclarator variable = getVariables().get(0);
    String fieldName = variable.getId().getName();
    String fieldNameUpper = fieldName.toUpperCase().substring(0, 1) + fieldName.substring(1, fieldName.length());
    final MethodDeclaration getter;
    if (parentClass != null)
        getter = parentClass.addMethod("get" + fieldNameUpper, PUBLIC);
    else
        getter = parentEnum.addMethod("get" + fieldNameUpper, PUBLIC);
    getter.setType(variable.getType());
    BlockStmt blockStmt = new BlockStmt();
    getter.setBody(blockStmt);
    blockStmt.addStatement(new ReturnStmt(name(fieldName)));
    return getter;
}
Also used : BlockStmt(com.github.javaparser.ast.stmt.BlockStmt) ReturnStmt(com.github.javaparser.ast.stmt.ReturnStmt)

Example 19 with ReturnStmt

use of com.github.javaparser.ast.stmt.ReturnStmt in project javaparser by javaparser.

the class TypeExtractor method visit.

@Override
public ResolvedType visit(LambdaExpr node, Boolean solveLambdas) {
    if (requireParentNode(node) instanceof MethodCallExpr) {
        MethodCallExpr callExpr = (MethodCallExpr) requireParentNode(node);
        int pos = JavaParserSymbolDeclaration.getParamPos(node);
        SymbolReference<ResolvedMethodDeclaration> refMethod = facade.solve(callExpr);
        if (!refMethod.isSolved()) {
            throw new com.github.javaparser.resolution.UnsolvedSymbolException(requireParentNode(node).toString(), callExpr.getName().getId());
        }
        logger.finest("getType on lambda expr " + refMethod.getCorrespondingDeclaration().getName());
        if (solveLambdas) {
            // The type parameter referred here should be the java.util.stream.Stream.T
            ResolvedType result = refMethod.getCorrespondingDeclaration().getParam(pos).getType();
            if (callExpr.getScope().isPresent()) {
                Expression scope = callExpr.getScope().get();
                // If it is a static call we should not try to get the type of the scope
                boolean staticCall = false;
                if (scope instanceof NameExpr) {
                    NameExpr nameExpr = (NameExpr) scope;
                    try {
                        SymbolReference<ResolvedTypeDeclaration> type = JavaParserFactory.getContext(nameExpr, typeSolver).solveType(nameExpr.getName().getId(), typeSolver);
                        if (type.isSolved()) {
                            staticCall = true;
                        }
                    } catch (Exception e) {
                    }
                }
                if (!staticCall) {
                    ResolvedType scopeType = facade.getType(scope);
                    if (scopeType.isReferenceType()) {
                        result = scopeType.asReferenceType().useThisTypeParametersOnTheGivenType(result);
                    }
                }
            }
            // We need to replace the type variables
            Context ctx = JavaParserFactory.getContext(node, typeSolver);
            result = solveGenericTypes(result, ctx, typeSolver);
            // We should find out which is the functional method (e.g., apply) and replace the params of the
            // solveLambdas with it, to derive so the values. We should also consider the value returned by the
            // lambdas
            Optional<MethodUsage> functionalMethod = FunctionalInterfaceLogic.getFunctionalMethod(result);
            if (functionalMethod.isPresent()) {
                LambdaExpr lambdaExpr = node;
                InferenceContext lambdaCtx = new InferenceContext(MyObjectProvider.INSTANCE);
                InferenceContext funcInterfaceCtx = new InferenceContext(MyObjectProvider.INSTANCE);
                // At this point parameterType
                // if Function<T=? super Stream.T, ? extends map.R>
                // we should replace Stream.T
                ResolvedType functionalInterfaceType = ReferenceTypeImpl.undeterminedParameters(functionalMethod.get().getDeclaration().declaringType(), typeSolver);
                lambdaCtx.addPair(result, functionalInterfaceType);
                ResolvedType actualType;
                if (lambdaExpr.getBody() instanceof ExpressionStmt) {
                    actualType = facade.getType(((ExpressionStmt) lambdaExpr.getBody()).getExpression());
                } else if (lambdaExpr.getBody() instanceof BlockStmt) {
                    BlockStmt blockStmt = (BlockStmt) lambdaExpr.getBody();
                    // Get all the return statements in the lambda block
                    List<ReturnStmt> returnStmts = blockStmt.findAll(ReturnStmt.class);
                    if (returnStmts.size() > 0) {
                        actualType = returnStmts.stream().map(returnStmt -> returnStmt.getExpression().map(e -> facade.getType(e)).orElse(ResolvedVoidType.INSTANCE)).filter(x -> x != null && !x.isVoid() && !x.isNull()).findFirst().orElse(ResolvedVoidType.INSTANCE);
                    } else {
                        return ResolvedVoidType.INSTANCE;
                    }
                } else {
                    throw new UnsupportedOperationException();
                }
                ResolvedType formalType = functionalMethod.get().returnType();
                // Infer the functional interfaces' return vs actual type
                funcInterfaceCtx.addPair(formalType, actualType);
                // Substitute to obtain a new type
                ResolvedType functionalTypeWithReturn = funcInterfaceCtx.resolve(funcInterfaceCtx.addSingle(functionalInterfaceType));
                // we don't need to bother inferring types
                if (!(formalType instanceof ResolvedVoidType)) {
                    lambdaCtx.addPair(result, functionalTypeWithReturn);
                    result = lambdaCtx.resolve(lambdaCtx.addSingle(result));
                }
            }
            return result;
        } else {
            return refMethod.getCorrespondingDeclaration().getParam(pos).getType();
        }
    } else {
        throw new UnsupportedOperationException("The type of a lambda expr depends on the position and its return value");
    }
}
Also used : ExpressionStmt(com.github.javaparser.ast.stmt.ExpressionStmt) ReturnStmt(com.github.javaparser.ast.stmt.ReturnStmt) Navigator.requireParentNode(com.github.javaparser.symbolsolver.javaparser.Navigator.requireParentNode) Parameter(com.github.javaparser.ast.body.Parameter) MethodUsage(com.github.javaparser.resolution.MethodUsage) Value(com.github.javaparser.symbolsolver.model.resolution.Value) Level(java.util.logging.Level) VariableDeclarator(com.github.javaparser.ast.body.VariableDeclarator) ResolvedReferenceTypeDeclaration(com.github.javaparser.resolution.declarations.ResolvedReferenceTypeDeclaration) ResolvedType(com.github.javaparser.resolution.types.ResolvedType) ImmutableList(com.google.common.collect.ImmutableList) ResolvedArrayType(com.github.javaparser.resolution.types.ResolvedArrayType) Context(com.github.javaparser.symbolsolver.core.resolution.Context) CompilationUnit(com.github.javaparser.ast.CompilationUnit) JavaParserFacade.solveGenericTypes(com.github.javaparser.symbolsolver.javaparsermodel.JavaParserFacade.solveGenericTypes) MyObjectProvider(com.github.javaparser.symbolsolver.reflectionmodel.MyObjectProvider) JavaParserSymbolDeclaration(com.github.javaparser.symbolsolver.javaparsermodel.declarations.JavaParserSymbolDeclaration) UnknownType(com.github.javaparser.ast.type.UnknownType) ResolvedMethodDeclaration(com.github.javaparser.resolution.declarations.ResolvedMethodDeclaration) UnsolvedSymbolException(com.github.javaparser.resolution.UnsolvedSymbolException) InferenceContext(com.github.javaparser.symbolsolver.logic.InferenceContext) TypeSolver(com.github.javaparser.symbolsolver.model.resolution.TypeSolver) ResolvedTypeDeclaration(com.github.javaparser.resolution.declarations.ResolvedTypeDeclaration) com.github.javaparser.symbolsolver.model.typesystem(com.github.javaparser.symbolsolver.model.typesystem) ReflectionClassDeclaration(com.github.javaparser.symbolsolver.reflectionmodel.ReflectionClassDeclaration) Logger(java.util.logging.Logger) ResolvedClassDeclaration(com.github.javaparser.resolution.declarations.ResolvedClassDeclaration) ResolvedVoidType(com.github.javaparser.resolution.types.ResolvedVoidType) FunctionalInterfaceLogic(com.github.javaparser.symbolsolver.logic.FunctionalInterfaceLogic) List(java.util.List) FieldDeclaration(com.github.javaparser.ast.body.FieldDeclaration) SymbolReference(com.github.javaparser.symbolsolver.model.resolution.SymbolReference) ResolvedPrimitiveType(com.github.javaparser.resolution.types.ResolvedPrimitiveType) ReflectionTypeSolver(com.github.javaparser.symbolsolver.resolution.typesolvers.ReflectionTypeSolver) Optional(java.util.Optional) ConsoleHandler(java.util.logging.ConsoleHandler) BlockStmt(com.github.javaparser.ast.stmt.BlockStmt) SymbolSolver(com.github.javaparser.symbolsolver.resolution.SymbolSolver) ClassOrInterfaceDeclaration(com.github.javaparser.ast.body.ClassOrInterfaceDeclaration) com.github.javaparser.ast.expr(com.github.javaparser.ast.expr) ResolvedTypeDeclaration(com.github.javaparser.resolution.declarations.ResolvedTypeDeclaration) ExpressionStmt(com.github.javaparser.ast.stmt.ExpressionStmt) ImmutableList(com.google.common.collect.ImmutableList) List(java.util.List) ResolvedType(com.github.javaparser.resolution.types.ResolvedType) UnsolvedSymbolException(com.github.javaparser.resolution.UnsolvedSymbolException) Context(com.github.javaparser.symbolsolver.core.resolution.Context) InferenceContext(com.github.javaparser.symbolsolver.logic.InferenceContext) InferenceContext(com.github.javaparser.symbolsolver.logic.InferenceContext) BlockStmt(com.github.javaparser.ast.stmt.BlockStmt) UnsolvedSymbolException(com.github.javaparser.resolution.UnsolvedSymbolException) ResolvedMethodDeclaration(com.github.javaparser.resolution.declarations.ResolvedMethodDeclaration) MethodUsage(com.github.javaparser.resolution.MethodUsage) ReturnStmt(com.github.javaparser.ast.stmt.ReturnStmt) ResolvedVoidType(com.github.javaparser.resolution.types.ResolvedVoidType)

Example 20 with ReturnStmt

use of com.github.javaparser.ast.stmt.ReturnStmt in project javaparser by javaparser.

the class ParsingSteps method thenLambdaInConditionalExpressionInMethodInClassIsParentOfContainedParameter.

@Then("ThenExpr in the conditional expression of the statement $statementPosition in method $methodPosition in class $classPosition is LambdaExpr")
public void thenLambdaInConditionalExpressionInMethodInClassIsParentOfContainedParameter(int statementPosition, int methodPosition, int classPosition) {
    ReturnStmt returnStmt = getStatementInMethodInClass(statementPosition, methodPosition, classPosition).asReturnStmt();
    ConditionalExpr conditionalExpr = (ConditionalExpr) returnStmt.getExpression().orElse(null);
    assertThat(conditionalExpr.getElseExpr().getClass().getName(), is(LambdaExpr.class.getName()));
}
Also used : ReturnStmt(com.github.javaparser.ast.stmt.ReturnStmt) Then(org.jbehave.core.annotations.Then)

Aggregations

ReturnStmt (com.github.javaparser.ast.stmt.ReturnStmt)27 CompilationUnit (com.github.javaparser.ast.CompilationUnit)23 MethodDeclaration (com.github.javaparser.ast.body.MethodDeclaration)23 Test (org.junit.Test)23 ReflectionTypeSolver (com.github.javaparser.symbolsolver.resolution.typesolvers.ReflectionTypeSolver)22 ResolvedType (com.github.javaparser.resolution.types.ResolvedType)21 Expression (com.github.javaparser.ast.expr.Expression)15 JavaParserFacade (com.github.javaparser.symbolsolver.javaparsermodel.JavaParserFacade)14 ClassOrInterfaceDeclaration (com.github.javaparser.ast.body.ClassOrInterfaceDeclaration)9 TypeSolver (com.github.javaparser.symbolsolver.model.resolution.TypeSolver)5 MethodCallExpr (com.github.javaparser.ast.expr.MethodCallExpr)3 LambdaExpr (com.github.javaparser.ast.expr.LambdaExpr)2 BlockStmt (com.github.javaparser.ast.stmt.BlockStmt)2 ResolvedMethodDeclaration (com.github.javaparser.resolution.declarations.ResolvedMethodDeclaration)2 Context (com.github.javaparser.symbolsolver.core.resolution.Context)2 Value (com.github.javaparser.symbolsolver.model.resolution.Value)2 AbstractResolutionTest (com.github.javaparser.symbolsolver.resolution.AbstractResolutionTest)2 FieldDeclaration (com.github.javaparser.ast.body.FieldDeclaration)1 Parameter (com.github.javaparser.ast.body.Parameter)1 VariableDeclarator (com.github.javaparser.ast.body.VariableDeclarator)1