Skip to content

Add an initializer that accepts [ExprSyntax] for ArrayExprSyntax #1693

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
May 24, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 25 additions & 0 deletions Sources/SwiftSyntaxBuilder/ConvenienceInitializers.swift
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,31 @@
@_spi(RawSyntax) import SwiftParser
@_spi(RawSyntax) import SwiftSyntax

// MARK: - ArrayElementList

extension ArrayElementListSyntax {
public init(expressions: [ExprSyntax]) {
let lastIndex = expressions.count - 1
let elements = expressions.enumerated().map { index, expression in
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It's valid for the last element to have a trailing comma in an array literal, so there's no need for enumerated() or index-checking here.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

SwiftSyntaxBuilder doesn’t add a trailing comma for the last element, so I’d prefer to be consistent between the two initializers her and also not add a trailing comma here either. So: I’d prefer to keep it as you wrote it @gibachan.

let element = ArrayElementSyntax(expression: expression)
if index < lastIndex {
return element.ensuringTrailingComma()
} else {
return element
}
}
self.init(elements)
}
}

// MARK: - ArrayExpr

extension ArrayExprSyntax {
public init(expressions: [ExprSyntax]) {
self.init(elements: ArrayElementListSyntax(expressions: expressions))
}
}

// MARK: - CustomAttribute

extension AttributeSyntax {
Expand Down
6 changes: 6 additions & 0 deletions Tests/SwiftSyntaxBuilderTest/ArrayExprTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -47,4 +47,10 @@ final class ArrayExprTests: XCTestCase {
"""
)
}

func testInitializerWithExpressions() {
let expressions: [ExprSyntax] = ["0", "1", "2"]
let arrayExpr = ArrayExprSyntax(expressions: expressions)
XCTAssertEqual(arrayExpr.description, "[0,1,2]")
}
}