diff --git a/Sources/SwiftSyntaxBuilder/TernaryExprConvenienceInitializers.swift b/Sources/SwiftSyntaxBuilder/TernaryExprConvenienceInitializers.swift new file mode 100644 index 00000000000..88d59955a9c --- /dev/null +++ b/Sources/SwiftSyntaxBuilder/TernaryExprConvenienceInitializers.swift @@ -0,0 +1,30 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the Swift.org open source project +// +// Copyright (c) 2014 - 2022 Apple Inc. and the Swift project authors +// Licensed under Apache License v2.0 with Runtime Library Exception +// +// See https://swift.org/LICENSE.txt for license information +// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors +// +//===----------------------------------------------------------------------===// + +import SwiftSyntax + +extension TernaryExpr { + public init( + if condition: ExpressibleAsExprBuildable, + then firstChoice: ExpressibleAsExprBuildable, + else secondChoice: ExpressibleAsExprBuildable + ) { + self.init( + conditionExpression: condition, + questionMark: .infixQuestionMarkToken(leadingTrivia: .space, trailingTrivia: .space), + firstChoice: firstChoice, + colonMark: .colonToken(leadingTrivia: .space), + secondChoice: secondChoice + ) + } +} + diff --git a/Sources/generate-swift-syntax-builder/Templates/BuildableNodesFile.swift b/Sources/generate-swift-syntax-builder/Templates/BuildableNodesFile.swift index 4020344a208..39b16c55c6e 100644 --- a/Sources/generate-swift-syntax-builder/Templates/BuildableNodesFile.swift +++ b/Sources/generate-swift-syntax-builder/Templates/BuildableNodesFile.swift @@ -355,11 +355,9 @@ private func createWithTrailingCommaFunction(node: Node) -> FunctionDecl { label: child.swiftName, expression: child.name == "TrailingComma" ? SequenceExpr { TernaryExpr( - conditionExpression: "withComma", - questionMark: .infixQuestionMark.withLeadingTrivia(.space).withTrailingTrivia(.space), - firstChoice: MemberAccessExpr(name: "comma"), - colonMark: .colon.withLeadingTrivia(.space).withTrailingTrivia(.space), - secondChoice: NilLiteralExpr() + if: "withComma", + then: MemberAccessExpr(name: "comma"), + else: NilLiteralExpr() ) } : child.swiftName ) diff --git a/Tests/SwiftSyntaxBuilderTest/TernaryExprTests.swift b/Tests/SwiftSyntaxBuilderTest/TernaryExprTests.swift new file mode 100644 index 00000000000..ee0630145fa --- /dev/null +++ b/Tests/SwiftSyntaxBuilderTest/TernaryExprTests.swift @@ -0,0 +1,14 @@ +import XCTest +import SwiftSyntax +import SwiftSyntaxBuilder + +final class TernaryExprTests: XCTestCase { + func testTernaryExpr() { + let buildable = TernaryExpr(if: BooleanLiteralExpr(true), then: "a", else: "b") + let syntax = buildable.buildSyntax(format: Format()) + XCTAssertEqual(syntax.description, """ + true ? a : b + """) + } +} +