@@ -327,15 +327,24 @@ extension SwiftLanguageService {
327327
328328 // MARK: - Build System Integration
329329
330- private func reopenDocument( _ snapshot: DocumentSnapshot , _ compileCmd: SwiftCompileCommand ? ) async {
330+ public func reopenDocument( _ notification: ReopenTextDocumentNotification ) async {
331+ let snapshot = orLog ( " Getting snapshot to re-open document " ) {
332+ try documentManager. latestSnapshot ( notification. textDocument. uri)
333+ }
334+ guard let snapshot else {
335+ return
336+ }
331337 cancelInFlightPublishDiagnosticsTask ( for: snapshot. uri)
332338 await diagnosticReportManager. removeItemsFromCache ( with: snapshot. uri)
333339
334340 let closeReq = closeDocumentSourcekitdRequest ( uri: snapshot. uri)
335- _ = try ? await self . sourcekitd. send ( closeReq, fileContents: nil )
341+ _ = await orLog ( " Closing document to re-open it " ) { try await self . sourcekitd. send ( closeReq, fileContents: nil ) }
336342
337- let openReq = openDocumentSourcekitdRequest ( snapshot: snapshot, compileCommand: compileCmd)
338- _ = try ? await self . sourcekitd. send ( openReq, fileContents: snapshot. text)
343+ let openReq = openDocumentSourcekitdRequest (
344+ snapshot: snapshot,
345+ compileCommand: await buildSettings ( for: snapshot. uri)
346+ )
347+ _ = await orLog ( " Re-opening document " ) { try await self . sourcekitd. send ( openReq, fileContents: snapshot. text) }
339348
340349 if await capabilityRegistry. clientSupportsPullDiagnostics ( for: . swift) {
341350 await self . refreshDiagnosticsDebouncer. scheduleCall ( )
@@ -345,14 +354,11 @@ extension SwiftLanguageService {
345354 }
346355
347356 public func documentUpdatedBuildSettings( _ uri: DocumentURI ) async {
348- // We may not have a snapshot if this is called just before `openDocument`.
349- guard let snapshot = try ? self . documentManager. latestSnapshot ( uri) else {
350- return
351- }
352-
353- // Close and re-open the document internally to inform sourcekitd to update the compile
354- // command. At the moment there's no better way to do this.
355- await self . reopenDocument ( snapshot, await self . buildSettings ( for: uri) )
357+ // Close and re-open the document internally to inform sourcekitd to update the compile command. At the moment
358+ // there's no better way to do this.
359+ // Schedule the document re-open in the SourceKit-LSP server. This ensures that the re-open happens exclusively with
360+ // no other request running at the same time.
361+ sourceKitLSPServer? . handle ( ReopenTextDocumentNotification ( textDocument: TextDocumentIdentifier ( uri) ) )
356362 }
357363
358364 public func documentDependenciesUpdated( _ uri: DocumentURI ) async {
0 commit comments