swiftlang / swiftlang/swift-syntax

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

Open
#2,948 2 comments 0 reactions 0 assignees View on GitHub
Dominant language
Swift
Stars
3.7k
Forks
553
Avg merge
5d 13h
Merged PRs (30d)
16

Description

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:

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

The current implementation would require the code below:

```swift
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):

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

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.