Error parsing java file with switch + enum

Hello devs,

I have written a standalone program to detect and automatically resolve false positive sonar issues. (related to this thread.) It’s working fine, but the parser fails to parse some Java files.

Here is an example.

Java enum:

public enum Fruit {
    APPLE, BANANA
}

Java class:

public class Main {
    private String extracted(Fruit fruit) {
        return switch (fruit) {
            case BANANA -> "banana";
            case APPLE -> "apple";
        };
    }

    public static void main(String[] args) {
        File file = new File("/Path/To/This/Main.java");
        InputFile inputFile = new GeneratedFile(file.toPath());
        JavaAstScanner scanner = new JavaAstScanner(null);
        VisitorsBridge visitorsBridge = new VisitorsBridge(new SubscriptionVisitor() {
            @Override
            public List<Tree.Kind> nodesToVisit() {
                return List.of(Tree.Kind.METHOD);
            }
        });
        scanner.setVisitorBridge(visitorsBridge);
        scanner.scan(Collections.singleton(inputFile));
    }
}

This gives the following error.

Unable to parse source file : '/Path/To/This/Main.java'
com.sonar.sslr.api.RecognitionException: Parse error at line 05 column 23: A switch expression should have a default case

I guess the AST scanner cannot identify the switch case labels as enum values in this case. Therefore it expects a default case, which kind of makes sense. But I don’t want the parser to break due to this. Is there a way to tell the parser not to do this check while parsing?

I’m using the following libraries.

org.sonarsource.java:java-frontend:7.34.0.35958
org.sonarsource.api.plugin:sonar-plugin-api:10.7.0.2191

Thanks,
Bhathiya

Hi Bhathiya,

Sorry for the delayed response; your post slipped through the net. Thank you for reporting the issue.

It appears the problem might be with the Eclipse parser, but I couldn’t reproduce it with Sonar Java version 8.9. It’s possible the issue has been resolved in later versions of the eclipse parser. Could you try updating to the latest release of Sonar Java by updating the dependency? If it does not work, I will investigate further.

Hi Erwan,

No worries, and thanks for the response.
I just ran a quick test and you seem to be correct, I can’t reproduce it with 8.9. We will upgrade.

Thank you.

Regards,
Bhathiya

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.