Skip to content

Add a convenience initializer for TernaryExpr #610

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Aug 20, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -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
)
}
}

Original file line number Diff line number Diff line change
Expand Up @@ -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
)
Expand Down
14 changes: 14 additions & 0 deletions Tests/SwiftSyntaxBuilderTest/TernaryExprTests.swift
Original file line number Diff line number Diff line change
@@ -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
""")
}
}