diff --git a/src/printer.mjs b/src/printer.mjs index a9f06c170..5600ba053 100644 --- a/src/printer.mjs +++ b/src/printer.mjs @@ -2419,7 +2419,16 @@ function printNode(path, options, print) { if (node.expr) { const printedExpr = print("expr"); - parts.push(" ", node.expr.comments ? indent(printedExpr) : printedExpr); + // Only comments printed around the expression (leading or + // trailing) need the extra indent. Dangling comments are printed + // by the expression itself at its own indent; wrapping those in + // indent() as well shifts them and the closing line one level + // too deep, e.g. an array holding only a comment. + const shouldIndent = + node.expr.comments && + (hasLeadingComment(node.expr) || hasTrailingComment(node.expr)); + + parts.push(" ", shouldIndent ? indent(printedExpr) : printedExpr); } if (hasDanglingComments(node)) { diff --git a/tests/array/__snapshots__/jsfmt.spec.mjs.snap b/tests/array/__snapshots__/jsfmt.spec.mjs.snap index dc64656e1..a7487ae31 100644 --- a/tests/array/__snapshots__/jsfmt.spec.mjs.snap +++ b/tests/array/__snapshots__/jsfmt.spec.mjs.snap @@ -1727,6 +1727,99 @@ $var = array(...new ArrayIterator(array("a", "b", "c"))); ================================================================================ `; +exports[`empty-comment.php 1`] = ` +====================================options===================================== +parsers: ["php"] +printWidth: 80 + | printWidth +=====================================input====================================== + 'bar', +]; + +function foo() +{ + return [ + // TODO: ... + ]; +} + +=====================================output===================================== + "bar", +]; + +function foo() +{ + return [ + // TODO: ... + ]; +} + +================================================================================ +`; + +exports[`empty-comment.php 2`] = ` +====================================options===================================== +parsers: ["php"] +phpVersion: "5.3" +printWidth: 80 + | printWidth +=====================================input====================================== + 'bar', +]; + +function foo() +{ + return [ + // TODO: ... + ]; +} + +=====================================output===================================== + "bar", +); + +function foo() +{ + return array( + // TODO: ... + ); +} + +================================================================================ +`; + exports[`single.php 1`] = ` ====================================options===================================== parsers: ["php"] diff --git a/tests/array/empty-comment.php b/tests/array/empty-comment.php new file mode 100644 index 000000000..f0c0e8e61 --- /dev/null +++ b/tests/array/empty-comment.php @@ -0,0 +1,17 @@ + 'bar', +]; + +function foo() +{ + return [ + // TODO: ... + ]; +}