Skip to content

Commit

Permalink
Formatter: Fix valueof should keep parentheses in union and array e…
Browse files Browse the repository at this point in the history
…xpression (#2686)

fix [#2632](#2632)

---------

Co-authored-by: Mark Cowlishaw <[email protected]>
  • Loading branch information
timotheeguerin and markcowl authored Nov 28, 2023
1 parent 5823b16 commit 05b57fd
Show file tree
Hide file tree
Showing 3 changed files with 51 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
{
"changes": [
{
"packageName": "@typespec/compiler",
"comment": "Formatter: Fix: `valueof` expression with parentheses around will preserve them when they are meaningful(For example inside a union or array expression)",
"type": "none"
}
],
"packageName": "@typespec/compiler"
}
6 changes: 6 additions & 0 deletions packages/compiler/src/formatter/print/needs-parens.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,12 @@ export function needsParens(path: AstPath<Node>, options: TypeSpecPrettierOption
// eslint-disable-next-line deprecation/deprecation
const node = path.getValue();
switch (node.kind) {
case SyntaxKind.ValueOfExpression:
return (
parent.kind === SyntaxKind.UnionExpression ||
parent.kind === SyntaxKind.ArrayExpression ||
parent.kind === SyntaxKind.IntersectionExpression
);
case SyntaxKind.IntersectionExpression:
return (
parent.kind === SyntaxKind.UnionExpression || parent.kind === SyntaxKind.ArrayExpression
Expand Down
35 changes: 35 additions & 0 deletions packages/compiler/test/formatter/formatter.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2429,6 +2429,41 @@ model Foo {
});
});

describe("valueof", () => {
it("format simple valueof", async () => {
await assertFormat({
code: `
alias A = valueof string;
`,
expected: `
alias A = valueof string;
`,
});
});

it("keeps parentheses around valueof inside a union", async () => {
await assertFormat({
code: `
alias A = (valueof string) | Model;
`,
expected: `
alias A = (valueof string) | Model;
`,
});
});

it("keeps parentheses around valueof inside a array expression", async () => {
await assertFormat({
code: `
alias A = (valueof string)[];
`,
expected: `
alias A = (valueof string)[];
`,
});
});
});

describe("projections", () => {
it("format projections", async () => {
await assertFormat({
Expand Down

0 comments on commit 05b57fd

Please sign in to comment.