Skip to content

Commit bb0091f

Browse files
committed
Provide api to interpret ExprSyntax as VersionTupleSyntax
1 parent e42bece commit bb0091f

File tree

2 files changed

+48
-0
lines changed

2 files changed

+48
-0
lines changed
Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
//===----------------------------------------------------------------------===//
2+
//
3+
// This source file is part of the Swift.org open source project
4+
//
5+
// Copyright (c) 2014 - 2023 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+
@_spi(RawSyntax) import SwiftSyntax
14+
15+
extension ExprSyntax {
16+
public func asVersionTuple(with maxComponentCount: Int) -> VersionTupleSyntax? {
17+
var parser = Parser(self.description)
18+
let raw = parser.parseVersionTuple(maxComponentCount: maxComponentCount)
19+
return Syntax(raw: raw.raw, rawNodeArena: raw.raw.arena).as(VersionTupleSyntax.self)
20+
}
21+
}
Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
//===----------------------------------------------------------------------===//
2+
//
3+
// This source file is part of the Swift.org open source project
4+
//
5+
// Copyright (c) 2014 - 2023 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 SwiftParser
14+
import SwiftSyntax
15+
import XCTest
16+
17+
final class ExpressionInterpretedAsVersionTupleTest: XCTestCase {
18+
func testExpressionInterpretedAsVersionTuple() throws {
19+
let expression: ExprSyntax = "2.2.2.2"
20+
let versionTuple = try XCTUnwrap(expression.asVersionTuple(with: 4))
21+
let versionTupleComponents = try XCTUnwrap(versionTuple.components)
22+
XCTAssertTrue(!versionTuple.hasError)
23+
XCTAssertEqual(versionTuple.description, "2.2.2.2")
24+
XCTAssertEqual(versionTuple.major.description, "2")
25+
XCTAssertEqual(versionTupleComponents.description, ".2.2.2")
26+
}
27+
}

0 commit comments

Comments
 (0)