Skip to content

Commit bcbf634

Browse files
committed
Address Review Comments
1 parent eaabf79 commit bcbf634

File tree

5 files changed

+32
-34
lines changed

5 files changed

+32
-34
lines changed

Sources/SourceKitLSP/Swift/MacroExpansion.swift

Lines changed: 17 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -15,8 +15,6 @@ import LSPLogging
1515
import LanguageServerProtocol
1616
import SourceKitD
1717

18-
@_spi(Testing) public typealias MacroExpansionEdit = RefactoringEdit
19-
2018
/// Detailed information about the result of a macro expansion operation.
2119
///
2220
/// Wraps the information returned by sourcekitd's `semantic_refactoring`
@@ -28,15 +26,15 @@ struct MacroExpansion: RefactoringResponse {
2826
/// The URI of the file where the macro is used
2927
var uri: DocumentURI
3028

31-
/// The resulting array of `MacroExpansionEdit` of a semantic refactoring request
32-
var edits: [MacroExpansionEdit]
29+
/// The resulting array of `RefactoringEdit` of a semantic refactoring request
30+
var edits: [RefactoringEdit]
3331

3432
init(title: String, uri: DocumentURI, refactoringEdits: [RefactoringEdit]) {
3533
self.title = title
3634
self.uri = uri
3735
self.edits = refactoringEdits.compactMap { refactoringEdit in
3836
if refactoringEdit.bufferName.isEmpty {
39-
logger.error("Unable to retrieve some parts of the expansion")
37+
logger.fault("Unable to retrieve some parts of the expansion")
4038
return nil
4139
}
4240

@@ -53,12 +51,9 @@ extension SwiftLanguageService {
5351
/// expansion to be displayed.
5452
///
5553
/// - Parameters:
56-
/// - expandMacroCommand: The `ExpandMacroCommand` that triggered this
57-
/// request.
54+
/// - expandMacroCommand: The `ExpandMacroCommand` that triggered this request.
5855
///
59-
/// - Returns:
60-
/// - an `[MacroExpansionEdit]` with the necessary edits and buffer name as
61-
/// a `LSPAny`
56+
/// - Returns: An `[RefactoringEdit]` with the necessary edits and buffer name as a `LSPAny`
6257
func expandMacro(
6358
_ expandMacroCommand: ExpandMacroCommand
6459
) async throws -> LSPAny {
@@ -69,17 +64,20 @@ extension SwiftLanguageService {
6964
}
7065

7166
guard let sourceFileURL = expandMacroCommand.textDocument.uri.fileURL else {
72-
throw ResponseError.unknown("Given URL is not a file URL")
67+
throw ResponseError.unknown("Given URI is not a file URL")
7368
}
7469

7570
let expansion = try await self.refactoring(expandMacroCommand)
7671

7772
for macroEdit in expansion.edits {
78-
let macroExpansionBufferDirectoryName = macroEdit.bufferName.dropLast(6) // buffer name without ".swift"
79-
80-
let macroExpansionBufferDirectoryURL = self.generatedMacroExpansionsPath.appendingPathComponent(
81-
String(macroExpansionBufferDirectoryName)
82-
)
73+
// buffer name without ".swift"
74+
let macroExpansionBufferDirectoryName =
75+
macroEdit.bufferName.hasSuffix(".swift")
76+
? String(macroEdit.bufferName.dropLast(6))
77+
: macroEdit.bufferName
78+
79+
let macroExpansionBufferDirectoryURL = self.generatedMacroExpansionsPath
80+
.appendingPathComponent(macroExpansionBufferDirectoryName)
8381
do {
8482
try FileManager.default.createDirectory(at: macroExpansionBufferDirectoryURL, withIntermediateDirectories: true)
8583
} catch {
@@ -96,22 +94,20 @@ extension SwiftLanguageService {
9694
"\(macroExpansionFileName)_\(macroExpansionPositionRangeIndicator).\(sourceFileURL.pathExtension)"
9795
)
9896

99-
let macroExpansionDocURI = DocumentURI(macroExpansionFilePath)
100-
10197
do {
102-
try macroEdit.newText.write(to: macroExpansionFilePath, atomically: true, encoding: String.Encoding.utf8)
98+
try macroEdit.newText.write(to: macroExpansionFilePath, atomically: true, encoding: .utf8)
10399
} catch {
104100
throw ResponseError.unknown("Unable to write macro expansion to file path: \"\(macroExpansionFilePath.path)\"")
105101
}
106102

107103
Task {
108-
let req = ShowDocumentRequest(uri: macroExpansionDocURI, selection: macroEdit.range)
104+
let req = ShowDocumentRequest(uri: DocumentURI(macroExpansionFilePath), selection: macroEdit.range)
109105

110106
let response = await orLog("Sending ShowDocumentRequest to Client") {
111107
try await sourceKitLSPServer.sendRequestToClient(req)
112108
}
113109

114-
if !(response?.success ?? true) {
110+
if let response, !response.success {
115111
logger.error("client refused to show document for \(expansion.title, privacy: .public)")
116112
}
117113
}

Sources/SourceKitLSP/Swift/Refactoring.swift

Lines changed: 6 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -29,29 +29,29 @@ extension RefactoringResponse {
2929
/// - keys: The sourcekitd key set to use for looking up into `dict`.
3030
init?(_ title: String, _ dict: SKDResponseDictionary, _ snapshot: DocumentSnapshot, _ keys: sourcekitd_api_keys) {
3131
guard let categorizedEdits: SKDResponseArray = dict[keys.categorizedEdits] else {
32-
logger.error("categorizedEdits doesn't exist in response dictionary")
32+
logger.fault("categorizedEdits doesn't exist in response dictionary")
3333
return nil
3434
}
3535

3636
var refactoringEdits = [RefactoringEdit]()
3737

3838
categorizedEdits.forEach { _, categorizedEdit in
3939
guard let edits: SKDResponseArray = categorizedEdit[keys.edits] else {
40-
logger.error("edits doesn't exist in categorizedEdit dictionary")
40+
logger.fault("edits doesn't exist in categorizedEdit dictionary")
4141
return true
4242
}
4343
edits.forEach { _, edit in
44-
// The LSP is zero based, but semantic_refactoring is one based.
4544
guard let startLine: Int = edit[keys.line],
4645
let startColumn: Int = edit[keys.column],
4746
let endLine: Int = edit[keys.endLine],
4847
let endColumn: Int = edit[keys.endColumn],
4948
let text: String = edit[keys.text]
5049
else {
51-
logger.error("Failed to deserialise edit dictionary containing values: \(edit)")
50+
logger.fault("Failed to deserialise edit dictionary containing values: \(edit)")
5251
return true // continue
5352
}
5453

54+
// The LSP is zero based, but semantic_refactoring is one based.
5555
let startPosition = snapshot.positionOf(
5656
zeroBasedLine: startLine - 1,
5757
utf8Column: startColumn - 1
@@ -77,7 +77,7 @@ extension RefactoringResponse {
7777
}
7878

7979
guard !refactoringEdits.isEmpty else {
80-
logger.error("No refactors found")
80+
logger.error("No refactoring edits found")
8181
return nil
8282
}
8383

@@ -94,8 +94,7 @@ extension SwiftLanguageService {
9494
///
9595
/// - Parameters:
9696
/// - refactorCommand: The semantic `RefactorCommand` that triggered this request.
97-
/// - Returns:
98-
/// - The `RefactoringResponse` as `T`
97+
/// - Returns: The response of the refactoring
9998
func refactoring<T: RefactorCommand>(
10099
_ refactorCommand: T
101100
) async throws -> T.Response {

Sources/SourceKitLSP/Swift/RefactoringEdit.swift

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@
1313
import LanguageServerProtocol
1414
import SourceKitD
1515

16-
/// Represents an edit from semantic refactor response. Notionally, a subclass /// of `TextEdit`
16+
/// Represents an edit from semantic refactor response. Notionally, a subclass of `TextEdit`
1717
@_spi(Testing) public struct RefactoringEdit: Hashable, Sendable, Codable {
1818
/// The range of text to be replaced.
1919
@CustomCodable<PositionRange>
@@ -22,6 +22,10 @@ import SourceKitD
2222
/// The new text.
2323
public var newText: String
2424

25+
/// If the new text of the edit should not be applied to the original source
26+
/// file but to a separate buffer, a fake name for that buffer. For example
27+
/// for expansion of macros, this is @ followed by the mangled name of the
28+
/// macro expansion, followed by .swift.
2529
public var bufferName: String
2630

2731
public init(range: Range<Position>, newText: String, bufferName: String) {

Sources/SourceKitLSP/Swift/SemanticRefactoring.swift

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -70,8 +70,7 @@ extension SwiftLanguageService {
7070
/// - Parameters:
7171
/// - semanticRefactorCommand: The `SemanticRefactorCommand` that triggered this request.
7272
///
73-
/// - Returns:
74-
/// - a `WorkspaceEdit` with the necessary refactors as a `LSPAny`
73+
/// - Returns: A `WorkspaceEdit` with the necessary refactors as a `LSPAny`
7574
func semanticRefactoring(
7675
_ semanticRefactorCommand: SemanticRefactorCommand
7776
) async throws -> LSPAny {

Tests/SourceKitLSPTests/ExecuteCommandTests.swift

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -203,7 +203,7 @@ final class ExecuteCommandTests: XCTestCase {
203203

204204
let request = ExecuteCommandRequest(command: command.command, arguments: command.arguments)
205205

206-
let expectation = XCTestExpectation(description: "Handle Show Document Request")
206+
let expectation = self.expectation(description: "Handle Show Document Request")
207207
let showDocumentRequestURI = ThreadSafeBox<DocumentURI?>(initialValue: nil)
208208

209209
project.testClient.handleSingleRequest { (req: ShowDocumentRequest) in
@@ -214,7 +214,7 @@ final class ExecuteCommandTests: XCTestCase {
214214

215215
let result = try await project.testClient.send(request)
216216

217-
guard let resultArray: [MacroExpansionEdit] = Array(fromLSPArray: result ?? .null) else {
217+
guard let resultArray: [RefactoringEdit] = Array(fromLSPArray: result ?? .null) else {
218218
XCTFail(
219219
"Result is not an array. Failed for position range between \(positionMarker.start) and \(positionMarker.end)"
220220
)
@@ -232,7 +232,7 @@ final class ExecuteCommandTests: XCTestCase {
232232
"Wrong macro expansion. Failed for position range between \(positionMarker.start) and \(positionMarker.end)"
233233
)
234234

235-
await fulfillment(of: [expectation], timeout: 10.0)
235+
try await fulfillmentOfOrThrow([expectation])
236236

237237
let url = try XCTUnwrap(
238238
showDocumentRequestURI.value?.fileURL,

0 commit comments

Comments
 (0)