Skip to content

[DocC Live Preview] Cache on-disk snapshots opened in sourcekitd #2226

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 3 additions & 3 deletions Sources/DocCDocumentation/IndexStoreDB+Extensions.swift
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ extension CheckedIndex {
var result: [SymbolOccurrence] = []
for occurrence in topLevelSymbolOccurrences {
let info = try await doccSymbolInformation(ofUSR: occurrence.symbol.usr, fetchSymbolGraph: fetchSymbolGraph)
if let info, info.matches(symbolLink) {
if info.matches(symbolLink) {
result.append(occurrence)
}
}
Expand All @@ -60,9 +60,9 @@ extension CheckedIndex {
package func doccSymbolInformation(
ofUSR usr: String,
fetchSymbolGraph: (SymbolLocation) async throws -> String?
) async throws -> DocCSymbolInformation? {
) async throws -> DocCSymbolInformation {
guard let topLevelSymbolOccurrence = primaryDefinitionOrDeclarationOccurrence(ofUSR: usr) else {
return nil
throw DocCCheckedIndexError.emptyDocCSymbolLink
}
let moduleName = topLevelSymbolOccurrence.location.moduleName
var symbols = [topLevelSymbolOccurrence]
Expand Down
2 changes: 1 addition & 1 deletion Sources/SourceKitLSP/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,7 @@ target_sources(SourceKitLSP PRIVATE
Swift/SwiftCommand.swift
Swift/SwiftLanguageService.swift
Swift/SwiftTestingScanner.swift
Swift/SymbolGraphCache.swift
Swift/SymbolInfo.swift
Swift/SyntacticSwiftXCTestScanner.swift
Swift/SyntacticTestIndex.swift
Expand All @@ -76,7 +77,6 @@ target_sources(SourceKitLSP PRIVATE
Swift/SyntaxHighlightingTokens.swift
Swift/SyntaxTreeManager.swift
Swift/VariableTypeInfo.swift
Swift/WithSnapshotFromDiskOpenedInSourcekitd.swift
)
set_target_properties(SourceKitLSP PROPERTIES
INTERFACE_INCLUDE_DIRECTORIES ${CMAKE_Swift_MODULE_DIRECTORY})
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -58,53 +58,16 @@ extension DocumentationLanguageService {
guard let index = workspace.index(checkedFor: .deletedFiles) else {
throw ResponseError.requestFailed(doccDocumentationError: .indexNotAvailable)
}
let symbolGraphCache = SymbolGraphCache(sourceKitLSPServer: sourceKitLSPServer)
guard let symbolLink = DocCSymbolLink(linkString: symbolName),
let symbolOccurrence = try await index.primaryDefinitionOrDeclarationOccurrence(
ofDocCSymbolLink: symbolLink,
fetchSymbolGraph: { location in
guard let symbolWorkspace = try await workspaceForDocument(uri: location.documentUri),
let languageService = try await languageService(for: location.documentUri, .swift, in: symbolWorkspace)
as? SwiftLanguageService
else {
throw ResponseError.internalError("Unable to find Swift language service for \(location.documentUri)")
}
return try await languageService.withSnapshotFromDiskOpenedInSourcekitd(
uri: location.documentUri,
fallbackSettingsAfterTimeout: false
) { (snapshot, compileCommand) in
let (_, _, symbolGraph) = try await languageService.cursorInfo(
snapshot,
compileCommand: compileCommand,
Range(snapshot.position(of: location)),
includeSymbolGraph: true
)
return symbolGraph
}
}
fetchSymbolGraph: symbolGraphCache.fetchSymbolGraph(at:)
)
else {
throw ResponseError.requestFailed(doccDocumentationError: .symbolNotFound(symbolName))
}
let symbolDocumentUri = symbolOccurrence.location.documentUri
guard
let symbolWorkspace = try await workspaceForDocument(uri: symbolDocumentUri),
let languageService = try await languageService(for: symbolDocumentUri, .swift, in: symbolWorkspace)
as? SwiftLanguageService
else {
throw ResponseError.internalError("Unable to find Swift language service for \(symbolDocumentUri)")
}
let symbolGraph = try await languageService.withSnapshotFromDiskOpenedInSourcekitd(
uri: symbolDocumentUri,
fallbackSettingsAfterTimeout: false
) { snapshot, compileCommand in
try await languageService.cursorInfo(
snapshot,
compileCommand: compileCommand,
Range(snapshot.position(of: symbolOccurrence.location)),
includeSymbolGraph: true
).symbolGraph
}
guard let symbolGraph else {
guard let symbolGraph = try await symbolGraphCache.fetchSymbolGraph(at: symbolOccurrence.location) else {
throw ResponseError.internalError("Unable to retrieve symbol graph for \(symbolOccurrence.symbol.name)")
}
return try await documentationManager.renderDocCDocumentation(
Expand Down
29 changes: 9 additions & 20 deletions Sources/SourceKitLSP/Swift/DoccDocumentation.swift
Original file line number Diff line number Diff line change
Expand Up @@ -70,25 +70,13 @@ extension SwiftLanguageService {
}
// Locate the documentation extension and include it in the request if one exists
let markupExtensionFile = await orLog("Finding markup extension file for symbol \(symbolUSR)") {
try await findMarkupExtensionFile(
let symbolGraphCache = SymbolGraphCache(sourceKitLSPServer: sourceKitLSPServer)
return try await findMarkupExtensionFile(
workspace: workspace,
documentationManager: documentationManager,
catalogURL: catalogURL,
for: symbolUSR,
fetchSymbolGraph: { symbolLocation in
try await withSnapshotFromDiskOpenedInSourcekitd(
uri: symbolLocation.documentUri,
fallbackSettingsAfterTimeout: false
) { (snapshot, compileCommand) in
let (_, _, symbolGraph) = try await self.cursorInfo(
snapshot,
compileCommand: compileCommand,
Range(snapshot.position(of: symbolLocation)),
includeSymbolGraph: true
)
return symbolGraph
}
}
fetchSymbolGraph: symbolGraphCache.fetchSymbolGraph(at:)
)
}
return try await documentationManager.renderDocCDocumentation(
Expand All @@ -113,11 +101,12 @@ extension SwiftLanguageService {
}
let catalogIndex = try await documentationManager.catalogIndex(for: catalogURL)
guard let index = workspace.index(checkedFor: .deletedFiles),
let symbolInformation = try await index.doccSymbolInformation(
ofUSR: symbolUSR,
fetchSymbolGraph: fetchSymbolGraph
),
let markupExtensionFileURL = catalogIndex.documentationExtension(for: symbolInformation)
let markupExtensionFileURL = try await catalogIndex.documentationExtension(
for: index.doccSymbolInformation(
ofUSR: symbolUSR,
fetchSymbolGraph: fetchSymbolGraph
)
)
else {
return nil
}
Expand Down
134 changes: 134 additions & 0 deletions Sources/SourceKitLSP/Swift/SymbolGraphCache.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,134 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2025 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//

import BuildSystemIntegration
import Foundation
import IndexStoreDB
import LanguageServerProtocol
import SKLogging
import SKUtilities
import SwiftExtensions

/// A cache of symbol graphs and their associated snapshots opened in sourcekitd. Any opened documents will be
/// closed when the cache is de-initialized.
///
/// Used by `textDocument/doccDocumentation` requests to retrieve symbol graphs for files that are not currently
/// open in the editor. This allows for retrieving multiple symbol graphs from the same file without having
/// to re-open and parse the syntax tree every time.
actor SymbolGraphCache: Sendable {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Would something like OnDiskDocumentManager be a more appropriate name because this type neither really caches values (it manages document lifetimes), nor does it really cache symbol graphs but it keeps track of sourcekitd documents.

private weak var sourceKitLSPServer: SourceKitLSPServer?
private var openSnapshots: [DocumentURI: (snapshot: DocumentSnapshot, patchedCompileCommand: SwiftCompileCommand?)]

init(sourceKitLSPServer: SourceKitLSPServer) {
self.sourceKitLSPServer = sourceKitLSPServer
self.openSnapshots = [:]
}

/// Open a unique dummy document in sourcekitd that has the contents of the file on disk for uri, but an arbitrary
/// URI which doesn't exist on disk. Return the symbol graph from sourcekitd.
///
/// The document will be retained until ``DocCSymbolGraphCache`` is de-initialized. This will avoid parsing the same
/// document multiple times if more than one symbol needs to be looked up.
///
/// - Parameter symbolLocation: The location of a symbol to find the symbol graph for.
/// - Returns: The symbol graph for this location, if any.
func fetchSymbolGraph(at symbolLocation: SymbolLocation) async throws -> String? {
let swiftLanguageService = try await swiftLanguageService(for: symbolLocation.documentUri)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think we’re never re-using an open document, are we? I don’t even think that we ever register open documents.

let (snapshot, patchedCompileCommand) = try await swiftLanguageService.openSnapshotFromDiskOpenedInSourcekitd(
uri: symbolLocation.documentUri,
fallbackSettingsAfterTimeout: false
)
return try await swiftLanguageService.cursorInfo(
snapshot,
compileCommand: patchedCompileCommand,
Range(snapshot.position(of: symbolLocation)),
includeSymbolGraph: true
).symbolGraph
}

private func swiftLanguageService(for uri: DocumentURI) async throws -> SwiftLanguageService {
guard let sourceKitLSPServer else {
throw ResponseError.internalError("SourceKit-LSP is shutting down")
}
guard let workspace = await sourceKitLSPServer.workspaceForDocument(uri: uri),
let languageService = await sourceKitLSPServer.languageService(for: uri, .swift, in: workspace),
let swiftLanguageService = languageService as? SwiftLanguageService
else {
throw ResponseError.internalError("Unable to find SwiftLanguageService for \(uri)")
}
return swiftLanguageService
}

deinit {
guard let sourceKitLSPServer else {
return
}

let documentsToClose = openSnapshots.values
Task {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Launching a task here means that the documents could be closed in parallel while another request is handled, which would be very hard to debug if this ends up creating some kind of data races in sourcekitd. I think I’d prefer a pattern where you have something like the following and then explicitly close the documents at end of the cache’s lifetime.

func withSymbolGraphCache<T>(_ body: (SymbolGraphCache) async throws -> T) async throws -> T

I recently wrote the following for another project, which might be helpful for such a with* implementation (or generally something that I think might be useful to have in SwiftExtensions).

/// Run `body` and always ensure that `cleanup` gets run, independently of whether `body` threw an error or returned a
/// value.
package func run<T>(
  _ body: () async throws -> T,
  cleanup: () async -> ()
) async throws -> T {
  do {
    let result = try await body()
    await cleanup()
    return result
  } catch {
    await cleanup()
    throw error
  }
}

for (snapshot, _) in documentsToClose {
guard let workspace = await sourceKitLSPServer.workspaceForDocument(uri: snapshot.uri),
let languageService = await sourceKitLSPServer.languageService(for: snapshot.uri, .swift, in: workspace),
let swiftLanguageService = languageService as? SwiftLanguageService
else {
logger.log("Unable to find SwiftLanguageService to close helper document \(snapshot.uri.forLogging)")
return
}
await swiftLanguageService.closeSnapshotFromDiskOpenedInSourcekitd(snapshot: snapshot)
}
}
}
}

fileprivate extension SwiftLanguageService {
func openSnapshotFromDiskOpenedInSourcekitd(
uri: DocumentURI,
fallbackSettingsAfterTimeout: Bool,
) async throws -> (snapshot: DocumentSnapshot, patchedCompileCommand: SwiftCompileCommand?) {
guard let fileURL = uri.fileURL else {
throw ResponseError.unknown("Cannot create snapshot with on-disk contents for non-file URI \(uri.forLogging)")
}
let snapshot = DocumentSnapshot(
uri: try DocumentURI(filePath: "\(UUID().uuidString)/\(fileURL.filePath)", isDirectory: false),
language: .swift,
version: 0,
lineTable: LineTable(try String(contentsOf: fileURL, encoding: .utf8))
)
let patchedCompileCommand: SwiftCompileCommand? =
if let buildSettings = await self.buildSettings(
for: uri,
fallbackAfterTimeout: fallbackSettingsAfterTimeout
) {
SwiftCompileCommand(buildSettings.patching(newFile: snapshot.uri, originalFile: uri))
} else {
nil
}

_ = try await send(
sourcekitdRequest: \.editorOpen,
self.openDocumentSourcekitdRequest(snapshot: snapshot, compileCommand: patchedCompileCommand),
snapshot: snapshot
)

return (snapshot, patchedCompileCommand)
}

func closeSnapshotFromDiskOpenedInSourcekitd(snapshot: DocumentSnapshot) async {
await orLog("Close helper document '\(snapshot.uri)'") {
_ = try await send(
sourcekitdRequest: \.editorClose,
self.closeDocumentSourcekitdRequest(uri: snapshot.uri),
snapshot: snapshot
)
}
}
}

This file was deleted.