Search in sources :

Example 6 with ResolvedTypeDeclaration

use of com.github.javaparser.resolution.declarations.ResolvedTypeDeclaration in project javaparser by javaparser.

the class CompilationUnitContextResolutionTest method solveTypeImported.

@Test
public void solveTypeImported() throws ParseException, IOException {
    CompilationUnit cu = parseSample("CompilationUnitWithImports");
    Context context = new CompilationUnitContext(cu, typeSolver);
    SymbolReference<ResolvedTypeDeclaration> ref = context.solveType("Assert", new JarTypeSolver(adaptPath("src/test/resources/junit-4.8.1.jar")));
    assertEquals(true, ref.isSolved());
    assertEquals("org.junit.Assert", ref.getCorrespondingDeclaration().getQualifiedName());
}
Also used : CompilationUnit(com.github.javaparser.ast.CompilationUnit) Context(com.github.javaparser.symbolsolver.core.resolution.Context) CompilationUnitContext(com.github.javaparser.symbolsolver.javaparsermodel.contexts.CompilationUnitContext) CompilationUnitContext(com.github.javaparser.symbolsolver.javaparsermodel.contexts.CompilationUnitContext) JarTypeSolver(com.github.javaparser.symbolsolver.resolution.typesolvers.JarTypeSolver) ResolvedTypeDeclaration(com.github.javaparser.resolution.declarations.ResolvedTypeDeclaration) AbstractResolutionTest(com.github.javaparser.symbolsolver.resolution.AbstractResolutionTest) Test(org.junit.Test)

Example 7 with ResolvedTypeDeclaration

use of com.github.javaparser.resolution.declarations.ResolvedTypeDeclaration in project javaparser by javaparser.

the class JavaParserFacadeResolutionTest method typeDeclarationSuperClassImplicitlyIncludeObject.

@Test
public void typeDeclarationSuperClassImplicitlyIncludeObject() {
    CompilationUnit cu = parseSample("Generics");
    ClassOrInterfaceDeclaration clazz = Navigator.demandClass(cu, "Generics");
    ResolvedTypeDeclaration typeDeclaration = JavaParserFacade.get(new ReflectionTypeSolver()).getTypeDeclaration(clazz);
    ResolvedReferenceType superclass = typeDeclaration.asClass().getSuperClass();
    assertEquals(Object.class.getCanonicalName(), superclass.getQualifiedName());
}
Also used : CompilationUnit(com.github.javaparser.ast.CompilationUnit) ClassOrInterfaceDeclaration(com.github.javaparser.ast.body.ClassOrInterfaceDeclaration) ResolvedReferenceType(com.github.javaparser.resolution.types.ResolvedReferenceType) ResolvedTypeDeclaration(com.github.javaparser.resolution.declarations.ResolvedTypeDeclaration) ReflectionTypeSolver(com.github.javaparser.symbolsolver.resolution.typesolvers.ReflectionTypeSolver) Test(org.junit.Test)

Example 8 with ResolvedTypeDeclaration

use of com.github.javaparser.resolution.declarations.ResolvedTypeDeclaration 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 9 with ResolvedTypeDeclaration

use of com.github.javaparser.resolution.declarations.ResolvedTypeDeclaration in project javaparser by javaparser.

the class AbstractJavaParserContext method findTypeDeclarations.

protected Collection<ResolvedReferenceTypeDeclaration> findTypeDeclarations(Optional<Expression> optScope, TypeSolver typeSolver) {
    if (optScope.isPresent()) {
        Expression scope = optScope.get();
        // consider static methods
        if (scope instanceof NameExpr) {
            NameExpr scopeAsName = (NameExpr) scope;
            SymbolReference<ResolvedTypeDeclaration> symbolReference = this.solveType(scopeAsName.getName().getId(), typeSolver);
            if (symbolReference.isSolved() && symbolReference.getCorrespondingDeclaration().isType()) {
                return singletonList(symbolReference.getCorrespondingDeclaration().asReferenceType());
            }
        }
        ResolvedType typeOfScope;
        try {
            typeOfScope = JavaParserFacade.get(typeSolver).getType(scope);
        } catch (Exception e) {
            throw new RuntimeException("Issue calculating the type of the scope of " + this, e);
        }
        if (typeOfScope.isWildcard()) {
            if (typeOfScope.asWildcard().isExtends() || typeOfScope.asWildcard().isSuper()) {
                return singletonList(typeOfScope.asWildcard().getBoundedType().asReferenceType().getTypeDeclaration());
            } else {
                return singletonList(new ReflectionClassDeclaration(Object.class, typeSolver).asReferenceType());
            }
        } else if (typeOfScope.isArray()) {
            // method call on array are Object methods
            return singletonList(new ReflectionClassDeclaration(Object.class, typeSolver).asReferenceType());
        } else if (typeOfScope.isTypeVariable()) {
            Collection<ResolvedReferenceTypeDeclaration> result = new ArrayList<>();
            for (ResolvedTypeParameterDeclaration.Bound bound : typeOfScope.asTypeParameter().getBounds()) {
                result.add(bound.getType().asReferenceType().getTypeDeclaration());
            }
            return result;
        } else if (typeOfScope.isConstraint()) {
            return singletonList(typeOfScope.asConstraintType().getBound().asReferenceType().getTypeDeclaration());
        }
        return singletonList(typeOfScope.asReferenceType().getTypeDeclaration());
    }
    ResolvedType typeOfScope = JavaParserFacade.get(typeSolver).getTypeOfThisIn(wrappedNode);
    return singletonList(typeOfScope.asReferenceType().getTypeDeclaration());
}
Also used : ResolvedReferenceTypeDeclaration(com.github.javaparser.resolution.declarations.ResolvedReferenceTypeDeclaration) NameExpr(com.github.javaparser.ast.expr.NameExpr) ReflectionClassDeclaration(com.github.javaparser.symbolsolver.reflectionmodel.ReflectionClassDeclaration) ResolvedTypeParameterDeclaration(com.github.javaparser.resolution.declarations.ResolvedTypeParameterDeclaration) ResolvedTypeDeclaration(com.github.javaparser.resolution.declarations.ResolvedTypeDeclaration) Expression(com.github.javaparser.ast.expr.Expression) ResolvedType(com.github.javaparser.resolution.types.ResolvedType)

Example 10 with ResolvedTypeDeclaration

use of com.github.javaparser.resolution.declarations.ResolvedTypeDeclaration in project javaparser by javaparser.

the class AnonymousClassDeclarationContext method solveType.

@Override
public SymbolReference<ResolvedTypeDeclaration> solveType(String name, TypeSolver typeSolver) {
    List<com.github.javaparser.ast.body.TypeDeclaration> typeDeclarations = myDeclaration.findMembersOfKind(com.github.javaparser.ast.body.TypeDeclaration.class);
    Optional<SymbolReference<ResolvedTypeDeclaration>> exactMatch = typeDeclarations.stream().filter(internalType -> internalType.getName().getId().equals(name)).findFirst().map(internalType -> SymbolReference.solved(JavaParserFacade.get(typeSolver).getTypeDeclaration(internalType)));
    if (exactMatch.isPresent()) {
        return exactMatch.get();
    }
    Optional<SymbolReference<ResolvedTypeDeclaration>> recursiveMatch = typeDeclarations.stream().filter(internalType -> name.startsWith(String.format("%s.", internalType.getName()))).findFirst().map(internalType -> JavaParserFactory.getContext(internalType, typeSolver).solveType(name.substring(internalType.getName().getId().length() + 1), typeSolver));
    if (recursiveMatch.isPresent()) {
        return recursiveMatch.get();
    }
    Optional<SymbolReference<ResolvedTypeDeclaration>> typeArgumentsMatch = wrappedNode.getTypeArguments().map(nodes -> ((NodeWithTypeArguments<?>) nodes).getTypeArguments().orElse(new NodeList<>())).orElse(new NodeList<>()).stream().filter(type -> type.toString().equals(name)).findFirst().map(matchingType -> SymbolReference.solved(new JavaParserTypeParameter(new TypeParameter(matchingType.toString()), typeSolver)));
    if (typeArgumentsMatch.isPresent()) {
        return typeArgumentsMatch.get();
    }
    // Look into extended classes and implemented interfaces
    for (ResolvedReferenceType ancestor : myDeclaration.getAncestors()) {
        // look at names of extended classes and implemented interfaces (this may not be important because they are checked in CompilationUnitContext)
        if (ancestor.getTypeDeclaration().getName().equals(name)) {
            return SymbolReference.solved(ancestor.getTypeDeclaration());
        }
        // look into internal types of extended classes and implemented interfaces
        try {
            for (ResolvedTypeDeclaration internalTypeDeclaration : ancestor.getTypeDeclaration().internalTypes()) {
                if (internalTypeDeclaration.getName().equals(name)) {
                    return SymbolReference.solved(internalTypeDeclaration);
                }
            }
        } catch (UnsupportedOperationException e) {
        // just continue using the next ancestor
        }
    }
    return getParent().solveType(name, typeSolver);
}
Also used : JavaParserFactory(com.github.javaparser.symbolsolver.javaparsermodel.JavaParserFactory) NodeList(com.github.javaparser.ast.NodeList) JavaParserFacade(com.github.javaparser.symbolsolver.javaparsermodel.JavaParserFacade) ResolvedMethodDeclaration(com.github.javaparser.resolution.declarations.ResolvedMethodDeclaration) TypeParameter(com.github.javaparser.ast.type.TypeParameter) TypeSolver(com.github.javaparser.symbolsolver.model.resolution.TypeSolver) ResolvedTypeDeclaration(com.github.javaparser.resolution.declarations.ResolvedTypeDeclaration) ReflectionClassDeclaration(com.github.javaparser.symbolsolver.reflectionmodel.ReflectionClassDeclaration) NodeWithTypeArguments(com.github.javaparser.ast.nodeTypes.NodeWithTypeArguments) ResolvedValueDeclaration(com.github.javaparser.resolution.declarations.ResolvedValueDeclaration) ResolvedReferenceType(com.github.javaparser.resolution.types.ResolvedReferenceType) Collectors(java.util.stream.Collectors) JavaParserAnonymousClassDeclaration(com.github.javaparser.symbolsolver.javaparsermodel.declarations.JavaParserAnonymousClassDeclaration) List(java.util.List) ResolvedType(com.github.javaparser.resolution.types.ResolvedType) MethodResolutionLogic(com.github.javaparser.symbolsolver.resolution.MethodResolutionLogic) SymbolReference(com.github.javaparser.symbolsolver.model.resolution.SymbolReference) ObjectCreationExpr(com.github.javaparser.ast.expr.ObjectCreationExpr) JavaParserTypeParameter(com.github.javaparser.symbolsolver.javaparsermodel.declarations.JavaParserTypeParameter) Optional(java.util.Optional) Preconditions(com.google.common.base.Preconditions) TypeParameter(com.github.javaparser.ast.type.TypeParameter) JavaParserTypeParameter(com.github.javaparser.symbolsolver.javaparsermodel.declarations.JavaParserTypeParameter) ResolvedReferenceType(com.github.javaparser.resolution.types.ResolvedReferenceType) SymbolReference(com.github.javaparser.symbolsolver.model.resolution.SymbolReference) JavaParserTypeParameter(com.github.javaparser.symbolsolver.javaparsermodel.declarations.JavaParserTypeParameter) ResolvedTypeDeclaration(com.github.javaparser.resolution.declarations.ResolvedTypeDeclaration) ResolvedTypeDeclaration(com.github.javaparser.resolution.declarations.ResolvedTypeDeclaration)

Aggregations

ResolvedTypeDeclaration (com.github.javaparser.resolution.declarations.ResolvedTypeDeclaration)23 CompilationUnit (com.github.javaparser.ast.CompilationUnit)19 ClassOrInterfaceDeclaration (com.github.javaparser.ast.body.ClassOrInterfaceDeclaration)17 Context (com.github.javaparser.symbolsolver.core.resolution.Context)17 Test (org.junit.Test)17 AbstractResolutionTest (com.github.javaparser.symbolsolver.resolution.AbstractResolutionTest)16 CompilationUnitContext (com.github.javaparser.symbolsolver.javaparsermodel.contexts.CompilationUnitContext)14 ClassOrInterfaceDeclarationContext (com.github.javaparser.symbolsolver.javaparsermodel.contexts.ClassOrInterfaceDeclarationContext)11 MemoryTypeSolver (com.github.javaparser.symbolsolver.resolution.typesolvers.MemoryTypeSolver)11 ResolvedReferenceTypeDeclaration (com.github.javaparser.resolution.declarations.ResolvedReferenceTypeDeclaration)5 ReflectionTypeSolver (com.github.javaparser.symbolsolver.resolution.typesolvers.ReflectionTypeSolver)5 ResolvedType (com.github.javaparser.resolution.types.ResolvedType)4 TypeSolver (com.github.javaparser.symbolsolver.model.resolution.TypeSolver)4 SymbolSolver (com.github.javaparser.symbolsolver.resolution.SymbolSolver)4 ResolvedMethodDeclaration (com.github.javaparser.resolution.declarations.ResolvedMethodDeclaration)3 JavaParserFacade (com.github.javaparser.symbolsolver.javaparsermodel.JavaParserFacade)3 SymbolReference (com.github.javaparser.symbolsolver.model.resolution.SymbolReference)3 ReflectionClassDeclaration (com.github.javaparser.symbolsolver.reflectionmodel.ReflectionClassDeclaration)3 List (java.util.List)3 ImportDeclaration (com.github.javaparser.ast.ImportDeclaration)2