Hi @sebsto. I would suggest to use the SyntaxBuilder initializers, they should be those with the header parameter if I remember correctly (typing from my phone as well so I canât check). Then you can simply do
StructDeclSyntax("struct MyStruct: Codable, Sendable") {
"let myProp: Int"
}
Basically the brackets of the trailing closure represents the brackets of the declaration you will get as output.
Another example:
let source = try SourceFileSyntax {
try StructDeclSyntax("struct MyStruct: Codable, Sendable") {
"let myArray: [Int]"
"let myEnum: MyNestedEnum"
try FunctionDeclSyntax("func bar() async throws -> Int") {
"var result = 0"
try ForStmtSyntax("for elem in myArray") {
"result += elem"
}
"return result"
}
try EnumDeclSyntax("enum MyNestedEnum: String, Codable, Sendable") {
"case a"
"case b"
for other in ["c", "d", "e"] {
"case \(raw: other)"
}
}
}
}
print(source.formatted())
Output:
struct MyStruct: Codable, Sendable {
let myArray: [Int]
let myEnum: MyNestedEnum
func bar() async throws -> Int {
var result = 0
for elem in myArray {
result += elem
}
return result
}
enum MyNestedEnum: String, Codable, Sendable {
case a
case b
case c
case d
case e
}
}
EDIT:
For this specific example, you can skip the whole FunctionDeclSyntax
and just write the following as a multi line string
"""
func bar() async throws -> Int {
var result = 0
for elem in myArray {
result += elem
}
return result
}
"""
but once you need to add custom logic, swift-syntax will emit warnings and format the output with the wrong indentation if a parsed string isn't a valid declaration, so for example the following would emit warnings and the result would probably be wrongly formatted:
"for elem in myArray {"
if someCondition {
"result += elem"
} else {
"result -= elem"
"}"
This happens because when swift-syntax parses "for elem in myArray {"
it expects to find a closing bracket in the same string, but it doesn't