Skip to content

Commit 54ff9a2

Browse files
authored
Merge pull request #459 from evnik/FunctionCallExpr
2 parents 3c8f29f + 71d6ba4 commit 54ff9a2

File tree

2 files changed

+28
-5
lines changed

2 files changed

+28
-5
lines changed

Sources/SwiftSyntaxBuilder/FunctionCallExprConvenienceInitializers.swift

Lines changed: 8 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -14,19 +14,22 @@
1414
import SwiftSyntax
1515

1616
extension FunctionCallExpr {
17+
/// A convenience initializer that allows passing in arguments using a result builder
18+
/// instead of having to wrap them in a `TupleExprElementList`.
19+
/// The presence of the parenthesis will be inferred based on the presence of arguments and the trailing closure.
1720
public init(
1821
_ calledExpression: ExpressibleAsExprBuildable,
19-
leftParen: TokenSyntax? = .leftParen,
20-
rightParen: TokenSyntax? = .rightParen,
2122
trailingClosure: ExpressibleAsClosureExpr? = nil,
2223
@TupleExprElementListBuilder argumentListBuilder: () -> ExpressibleAsTupleExprElementList = { TupleExprElementList([]) },
2324
@MultipleTrailingClosureElementListBuilder additionalTrailingClosuresBuilder: () -> MultipleTrailingClosureElementList? = { nil }
2425
) {
26+
let argumentList = argumentListBuilder().createTupleExprElementList()
27+
let shouldOmitParens = argumentList.elements.isEmpty && trailingClosure != nil
2528
self.init(
2629
calledExpression: calledExpression.createExprBuildable(),
27-
leftParen: leftParen,
28-
argumentList: argumentListBuilder(),
29-
rightParen: rightParen,
30+
leftParen: shouldOmitParens ? nil : .leftParen,
31+
argumentList: argumentList,
32+
rightParen: shouldOmitParens ? nil : .rightParen,
3033
trailingClosure: trailingClosure,
3134
additionalTrailingClosures: additionalTrailingClosuresBuilder()
3235
)

Tests/SwiftSyntaxBuilderTest/FunctionTests.swift

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -60,4 +60,24 @@ final class FunctionTests: XCTestCase {
6060
}
6161
""")
6262
}
63+
64+
func testParensEmittedForNoArgumentsAndNoTrailingClosure() {
65+
let buildable = FunctionCallExpr("test")
66+
let syntax = buildable.buildSyntax(format: Format())
67+
XCTAssertEqual(syntax.description, "test()")
68+
}
69+
70+
func testParensEmittedForArgumentAndTrailingClosure() {
71+
let buildable = FunctionCallExpr("test", trailingClosure: ClosureExpr(), argumentListBuilder: {
72+
TupleExprElement(expression: "42")
73+
})
74+
let syntax = buildable.buildSyntax(format: Format())
75+
XCTAssertEqual(syntax.description, "test(42){}")
76+
}
77+
78+
func testParensOmittedForNoArgumentsAndTrailingClosure() {
79+
let buildable = FunctionCallExpr("test", trailingClosure: ClosureExpr())
80+
let syntax = buildable.buildSyntax(format: Format())
81+
XCTAssertEqual(syntax.description, "test{}")
82+
}
6383
}

0 commit comments

Comments
 (0)