Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Improved multiline closure comment detection #6070

Merged
merged 2 commits into from May 7, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
35 changes: 35 additions & 0 deletions CHANGELOG.unreleased.md
Expand Up @@ -151,4 +151,39 @@ 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,
});