Skip to content

Commit 09591a7

Browse files
authored
Merge pull request #223 from ahoppen/constructor-from-syntax-protocol
Add an initializer to construct Syntax nodes from syntax protocol types
2 parents 997c82c + 74b6075 commit 09591a7

File tree

2 files changed

+18
-0
lines changed

2 files changed

+18
-0
lines changed

Sources/SwiftSyntax/Syntax.swift

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -39,6 +39,15 @@ public struct Syntax: SyntaxProtocol, SyntaxHashable {
3939
guard let syntax = syntax else { return nil }
4040
self = syntax._syntaxNode
4141
}
42+
43+
public init(fromProtocol syntax: SyntaxProtocol) {
44+
self = syntax._syntaxNode
45+
}
46+
47+
public init?(fromProtocol syntax: SyntaxProtocol?) {
48+
guard let syntax = syntax else { return nil }
49+
self = syntax._syntaxNode
50+
}
4251

4352
public func hash(into hasher: inout Hasher) {
4453
return data.nodeId.hash(into: &hasher)

Tests/SwiftSyntaxTest/SyntaxTests.swift

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -135,4 +135,13 @@ public class SyntaxTests: XCTestCase {
135135
XCTAssertTrue(integerExpr.syntaxNodeType == node.syntaxNodeType)
136136
XCTAssertEqual("\(integerExpr.syntaxNodeType)", "IntegerLiteralExprSyntax")
137137
}
138+
139+
public func testConstructFromSyntaxProtocol() {
140+
let integerExpr = IntegerLiteralExprSyntax {
141+
$0.useDigits(SyntaxFactory.makeIntegerLiteral("1", trailingTrivia: .spaces(1)))
142+
}
143+
144+
XCTAssertEqual(Syntax(integerExpr), Syntax(fromProtocol: integerExpr as SyntaxProtocol))
145+
XCTAssertEqual(Syntax(integerExpr), Syntax(fromProtocol: integerExpr as ExprSyntaxProtocol))
146+
}
138147
}

0 commit comments

Comments
 (0)