Skip to content

Commit d13f83d

Browse files
authored
SwiftSyntax: Factor out an API to decode serialized SourceFileSyntax. NFC (#14164)
Since our recent integration with SourceKit, clients may get a SourceFileSyntax in a serialized form from SourceKit response. We need an API in the SwiftSyntax framework to decode this form. This'll be a more common pattern to get a Swift side syntax tree than invoking swiftc internally.
1 parent 9c37cb8 commit d13f83d

File tree

1 file changed

+17
-1
lines changed

1 file changed

+17
-1
lines changed

tools/SwiftSyntax/SwiftSyntax.swift

+17-1
Original file line numberDiff line numberDiff line change
@@ -42,11 +42,27 @@ extension Syntax {
4242
guard result.wasSuccessful else {
4343
throw ParserError.swiftcFailed(result.exitCode, result.stderr)
4444
}
45+
return try decodeSourceFileSyntax(result.stdoutData)
46+
}
47+
48+
/// Decode a serialized form of SourceFileSyntax to a syntax node.
49+
/// - Parameter content: The data of the serialized SourceFileSyntax.
50+
/// - Returns: A top-level Syntax node representing the contents of the tree,
51+
/// if the parse was successful.
52+
fileprivate static func decodeSourceFileSyntax(_ content: Data) throws -> SourceFileSyntax {
4553
let decoder = JSONDecoder()
46-
let raw = try decoder.decode(RawSyntax.self, from: result.stdoutData)
54+
let raw = try decoder.decode(RawSyntax.self, from: content)
4755
guard let file = makeSyntax(raw) as? SourceFileSyntax else {
4856
throw ParserError.invalidFile
4957
}
5058
return file
5159
}
60+
61+
/// Decode a serialized form of SourceFileSyntax to a syntax node.
62+
/// - Parameter content: The string content of the serialized SourceFileSyntax.
63+
/// - Returns: A top-level Syntax node representing the contents of the tree,
64+
/// if the parse was successful.
65+
public static func decodeSourceFileSyntax(_ content: String) throws -> SourceFileSyntax {
66+
return try decodeSourceFileSyntax(content.data(using: .utf8)!)
67+
}
5268
}

0 commit comments

Comments
 (0)