Repository: swiftlang/swift-syntax (swift)

Issue:
`ArrayExprSyntax` initializer that takes an array of `ExprSyntax`
### Description

Constructing an `ArrayExprSyntax` from a Swift array of arbitrary `ExprSyntax` values is a bit of a pain. Right now, we do silly dances like:

```swift
let exprs: [ExprSyntax] = ...
let exprString = exprs.lazy
  .map(\.trimmedDescription)
  .joined(separator: ", ")
return ExprSyntax("[\(raw: exprString)]").as(ArrayExprSyntax.self)
```

Having a convenience initializer that inserts commas and necessary trailing trivia would make this much nicer.

Pull request:
Resolve #1674

I have added initializers for `ArrayExprSyntax` and `ArrayElementListSyntax` that allow codes like below

```swift
let expressions: [ExprSyntax] = ...
let arrayExprSyntax = ArrayExprSyntax(expressions: expressions)
```

( I'm not sure if I need to write a test for the `ArrayExprSyntax` initializer or where to place it. )

Patch:
diff --git a/Sources/SwiftSyntaxBuilder/ConvenienceInitializers.swift b/Sources/SwiftSyntaxBuilder/ConvenienceInitializers.swift
index a6e811ff336..b6ff4b16bde 100644
--- a/Sources/SwiftSyntaxBuilder/ConvenienceInitializers.swift
+++ b/Sources/SwiftSyntaxBuilder/ConvenienceInitializers.swift
@@ -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
+      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 {


Test patch:
diff --git a/Tests/SwiftSyntaxBuilderTest/ArrayExprTests.swift b/Tests/SwiftSyntaxBuilderTest/ArrayExprTests.swift
index 1b5e2759e79..4bdb98bec31 100644
--- a/Tests/SwiftSyntaxBuilderTest/ArrayExprTests.swift
+++ b/Tests/SwiftSyntaxBuilderTest/ArrayExprTests.swift
@@ -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]")
+  }
 }