Skip to content

Commit 6ce8c48

Browse files
authored
Merge pull request #610 from fwcd/ternary-convenience-init
Add a convenience initializer for `TernaryExpr`
2 parents 70e4f96 + 84aa2a8 commit 6ce8c48

File tree

3 files changed

+47
-5
lines changed

3 files changed

+47
-5
lines changed
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
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 TernaryExpr {
16+
public init(
17+
if condition: ExpressibleAsExprBuildable,
18+
then firstChoice: ExpressibleAsExprBuildable,
19+
else secondChoice: ExpressibleAsExprBuildable
20+
) {
21+
self.init(
22+
conditionExpression: condition,
23+
questionMark: .infixQuestionMarkToken(leadingTrivia: .space, trailingTrivia: .space),
24+
firstChoice: firstChoice,
25+
colonMark: .colonToken(leadingTrivia: .space),
26+
secondChoice: secondChoice
27+
)
28+
}
29+
}
30+

Sources/generate-swift-syntax-builder/Templates/BuildableNodesFile.swift

Lines changed: 3 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -355,11 +355,9 @@ private func createWithTrailingCommaFunction(node: Node) -> FunctionDecl {
355355
label: child.swiftName,
356356
expression: child.name == "TrailingComma" ? SequenceExpr {
357357
TernaryExpr(
358-
conditionExpression: "withComma",
359-
questionMark: .infixQuestionMark.withLeadingTrivia(.space).withTrailingTrivia(.space),
360-
firstChoice: MemberAccessExpr(name: "comma"),
361-
colonMark: .colon.withLeadingTrivia(.space).withTrailingTrivia(.space),
362-
secondChoice: NilLiteralExpr()
358+
if: "withComma",
359+
then: MemberAccessExpr(name: "comma"),
360+
else: NilLiteralExpr()
363361
)
364362
} : child.swiftName
365363
)
Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
import XCTest
2+
import SwiftSyntax
3+
import SwiftSyntaxBuilder
4+
5+
final class TernaryExprTests: XCTestCase {
6+
func testTernaryExpr() {
7+
let buildable = TernaryExpr(if: BooleanLiteralExpr(true), then: "a", else: "b")
8+
let syntax = buildable.buildSyntax(format: Format())
9+
XCTAssertEqual(syntax.description, """
10+
true ? a : b
11+
""")
12+
}
13+
}
14+

0 commit comments

Comments
 (0)