diff --git a/.chronus/changes/fix-formatting-object-array-literal-hug-2024-5-13-20-4-7.md b/.chronus/changes/fix-formatting-object-array-literal-hug-2024-5-13-20-4-7.md new file mode 100644 index 0000000000..49283b977e --- /dev/null +++ b/.chronus/changes/fix-formatting-object-array-literal-hug-2024-5-13-20-4-7.md @@ -0,0 +1,8 @@ +--- +# Change versionKind to one of: internal, fix, dependencies, feature, deprecation, breaking +changeKind: fix +packages: + - "@typespec/compiler" +--- + +Fix formatting of object and array literal in decorator to hug parenthesis diff --git a/packages/compiler/src/formatter/print/printer.ts b/packages/compiler/src/formatter/print/printer.ts index 969ec4bb81..c982c709be 100644 --- a/packages/compiler/src/formatter/print/printer.ts +++ b/packages/compiler/src/formatter/print/printer.ts @@ -700,12 +700,14 @@ function printCallOrDecoratorArgs( } // So that decorator with single object arguments have ( and { hugging. - // @deco({ + // @deco(#{ // value: "foo" // }) const shouldHug = node.arguments.length === 1 && (node.arguments[0].kind === SyntaxKind.ModelExpression || + node.arguments[0].kind === SyntaxKind.ObjectLiteral || + node.arguments[0].kind === SyntaxKind.ArrayLiteral || node.arguments[0].kind === SyntaxKind.StringLiteral || node.arguments[0].kind === SyntaxKind.StringTemplateExpression); diff --git a/packages/compiler/test/formatter/formatter.test.ts b/packages/compiler/test/formatter/formatter.test.ts index 2443435437..39b04d7ed8 100644 --- a/packages/compiler/test/formatter/formatter.test.ts +++ b/packages/compiler/test/formatter/formatter.test.ts @@ -852,6 +852,59 @@ scalar Foo { }); }); }); + + describe("scalar constructor call", () => { + it("simple call", async () => { + await assertFormat({ + code: ` +const foo = utcDateTime. fromISO( + "abc" ); +`, + expected: ` +const foo = utcDateTime.fromISO("abc"); +`, + }); + }); + + it("hug object literal", async () => { + await assertFormat({ + code: ` +const foo = utcDateTime. fromFoo(#{ name: "abc", + multiline1: "abc", + multiline2: "abc", + multiline3: "abc", }); +`, + expected: ` +const foo = utcDateTime.fromFoo(#{ + name: "abc", + multiline1: "abc", + multiline2: "abc", + multiline3: "abc", +}); +`, + }); + }); + + it("hug array literal", async () => { + await assertFormat({ + code: ` +const foo = utcDateTime. fromFoo(#[ + "very very long array", + "very very long array", + "very very long array" +]); +`, + expected: ` +const foo = utcDateTime.fromFoo(#[ + "very very long array", + "very very long array", + "very very long array" +]); +`, + }); + }); + }); + describe("comments", () => { it("format comment at position 0", async () => { await assertFormat({