Skip to content

Commit 9e6d6bf

Browse files
authored
fix(compiler): preserve dangling comments in empty operation parameter list (#10351)
## Summary `tsp format` crashed on: ```tsp namespace MyApp; op find(/* conditions */): unknown; ``` with `TypeError: Cannot read properties of undefined (reading 'trim')` from prettier's ensureAllCommentsPrinted. ### Root cause printModelExpression (used for operation parameter lists) returned an empty string when the property list was empty, dropping any dangling comments. Prettier then detected an unprinted comment and threw. ### Fix Print dangling comments in the empty-properties branch so the block comment survives formatting. ## Test Added keeps block comment in empty parameter list to formatter.test.ts. All 199 formatter tests pass.
1 parent b99f92f commit 9e6d6bf

3 files changed

Lines changed: 35 additions & 6 deletions

File tree

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
---
2+
changeKind: fix
3+
packages:
4+
- "@typespec/compiler"
5+
---
6+
7+
Fix formatter crash when an operation's parameter list contains only a block comment (e.g. `op find(/* conditions */): unknown;`). Dangling comments in empty parameter lists are now preserved instead of being dropped.

packages/compiler/src/formatter/print/printer.ts

Lines changed: 13 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -969,12 +969,19 @@ export function printModelExpression(
969969
if (inBlock) {
970970
return group(printModelPropertiesBlock(path, options, print));
971971
} else {
972-
const properties =
973-
node.properties.length === 0
974-
? ""
975-
: indent(
976-
joinMembersInBlock(path, "properties", options, print, ifBreak(",", ", "), softline),
977-
);
972+
const nodeHasComments = hasComments(node, CommentCheckFlags.Dangling);
973+
if (node.properties.length === 0) {
974+
if (nodeHasComments) {
975+
return group([
976+
indent(printDanglingComments(path, options, { sameIndent: true })),
977+
softline,
978+
]);
979+
}
980+
return group(["", softline]);
981+
}
982+
const properties = indent(
983+
joinMembersInBlock(path, "properties", options, print, ifBreak(",", ", "), softline),
984+
);
978985
return group([properties, softline]);
979986
}
980987
}

packages/compiler/test/formatter/formatter.test.ts

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -737,6 +737,21 @@ op foo(
737737
});
738738
});
739739

740+
it("keeps block comment in empty parameter list", async () => {
741+
await assertFormat({
742+
code: `
743+
namespace MyApp;
744+
745+
op find( /* conditions */) : unknown;
746+
`,
747+
expected: `
748+
namespace MyApp;
749+
750+
op find(/* conditions */): unknown;
751+
`,
752+
});
753+
});
754+
740755
it("wrap in new lines parameters with block comments", async () => {
741756
await assertFormat({
742757
code: `

0 commit comments

Comments
 (0)