Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Method 'forEach' cannot be resolved in certain context #4330

Open
huajiaoyu opened this issue Mar 4, 2024 · 6 comments
Open

Method 'forEach' cannot be resolved in certain context #4330

huajiaoyu opened this issue Mar 4, 2024 · 6 comments

Comments

@huajiaoyu
Copy link

huajiaoyu commented Mar 4, 2024

I was trying to resolve argument types for all method call expressions(MethodCallExpr.class) in a method(Main Function in TestForEach.java in this case). I guess the exception happend with the generic type in List<String>.

Stack trace

Method Call: forEach
[java.util.function.Consumer<? super java.lang.String>]
Method Call: println
java.lang.RuntimeException: Method 'forEach' cannot be resolved in context ls.forEach(s -> {
    System.out.println(s);
}) (line: 12) MethodCallExprContext{wrapped=ls.forEach(s -> {
    System.out.println(s);
})}. Parameter types: [ReferenceType{java.util.function.Consumer, typeParametersMap=TypeParametersMap{nameToValue={java.util.function.Consumer.T=WildcardUsage{type=SUPER, boundedType=ReferenceType{java.lang.String, typeParametersMap=TypeParametersMap{nameToValue={}}}}}}}]
	at com.github.javaparser.symbolsolver.javaparsermodel.JavaParserFacade.solveMethodAsUsage(JavaParserFacade.java:659)
	at com.github.javaparser.symbolsolver.javaparsermodel.contexts.LambdaExprContext.solveSymbolAsValue(LambdaExprContext.java:74)
	at com.github.javaparser.symbolsolver.javaparsermodel.declarations.JavaParserParameterDeclaration.getType(JavaParserParameterDeclaration.java:64)
	at com.github.javaparser.resolution.model.Value.from(Value.java:45)
	at com.github.javaparser.resolution.Context.solveSymbolAsValueInParentContext(Context.java:199)
	at com.github.javaparser.symbolsolver.javaparsermodel.contexts.MethodCallExprContext.solveSymbolAsValue(MethodCallExprContext.java:145)
	at com.github.javaparser.symbolsolver.resolution.SymbolSolver.solveSymbolAsValue(SymbolSolver.java:76)
	at com.github.javaparser.symbolsolver.resolution.SymbolSolver.solveSymbolAsValue(SymbolSolver.java:82)
	at com.github.javaparser.symbolsolver.javaparsermodel.TypeExtractor.visit(TypeExtractor.java:335)
	at com.github.javaparser.symbolsolver.javaparsermodel.TypeExtractor.visit(TypeExtractor.java:65)
	at com.github.javaparser.ast.expr.NameExpr.accept(NameExpr.java:81)
	at com.github.javaparser.symbolsolver.javaparsermodel.JavaParserFacade.getTypeConcrete(JavaParserFacade.java:501)
	at com.github.javaparser.symbolsolver.javaparsermodel.JavaParserFacade.getType(JavaParserFacade.java:349)
	at com.github.javaparser.symbolsolver.javaparsermodel.JavaParserFacade.getType(JavaParserFacade.java:331)
	at com.github.javaparser.symbolsolver.JavaSymbolSolver.calculateType(JavaSymbolSolver.java:294)
	at com.github.javaparser.ast.expr.Expression.calculateResolvedType(Expression.java:575)
	at cn.hjy.drawiogen.DrawioGenApplicationTests.lambda$getTypeStrListFromCallExpr$2(DrawioGenApplicationTests.java:83)
	at java.base/java.util.stream.ReferencePipeline$3$1.accept(ReferencePipeline.java:197)
	at java.base/java.util.ArrayList$ArrayListSpliterator.forEachRemaining(ArrayList.java:1625)
	at java.base/java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:509)
	at java.base/java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:499)
	at java.base/java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:575)
	at java.base/java.util.stream.AbstractPipeline.evaluateToArrayNode(AbstractPipeline.java:260)
	at java.base/java.util.stream.ReferencePipeline.toArray(ReferencePipeline.java:616)
	at java.base/java.util.stream.ReferencePipeline.toArray(ReferencePipeline.java:622)
	at java.base/java.util.stream.ReferencePipeline.toList(ReferencePipeline.java:627)
	at cn.hjy.drawiogen.DrawioGenApplicationTests.getTypeStrListFromCallExpr(DrawioGenApplicationTests.java:89)
	at cn.hjy.drawiogen.DrawioGenApplicationTests.lambda$main$0(DrawioGenApplicationTests.java:66)
	at java.base/java.util.ArrayList.forEach(ArrayList.java:1511)
	at cn.hjy.drawiogen.DrawioGenApplicationTests.lambda$main$1(DrawioGenApplicationTests.java:64)
	at java.base/java.util.ArrayList.forEach(ArrayList.java:1511)
	at cn.hjy.drawiogen.DrawioGenApplicationTests.main(DrawioGenApplicationTests.java:61)

Main function

    public static void main(String[] args) {
        try {
            CombinedTypeSolver combinedTypeSolver = new CombinedTypeSolver(new ReflectionTypeSolver());
            TypeSolver javaParserTypeSolver = new JavaParserTypeSolver(new File("D:\\my-workspace\\demo\\src\\main\\java"));
            combinedTypeSolver.add(javaParserTypeSolver);


            ParserConfiguration config = StaticJavaParser.getParserConfiguration();
            config.setSymbolResolver(new JavaSymbolSolver(combinedTypeSolver));
            StaticJavaParser.setConfiguration(config);


            FileInputStream file = new FileInputStream("D:\\my-workspace\\demo\\src\\main\\java\\cn\\hjy\\TestForEach.java");

            CompilationUnit cu = StaticJavaParser.parse(file);

            cu.findAll(MethodDeclaration.class).forEach(method -> {
                System.out.println("Method Name: " + method.getNameAsString());

                method.findAll(MethodCallExpr.class).forEach(callExpr -> {
                    System.out.println("Method Call: " + callExpr.getNameAsString());
                    System.out.println(getTypeStrListFromCallExpr(callExpr));
                });

                System.out.println("----------------------------------");
            });

        } catch (FileNotFoundException e) {
            System.out.println("File not found");
        }
    }

    private static List<String> getTypeStrListFromCallExpr(MethodCallExpr callExpr) {
        NodeList<Expression> arguments = callExpr.getArguments();
        return arguments.stream().map(arg -> {
                    try {
                        return arg.calculateResolvedType().describe();
                    } catch (Exception e) {
                        e.printStackTrace();
                        throw new IllegalStateException("Failed to resolve arg: "+arg.toString());
                    }
                }
        ).toList();
    }

TestForEach.java

public class TestForEach {

    public static void main(String[] args) {
        List<String> ls = new ArrayList<>();
        ls.add("sss");
        ls.forEach(s->{
            System.out.println(s);
        });
    }

}
@jlerbsc
Copy link
Collaborator

jlerbsc commented Mar 4, 2024

There seems to be an inference problem when solving the foreach() method. I haven't been able to pinpoint the exact cause of this problem.

@huajiaoyu
Copy link
Author

There seems to be an inference problem when solving the foreach() method. I haven't been able to pinpoint the exact cause of this problem.

Thank you for your reply. Can you explain more about "an inference problem"? What did you mean by that?

@jlerbsc
Copy link
Collaborator

jlerbsc commented Mar 5, 2024

The Iterable.foreach method is a generic method which takes a parameter which JP tries to determine in order to resolve the foreach method.

@jlerbsc
Copy link
Collaborator

jlerbsc commented Mar 7, 2024

I don't have a solution to this problem at the moment.

@jlerbsc
Copy link
Collaborator

jlerbsc commented Mar 10, 2024

To complete this issue i think this section describes the problem https://docs.oracle.com/javase/tutorial/java/generics/genTypeInference.html#target_types

@hardik6955
Copy link

I need solution this code.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging a pull request may close this issue.

3 participants