Skip to content

Commit bd19d79

Browse files
committed
fix(prettier): keep JSDoc type-cast parentheses on return and throw
Stacked casts such as return /** @type {A} */ (/** @type {B} */ (x)) were wrapped to avoid ASI, and that wrap dropped the parentheses TypeScript needs for the comments to stay casts.
1 parent 2af0e22 commit bd19d79

3 files changed

Lines changed: 137 additions & 24 deletions

File tree

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
---
2+
'@tsrx/prettier-plugin': patch
3+
---
4+
5+
`return` and `throw` keep JSDoc type casts when the argument starts with more
6+
than one comment. `return /** @type {A} */ (/** @type {B} */ (x))` used to print
7+
both comments without the parentheses that make them casts, so TypeScript no
8+
longer treated them as casts. The same happened to `throw`, and to a cast that
9+
followed an own-line comment.

‎packages/prettier-plugin/src/index.js‎

Lines changed: 88 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -506,6 +506,27 @@ function isTypeCastComment(comment) {
506506
);
507507
}
508508

509+
/**
510+
* Whether `comment` is a JSDoc cast whose `(` opens before `nextStart`
511+
* (the next leading comment). One pair of parentheses around the whole value
512+
* only keeps the last cast; each earlier one has to be printed after its
513+
* comment.
514+
* @param {AST.Comment} comment
515+
* @param {number} nextStart
516+
* @param {TsrxFormatOptions} options
517+
* @returns {boolean}
518+
*/
519+
function commentOpensTypeCast(comment, nextStart, options) {
520+
if (!isTypeCastComment(comment) || typeof options.originalText !== 'string') {
521+
return false;
522+
}
523+
const end = /** @type {AST.NodeWithLocation} */ (comment).end;
524+
if (typeof end !== 'number' || nextStart < end) {
525+
return false;
526+
}
527+
return /^\s*\(\s*$/.test(options.originalText.slice(end, nextStart));
528+
}
529+
509530
/**
510531
* Whether a parenthesized node's parentheses complete a JSDoc type cast:
511532
* `/** @type {T} *\/ (value)` only casts `value` with them. The cast comment
@@ -1659,6 +1680,11 @@ function printTsrxNode(node, path, options, print, args) {
16591680

16601681
/** @type {Doc[]} */
16611682
const parts = [];
1683+
// Leading comments fill this list. A stacked JSDoc cast reassigns it to the
1684+
// inside of the parentheses that comment opens, so later comments hug that
1685+
// `(`.
1686+
/** @type {Doc[]} */
1687+
let commentParts = parts;
16621688

16631689
const isInlineContext = args && args.isInlineContext;
16641690
const suppressLeadingComments = args && args.suppressLeadingComments;
@@ -1671,24 +1697,43 @@ function printTsrxNode(node, path, options, print, args) {
16711697
const isLastComment = i === node.leadingComments.length - 1;
16721698

16731699
if (comment.type === 'Line') {
1674-
parts.push('//' + comment.value);
1675-
parts.push(hardline);
1700+
commentParts.push('//' + comment.value);
1701+
commentParts.push(hardline);
16761702

16771703
// Check if there should be blank lines between this comment and the next
16781704
if (nextComment) {
16791705
const blankLinesBetween = getBlankLinesBetweenNodes(comment, nextComment);
16801706
if (blankLinesBetween > 0) {
1681-
parts.push(hardline);
1707+
commentParts.push(hardline);
16821708
}
16831709
} else if (isLastComment && node.type !== 'JSXText') {
16841710
// Preserve a blank line between the last comment and the node if it existed
16851711
const blankLinesBetween = getBlankLinesBetweenNodes(comment, node);
16861712
if (blankLinesBetween > 0) {
1687-
parts.push(hardline);
1713+
commentParts.push(hardline);
16881714
}
16891715
}
16901716
} else if (comment.type === 'Block') {
1691-
parts.push('/*' + comment.value + '*/');
1717+
commentParts.push('/*' + comment.value + '*/');
1718+
1719+
const nextStart = /** @type {AST.NodeWithLocation} */ (nextComment ?? node).start;
1720+
if (
1721+
nextComment &&
1722+
typeof nextStart === 'number' &&
1723+
commentOpensTypeCast(comment, nextStart, options)
1724+
) {
1725+
// The `(` between this cast and the next comment is what makes
1726+
// the comment a cast. Keep it here; the innermost pair is
1727+
// printed around the value.
1728+
const inner = /** @type {Doc[]} */ ([]);
1729+
const blankLinesBetween = getBlankLinesBetweenNodes(comment, nextComment);
1730+
// A blank line belongs after the opening `(`, not before the close.
1731+
const openBreak = blankLinesBetween > 0 ? [hardline, hardline] : softline;
1732+
const closeBreak = blankLinesBetween > 0 ? hardline : softline;
1733+
commentParts.push(' ', group(['(', indent([openBreak, inner]), closeBreak, ')']));
1734+
commentParts = inner;
1735+
continue;
1736+
}
16921737

16931738
// Check if comment and node are on the same line (for inline JSDoc comments)
16941739
const isCommentInlineWithParen =
@@ -1698,23 +1743,23 @@ function printTsrxNode(node, path, options, print, args) {
16981743
const shouldKeepOnSameLine = isCommentOnSameLine || isCommentInlineWithParen;
16991744

17001745
if (!isInlineContext && !shouldKeepOnSameLine) {
1701-
parts.push(hardline);
1746+
commentParts.push(hardline);
17021747

17031748
// Check if there should be blank lines between this comment and the next
17041749
if (nextComment) {
17051750
const blankLinesBetween = getBlankLinesBetweenNodes(comment, nextComment);
17061751
if (blankLinesBetween > 0) {
1707-
parts.push(hardline);
1752+
commentParts.push(hardline);
17081753
}
17091754
} else if (isLastComment) {
17101755
// Preserve a blank line between the last comment and the node if it existed
17111756
const blankLinesBetween = getBlankLinesBetweenNodes(comment, node);
17121757
if (blankLinesBetween > 0) {
1713-
parts.push(hardline);
1758+
commentParts.push(hardline);
17141759
}
17151760
}
17161761
} else {
1717-
parts.push(' ');
1762+
commentParts.push(' ');
17181763
}
17191764
}
17201765
}
@@ -2866,7 +2911,8 @@ function printTsrxNode(node, path, options, print, args) {
28662911
) {
28672912
// The comment prints on its own line, which would separate `return`
28682913
// from its argument and trigger ASI — keep the argument in parens.
2869-
// These parens replace any the argument would print for itself.
2914+
// These parens replace precedence parentheses the argument would
2915+
// print for itself. A JSDoc type cast keeps its own parentheses.
28702916
parts.push(
28712917
' (',
28722918
indent([
@@ -3377,18 +3423,28 @@ function printTsrxNode(node, path, options, print, args) {
33773423
nodeContent = [...printDecorators(decorated, path, options, print), nodeContent];
33783424
}
33793425

3380-
if (!args?.suppressOwnParens) {
3381-
if (hasTypeCastParens(path, options)) {
3382-
// Like Prettier, a cast breaks inside its parens unless it hugs a literal
3383-
nodeContent =
3384-
node.type === 'ObjectExpression' || node.type === 'ArrayExpression'
3385-
? ['(', nodeContent, ')']
3386-
: group(['(', indent([softline, nodeContent]), softline, ')']);
3387-
} else if (needsParens(path, options)) {
3388-
nodeContent = ['(', nodeContent, ')'];
3389-
}
3426+
// A parent that prints its own parens (`return` / `throw` with a leading
3427+
// comment, a superclass) passes `suppressOwnParens` so precedence
3428+
// parentheses are not doubled. JSDoc type-cast parentheses are not those:
3429+
// the comment is only a cast when it hugs `(expr)`.
3430+
if (hasTypeCastParens(path, options)) {
3431+
// Like Prettier, a cast breaks inside its parens unless it hugs a literal
3432+
nodeContent =
3433+
node.type === 'ObjectExpression' || node.type === 'ArrayExpression'
3434+
? ['(', nodeContent, ')']
3435+
: group(['(', indent([softline, nodeContent]), softline, ')']);
3436+
} else if (!args?.suppressOwnParens && needsParens(path, options)) {
3437+
nodeContent = ['(', nodeContent, ')'];
33903438
}
33913439

3440+
if (commentParts !== parts) {
3441+
// Trailing comments belong with the value, inside the cast parentheses.
3442+
const finished = finishTsrxNode(/** @type {AST.Node} */ (node), commentParts, nodeContent);
3443+
if (finished !== commentParts) {
3444+
commentParts.push(finished);
3445+
}
3446+
return parts;
3447+
}
33923448
return finishTsrxNode(/** @type {AST.Node} */ (node), parts, nodeContent);
33933449
}
33943450

@@ -5578,7 +5634,8 @@ function printThrowStatement(node, path, options, print) {
55785634
const parts = [];
55795635
if (path.call((argumentPath) => getOwnLineCommentAhead(argumentPath, options), 'argument')) {
55805636
// Same ASI hazard as `return`: keep the argument attached via parens.
5581-
// These parens replace any the argument would print for itself.
5637+
// These parens replace precedence parentheses the argument would
5638+
// print for itself. A JSDoc type cast keeps its own parentheses.
55825639
parts.push(
55835640
'throw (',
55845641
indent([
@@ -5598,8 +5655,9 @@ function printThrowStatement(node, path, options, print) {
55985655

55995656
/**
56005657
* Whether printTsrxNode ends a node's leading comments with a line break. It
5601-
* does after a line comment, and after a block comment unless that is the last
5602-
* comment and shares its line with the node or with a type cast's `(`.
5658+
* does after a line comment, and after a block comment unless that comment
5659+
* hugs a type cast's `(`, or it is the last comment and shares its line with
5660+
* the node or with a type cast's `(`.
56035661
* @param {AST.Node} node - The node
56045662
* @param {TsrxFormatOptions} options - Prettier options
56055663
* @returns {boolean}
@@ -5610,9 +5668,15 @@ function hasOwnLineLeadingComment(node, options) {
56105668
return false;
56115669
}
56125670
return comments.some((comment, index) => {
5613-
if (comment.type === 'Line' || index < comments.length - 1) {
5671+
if (comment.type === 'Line') {
56145672
return true;
56155673
}
5674+
if (index < comments.length - 1) {
5675+
const nextStart = /** @type {AST.NodeWithLocation} */ (comments[index + 1]).start;
5676+
// A stacked cast prints `(` after this comment, so the comment does
5677+
// not end the line between `return`/`throw` and the argument.
5678+
return !(typeof nextStart === 'number' && commentOpensTypeCast(comment, nextStart, options));
5679+
}
56165680
const isOnNodeLine = comment.loc && node.loc && comment.loc.end.line === node.loc.start.line;
56175681
return !isOnNodeLine && !isCommentFollowedBySameLineParen(comment, options);
56185682
});

‎packages/prettier-plugin/src/index.test.js‎

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7956,6 +7956,46 @@ function fail() {
79567956
// pick the error
79577957
errors.first
79587958
);
7959+
}`;
7960+
const result = await format(input);
7961+
expect(result).toBeWithNewline(expected);
7962+
});
7963+
7964+
// A JSDoc cast is only a cast while its comment hugs `(expr)`. Wrapping
7965+
// the argument to avoid ASI used to drop those parentheses.
7966+
it('keeps JSDoc type casts on a return or throw argument with leading comments', async () => {
7967+
const input = `function run() {
7968+
return /** @type {A} */ (/** @type {B} */ (x));
7969+
}
7970+
function fail() {
7971+
throw /** @type {A} */ (/** @satisfies {B} */ (x));
7972+
}
7973+
function noted() {
7974+
return (
7975+
// note
7976+
/** @type {T} */ (value)
7977+
);
7978+
}
7979+
function blocked() {
7980+
return /* note */ /** @type {A} */ (/** @type {B} */ (x));
7981+
}`;
7982+
const expected = `function run() {
7983+
return /** @type {A} */ (/** @type {B} */ (x));
7984+
}
7985+
function fail() {
7986+
throw /** @type {A} */ (/** @satisfies {B} */ (x));
7987+
}
7988+
function noted() {
7989+
return (
7990+
// note
7991+
/** @type {T} */ (value)
7992+
);
7993+
}
7994+
function blocked() {
7995+
return (
7996+
/* note */
7997+
/** @type {A} */ (/** @type {B} */ (x))
7998+
);
79597999
}`;
79608000
const result = await format(input);
79618001
expect(result).toBeWithNewline(expected);

0 commit comments

Comments
 (0)