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

fix [#2632](https://github.com/microsoft/typespec/issues/2632)

---------

Co-authored-by: Mark Cowlishaw <markcowl@microsoft.com>
This commit is contained in:
Timothee Guerin 2023-11-27 16:36:38 -08:00 коммит произвёл GitHub
Родитель 5823b16204
Коммит 05b57fdc66
Не найден ключ, соответствующий данной подписи
Идентификатор ключа GPG: 4AEE18F83AFDEB23
3 изменённых файлов: 51 добавлений и 0 удалений

Просмотреть файл

@ -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"
}

Просмотреть файл

@ -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

Просмотреть файл

@ -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({