spoon icon indicating copy to clipboard operation
spoon copied to clipboard

[Bug] setPreserveLineNumbers(true) incompatible with single line comments

Open xzel23 opened this issue 4 years ago • 1 comments

Describe the bug when preserveLineNumbers is set, a closing brace is sometimes placed on the same line as a single line comment leading to sytactically incorrect code.

To Reproduce

Input:

                class A {
                    private static String getArgText(int min, int max) {
                        assert min<=max;

                        String argText = switch (min) {
                            case 0 -> "";
                            case 1 -> (min == max) ? " arg" : " arg1";
                            case 2 -> " arg1 arg2";
                            case 3 -> " arg1 arg2 arg3";
                            default -> //noinspection StringConcatenationMissingWhitespace
                                    " arg1 ... arg" + min;
                        };
                        
                        return argText;
                    }
                }

Processing with Spoon:

        Launcher launcher = new Launcher();
        launcher.addInputResource(new VirtualFile(code));
        launcher.getEnvironment().setComplianceLevel(16);
        launcher.getEnvironment().setNoClasspath(true);
        launcher.getEnvironment().setAutoImports(true);
        launcher.getEnvironment().setPreserveLineNumbers(true);

        CtModel model = launcher.buildModel();

        System.out.println(model.getRootPackage().getType("A").toString());

Output:

class A {
    private static String getArgText(int min, int max) {
        assert min <= max;

        String argText = switch (min) {
            case 0 ->                 "";
            case 1 ->                 min == max ? " arg" : " arg1";
            case 2 ->                 " arg1 arg2";
            case 3 ->                 " arg1 arg2 arg3";
            default ->
                " arg1 ... arg" + min;                 // noinspection StringConcatenationMissingWhitespace};


        return argText;
    }
}

Note that the closing brace after the default clause is place after the single line comment. This does not happen, if I call launcher.getEnvironment().setPreserveLineNumbers(false); instead.

Operating system, JDK and Spoon version used

  • OS: MacOS 12.0.1
  • JDK: JDK 17 (GraalVM CE)
  • Spoon version: current Git (10.0.0 + changes since release)

xzel23 avatar Nov 15 '21 07:11 xzel23

I might find the time to look into this later this week - currently busy with my day job.

xzel23 avatar Nov 15 '21 07:11 xzel23