From bb238f5765f6d66e3d130ef4b3b70a433fa6ab01 Mon Sep 17 00:00:00 2001 From: Sosuke Suzuki Date: Thu, 8 Oct 2020 17:08:40 +0900 Subject: [PATCH] Fix placing leading comments for a body of while statement (#9345) * Add leading comments for while * Add tests * Add changelog --- changelog_unreleased/javascript/pr-9345.md | 20 +++++++++++++++++++ src/language-js/comments.js | 5 +++++ .../comments/__snapshots__/jsfmt.spec.js.snap | 14 +++++++++++++ tests/js/comments/while.js | 3 +++ 4 files changed, 42 insertions(+) create mode 100644 changelog_unreleased/javascript/pr-9345.md diff --git a/changelog_unreleased/javascript/pr-9345.md b/changelog_unreleased/javascript/pr-9345.md new file mode 100644 index 000000000..d579dc6a7 --- /dev/null +++ b/changelog_unreleased/javascript/pr-9345.md @@ -0,0 +1,20 @@ +#### Fix placing leading comments for a body of while statement (#9345 by @sosukesuzuki) + + +```js +// Input +while(1) // Comment + foo(); + +// Prettier stable +while ( + 1 // Comment +) + foo(); + +// Prettier master +while (1) + // Comment + foo(); + +``` diff --git a/src/language-js/comments.js b/src/language-js/comments.js index c1430cf9b..8777c4d5c 100644 --- a/src/language-js/comments.js +++ b/src/language-js/comments.js @@ -336,6 +336,11 @@ function handleWhileComments( return true; } + if (enclosingNode.body === followingNode) { + addLeadingComment(followingNode, comment); + return true; + } + return false; } diff --git a/tests/js/comments/__snapshots__/jsfmt.spec.js.snap b/tests/js/comments/__snapshots__/jsfmt.spec.js.snap index 748be7411..46bb3bfb7 100644 --- a/tests/js/comments/__snapshots__/jsfmt.spec.js.snap +++ b/tests/js/comments/__snapshots__/jsfmt.spec.js.snap @@ -5097,6 +5097,9 @@ while(true) {} // comment while(true) /* comment */ ++x; +while(1) // Comment + foo(); + =====================================output===================================== while ( true @@ -5122,6 +5125,10 @@ while (true) {} // comment while (true) /* comment */ ++x +while (1) + // Comment + foo() + ================================================================================ `; @@ -5152,6 +5159,9 @@ while(true) {} // comment while(true) /* comment */ ++x; +while(1) // Comment + foo(); + =====================================output===================================== while ( true @@ -5177,5 +5187,9 @@ while (true) {} // comment while (true) /* comment */ ++x; +while (1) + // Comment + foo(); + ================================================================================ `; diff --git a/tests/js/comments/while.js b/tests/js/comments/while.js index c4ce2dc44..e63395a57 100644 --- a/tests/js/comments/while.js +++ b/tests/js/comments/while.js @@ -18,3 +18,6 @@ while( while(true) {} // comment while(true) /* comment */ ++x; + +while(1) // Comment + foo();