Skip to content

Commit 3b370e0

Browse files
committed
Add convenience initializer for CustomAttribute
1 parent bb62ba2 commit 3b370e0

File tree

2 files changed

+58
-0
lines changed

2 files changed

+58
-0
lines changed
Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
//===----------------------------------------------------------------------===//
2+
//
3+
// This source file is part of the Swift.org open source project
4+
//
5+
// Copyright (c) 2014 - 2022 Apple Inc. and the Swift project authors
6+
// Licensed under Apache License v2.0 with Runtime Library Exception
7+
//
8+
// See https://swift.org/LICENSE.txt for license information
9+
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
10+
//
11+
//===----------------------------------------------------------------------===//
12+
13+
import SwiftSyntax
14+
15+
extension CustomAttribute {
16+
/// A convenience initializer that allows passing in arguments using a result builder
17+
/// and automatically adds parentheses as needed, similar to the convenience
18+
/// initializer for `FunctionCallExpr`.
19+
public init(
20+
_ attributeName: ExpressibleAsTypeBuildable,
21+
@TupleExprElementListBuilder argumentList: () -> ExpressibleAsTupleExprElementList? = { nil }
22+
) {
23+
let argumentList = argumentList()
24+
self.init(
25+
attributeName: attributeName,
26+
leftParen: argumentList.map { _ in .leftParen },
27+
argumentList: argumentList,
28+
rightParen: argumentList.map { _ in .rightParen }
29+
)
30+
}
31+
}
32+
Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
import XCTest
2+
import SwiftSyntax
3+
import SwiftSyntaxBuilder
4+
5+
final class CustomAttributeTests: XCTestCase {
6+
func testCustomAttributeConvenienceInitializer() {
7+
let testCases: [UInt: (CustomAttribute, String)] = [
8+
#line: (CustomAttribute("Test"), "@Test"),
9+
#line: (CustomAttribute("WithParens") {}, "@WithParens()"),
10+
#line: (CustomAttribute("WithArgs") {
11+
TupleExprElement(expression: "value1")
12+
TupleExprElement(label: "labelled", expression: "value2")
13+
}, "@WithArgs(value1, labelled: value2)"),
14+
]
15+
16+
for (line, testCase) in testCases {
17+
let (builder, expected) = testCase
18+
let syntax = builder.buildSyntax(format: Format())
19+
20+
var text = ""
21+
syntax.write(to: &text)
22+
23+
XCTAssertEqual(text, expected, line: line)
24+
}
25+
}
26+
}

0 commit comments

Comments
 (0)