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

Formatter: Fix valueof should keep parentheses in union and array expression #2686

Merged
Merged
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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 () => {
timotheeguerin marked this conversation as resolved.
Show resolved Hide resolved
await assertFormat({
code: `
alias A = (valueof string)[];
`,
expected: `
alias A = (valueof string)[];
`,
});
});
});

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