Skip to content

Commit

Permalink
Improved multiline closure comment detection
Browse files Browse the repository at this point in the history
Fixes #6067
  • Loading branch information
Yang Su committed May 4, 2019
1 parent 26183e5 commit 4a67b6f
Show file tree
Hide file tree
Showing 4 changed files with 68 additions and 3 deletions.
36 changes: 36 additions & 0 deletions CHANGELOG.unreleased.md
Expand Up @@ -151,4 +151,40 @@ Examples:
{{/if}}
e
{{/if}}


- JavaScript: Improved multiline closure compiler typecast comment detection ([#6070] by [@yangsu])

Previously, multiline closure compiler typecast comments with lines that
start with \* weren't flagged correctly and the subsequent parenthesis were
stripped. Prettier master fixes this issue.
<!-- prettier-ignore --\>
```js
// Input
const style =/**
* @type {{
* width: number,
* }}
*/({
width,
});
// Output (Prettier stable)
const style =/**
* @type {{
* width: number,
* }}
*/ {
width,
};
// Output (Prettier master)
const style =/**
* @type {{
* width: number,
* }}
*/({
width,
});
```
11 changes: 8 additions & 3 deletions src/language-js/needs-parens.js
Expand Up @@ -45,13 +45,18 @@ function hasClosureCompilerTypeCastComment(text, path) {
}

function isTypeCastComment(comment) {
const trimmed = comment.trim();
if (!/^\*\s*@type\s*\{[^]+\}$/.test(trimmed)) {
const cleaned = comment
.trim()
.split("\n")
.map(line => line.replace(/^[\s*]+/, ""))
.join(" ")
.trim();
if (!/^@type\s+\{[^]+\}$/.test(cleaned)) {
return false;
}
let isCompletelyClosed = false;
let unpairedBracketCount = 0;
for (const char of trimmed) {
for (const char of cleaned) {
if (char === "{") {
if (isCompletelyClosed) {
return false;
Expand Down
16 changes: 16 additions & 0 deletions tests/comments_closure_typecast/__snapshots__/jsfmt.spec.js.snap
Expand Up @@ -65,6 +65,14 @@ const style = /** @type {{
...margins,
});
const style =/**
* @type {{
* width: number,
* }}
*/({
width,
});
=====================================output=====================================
// test to make sure comments are attached correctly
let inlineComment = /* some comment */ someReallyLongFunctionCall(
Expand Down Expand Up @@ -128,5 +136,13 @@ const style = /** @type {{
...margins
});
const style = /**
* @type {{
* width: number,
* }}
*/ ({
width
});
================================================================================
`;
8 changes: 8 additions & 0 deletions tests/comments_closure_typecast/closure-compiler-type-cast.js
Expand Up @@ -56,3 +56,11 @@ const style = /** @type {{
height,
...margins,
});

const style =/**
* @type {{
* width: number,
* }}
*/({
width,
});

0 comments on commit 4a67b6f

Please sign in to comment.