javaparser icon indicating copy to clipboard operation
javaparser copied to clipboard

Disappearing comments with LexicalPreservingPrinter

Open andrecsilva opened this issue 2 years ago • 2 comments

Moving statements may make their associated comments disappear from LexicalPreservingPrinter output. An example:

    String code =
        """
    class A{
	    void f(){
		    // first comment
		    int a = 1;
		    // second comment
		    int b = 2;
		    // third comment
		    int c = 3;
	    }
    }
    """;
    CompilationUnit cu = StaticJavaParser.parse(code);
    LexicalPreservingPrinter.setup(cu);

    System.out.println(cu);
    System.out.println("----------------------------------");
    System.out.println(LexicalPreservingPrinter.print(cu));
    var block = cu.findAll(BlockStmt.class).get(0);
    var lastStmt = block.getStatements().removeLast();
    block.addStatement(lastStmt);

    System.out.println("AFTER-----------------------------");
    System.out.println(cu);
    System.out.println("----------------------------------");
    System.out.println(LexicalPreservingPrinter.print(cu));

Output:

    class A {

        void f() {
            // first comment
            int a = 1;
            // second comment
            int b = 2;
            // third comment
            int c = 3;
        }
    }

    ----------------------------------
    class A{
     void f(){
      // first comment
      int a = 1;
      // second comment
      int b = 2;
      // third comment
      int c = 3;
     }
    }

    AFTER-----------------------------
    class A {

        void f() {
            // first comment
            int a = 1;
            // second comment
            int b = 2;
            // third comment
            int c = 3;
        }
    }

    ----------------------------------
    class A{
     void f(){
      // first comment
      int a = 1;
      // second comment
      int b = 2;
      int c = 3;

     }
    }

Notice the last comment is present with the default printer, but won't be printed with the LexicalPreservingPrinter. There is also an extra empty line at the end of the block.

andrecsilva avatar Apr 18 '24 12:04 andrecsilva

It's a complicated case and I'm surprised that you're the first person to spot this issue. Unfortunately I'm not going to be able to solve it immediately. No matter how much I think about it, I can't see how to display the comment with the LexicalPreservingPrinter.

jlerbsc avatar Apr 19 '24 16:04 jlerbsc