PHP-Parser icon indicating copy to clipboard operation
PHP-Parser copied to clipboard

[PrettyPrinter] Failing test Pretty Printer should not duplicate comment

Open samsonasik opened this issue 4 years ago • 1 comments

Given the following code:

    if ( true ) :
        // TEST 1
      elseif ( true ) :
        // TEST 2
        // TEST 3
        // TEST 4
      endif;

It currently print back:

    if (true) {
        // TEST 1
    } elseif (true) {
        // TEST 2
        // TEST 3
        // TEST 4
+       // TEST 2
+       // TEST 3
+       // TEST 4
    }

which duplicate on elseif part.

samsonasik avatar Jul 20 '21 01:07 samsonasik

The issue seems because of using : with endif syntax, when changed to { }, it is working as expected.

samsonasik avatar Jul 20 '21 01:07 samsonasik

To clarify, this works fine with the normal pretty printer, but the comment gets duplicated if formatting preservation is enabled. The dump looks like this:

array(
    0: Stmt_Function[3:1 - 10:1](
        attrGroups: array(
        )
        byRef: false
        name: Identifier[3:10 - 3:27](
            name: noDuplicateComment
        )
        params: array(
        )
        returnType: null
        stmts: array(
            0: Stmt_If[5:5 - 9:10](
                cond: Expr_ConstFetch[5:9 - 5:12](
                    name: Name[5:9 - 5:12](
                        parts: array(
                            0: true
                        )
                    )
                )
                stmts: array(
                    0: Stmt_Nop[6:0 - 6:17](
                        comments: array(
                            0: // TEST 1
                        )
                    )
                )
                elseifs: array(
                    0: Stmt_ElseIf[7:5 - 7:18](
                        cond: Expr_ConstFetch[7:13 - 7:16](
                            name: Name[7:13 - 7:16](
                                parts: array(
                                    0: true
                                )
                            )
                        )
                        stmts: array(
                            0: Stmt_Nop[8:0 - 8:17](
                                comments: array(
                                    0: // TEST 2
                                )
                            )
                        )
                        comments: array(
                            0: // TEST 1
                        )
                    )
                )
                else: null
            )
        )
    )
)

Presumably, the issue is that the Nop with the comments is located outside the Endif node.

nikic avatar Sep 11 '22 14:09 nikic

Fixed by https://github.com/nikic/PHP-Parser/commit/9b46dffb12c6c83d33b993ae81b9a2895293dee8.

nikic avatar Sep 11 '22 14:09 nikic