Skip to content

Add the ability to create VariableDeclSyntax instances with multiple accessors using a result builder #2948

Open
@thafner0

Description

@thafner0

Creating VariableDeclSyntax instances using a result builder is super helpful to generate readable yet flexible code. This functionality works fine if generating a single get accessor using the abbreviated syntax (simple closure with statements being used in the getter). However, if it is necessary to have multiple accessors, this requires much more messy code since result builders don't support multiple accessors at this time. It would be ideal to have a second result builder initializer that accepted a closure returning a AccessorDeclListSyntax using an AccessorDeclListBuilder to construct the list of accessors. The two initializers could use a shared private initializer that would be responsible for doing all common work done in both with the two precise implementations merely handling the difference in AccessorDeclSyntax.Accessors case.

Comparison Between Current and Proposed Implmentations

The proposed implementation is only adding to what is already present and would be added into the SwiftSyntaxBuilder target. The below code snippets assume that SwiftSyntax and SwiftSyntaxBuilder are both imported.

Current Implementation

To generate the code below:

var example: Int {
get {
// code in getter
}
set {
// code in setter
}
}

The current implementation would require the code below:

VariableDeclSyntax(
bindingSpecifier: .keyword(.var, trailingTrivia: .space),
bindingsBuilder: PatternBindingListSyntax {
PatternBindingSyntax(
pattern: PatternSyntax("example"),
typeAnnotation: TypeAnnotationSyntax(
colon: .colonToken(trailingTrivia: .space),
type: TypeSyntax("Int")
),
accessorBlock: .accessors(AccessorDeclListSyntax {
try! AccessorDeclSyntax("get") {
// getter code represented as SwiftSyntax types
}
try! AccessorDeclSyntax("set") {
// setter code represented as SwiftSyntax types
}
})
}
)

The code immediately above could be simplified under the proposed changes as shown below (providing there is only one binding, which is a similar requirement to the existing implementation of result builders for getter-only accessors):

VariableDeclSyntax("var example: Int") {
try! AccessorDeclSyntax("get") {
// getter code represented as SwiftSyntax types
}
try! AccessorDeclSyntax("set") {
// setter code represented as SwiftSyntax types
}
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions