Skip to content

Dynamically register completion options for supporting clients #380

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

Merged
merged 4 commits into from
Apr 6, 2021
Merged
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
Original file line number Diff line number Diff line change
Expand Up @@ -27,15 +27,15 @@ public struct RegisterCapabilityRequest: RequestType, Hashable {
public typealias Response = VoidResponse

/// Capability registrations.
public var registrations: [Registration]
public var registrations: [CapabilityRegistration]

public init(registrations: [Registration]) {
public init(registrations: [CapabilityRegistration]) {
self.registrations = registrations
}
}

/// General parameters to register a capability.
public struct Registration: Codable, Hashable {
public struct CapabilityRegistration: Codable, Hashable {
/// The id used to register the capability which may be used to unregister support.
public var id: String

Expand All @@ -51,8 +51,8 @@ public struct Registration: Codable, Hashable {
self.registerOptions = registerOptions
}

/// Create a new `Registration` with a randomly generated id. Save the generated
/// id if you wish to unregister the given registration.
/// Create a new `CapabilityRegistration` with a randomly generated id. Save
/// the generated id if you wish to unregister the given registration.
public init(method: String, registerOptions: LSPAny?) {
self.id = UUID().uuidString
self.method = method
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,12 +12,23 @@

import Foundation

/// An event describing a file change.
public protocol RegistrationOptions: Codable, LSPAnyCodable, Hashable {
/// Protocol for capability registration options, which must be encodable to
/// `LSPAny` so they can be included in a `Registration`.
public protocol RegistrationOptions: Hashable {
func encodeIntoLSPAny(dict: inout [String: LSPAny])
}

fileprivate func encode(strings: [String]) -> LSPAny {
var values = [LSPAny]()
values.reserveCapacity(strings.count)
for str in strings {
values.append(.string(str))
}
return .array(values)
}

/// General text document registration options.
public struct TextDocumentRegistrationOptions: RegistrationOptions {
public struct TextDocumentRegistrationOptions: RegistrationOptions, Hashable {
/// A document selector to identify the scope of the registration. If not set,
/// the document selector provided on the client side will be used.
public var documentSelector: DocumentSelector?
Expand All @@ -26,21 +37,40 @@ public struct TextDocumentRegistrationOptions: RegistrationOptions {
self.documentSelector = documentSelector
}

public init?(fromLSPDictionary dictionary: [String : LSPAny]) {
guard let selectorValue = dictionary[CodingKeys.documentSelector.stringValue] else {
self.documentSelector = nil
return
}
guard case .dictionary(let selectorDictionary) = selectorValue else { return nil }
guard let documentSelector = DocumentSelector(fromLSPDictionary: selectorDictionary) else {
return nil
}
self.documentSelector = documentSelector
public func encodeIntoLSPAny(dict: inout [String: LSPAny]) {
guard let documentSelector = documentSelector else { return }
dict["documentSelector"] = documentSelector.encodeToLSPAny()
}
}

/// Protocol for a type which structurally represents`TextDocumentRegistrationOptions`.
public protocol TextDocumentRegistrationOptionsProtocol {
var textDocumentRegistrationOptions: TextDocumentRegistrationOptions {get}
}

/// Code completiion registration options.
public struct CompletionRegistrationOptions: RegistrationOptions, TextDocumentRegistrationOptionsProtocol, Hashable {
public var textDocumentRegistrationOptions: TextDocumentRegistrationOptions
public var completionOptions: CompletionOptions

public init(documentSelector: DocumentSelector? = nil, completionOptions: CompletionOptions) {
self.textDocumentRegistrationOptions =
TextDocumentRegistrationOptions(documentSelector: documentSelector)
self.completionOptions = completionOptions
}

public func encodeToLSPAny() -> LSPAny {
guard let documentSelector = documentSelector else { return .dictionary([:]) }
return .dictionary([CodingKeys.documentSelector.stringValue: documentSelector.encodeToLSPAny()])
public func encodeIntoLSPAny(dict: inout [String: LSPAny]) {
textDocumentRegistrationOptions.encodeIntoLSPAny(dict: &dict)

if let resolveProvider = completionOptions.resolveProvider {
dict["resolveProvider"] = .bool(resolveProvider)
}
if let triggerCharacters = completionOptions.triggerCharacters {
dict["triggerCharacters"] = encode(strings: triggerCharacters)
}
if let allCommitCharacters = completionOptions.allCommitCharacters {
dict["allCommitCharacters"] = encode(strings: allCommitCharacters)
}
}
}

Expand All @@ -53,14 +83,8 @@ public struct DidChangeWatchedFilesRegistrationOptions: RegistrationOptions {
self.watchers = watchers
}

public init?(fromLSPDictionary dictionary: [String : LSPAny]) {
guard let watchersLSPAny = dictionary[CodingKeys.watchers.stringValue] else { return nil }
guard let watchers = [FileSystemWatcher].init(fromLSPArray: watchersLSPAny) else { return nil }
self.watchers = watchers
}

public func encodeToLSPAny() -> LSPAny {
return .dictionary([CodingKeys.watchers.stringValue: watchers.encodeToLSPAny()])
public func encodeIntoLSPAny(dict: inout [String: LSPAny]) {
dict["watchers"] = watchers.encodeToLSPAny()
}
}

Expand All @@ -73,25 +97,7 @@ public struct ExecuteCommandRegistrationOptions: RegistrationOptions {
self.commands = commands
}

public init?(fromLSPDictionary dictionary: [String : LSPAny]) {
guard case .array(let commandsArray) = dictionary[CodingKeys.commands.stringValue] else {
return nil
}
var values = [String]()
values.reserveCapacity(commandsArray.count)
for lspAny in commandsArray {
guard case .string(let value) = lspAny else { return nil }
values.append(value)
}
self.commands = values
}

public func encodeToLSPAny() -> LSPAny {
var values = [LSPAny]()
values.reserveCapacity(commands.count)
for command in commands {
values.append(.string(command))
}
return .dictionary([CodingKeys.commands.stringValue: .array(values)])
public func encodeIntoLSPAny(dict: inout [String: LSPAny]) {
dict["commands"] = encode(strings: commands)
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -243,16 +243,23 @@ public enum TextDocumentSyncKind: Int, Codable, Hashable {
}

public struct CompletionOptions: Codable, Hashable {

/// Whether to use `textDocument/resolveCompletion`
public var resolveProvider: Bool?

/// The characters that should trigger automatic completion.
public var triggerCharacters: [String]
public var triggerCharacters: [String]?

public init(resolveProvider: Bool? = false, triggerCharacters: [String]) {
/// The list of all possible characters that commit a completion.
public var allCommitCharacters: [String]?

public init(
resolveProvider: Bool? = false,
triggerCharacters: [String]? = nil,
allCommitCharacters: [String]? = nil
) {
self.resolveProvider = resolveProvider
self.triggerCharacters = triggerCharacters
self.allCommitCharacters = allCommitCharacters
}
}

Expand Down
2 changes: 1 addition & 1 deletion Sources/SKTestSupport/SKSwiftPMTestWorkspace.swift
Original file line number Diff line number Diff line change
Expand Up @@ -90,7 +90,7 @@ public final class SKSwiftPMTestWorkspace {
let server = testServer.server!
server.workspace = Workspace(
rootUri: DocumentURI(sources.rootDirectory),
clientCapabilities: ClientCapabilities(),
capabilityRegistry: CapabilityRegistry(clientCapabilities: ClientCapabilities()),
toolchainRegistry: ToolchainRegistry.shared,
buildSetup: buildSetup,
underlyingBuildSystem: swiftpm,
Expand Down
2 changes: 1 addition & 1 deletion Sources/SKTestSupport/SKTibsTestWorkspace.swift
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,7 @@ public final class SKTibsTestWorkspace {

testServer.server!.workspace = Workspace(
rootUri: DocumentURI(sources.rootDirectory),
clientCapabilities: clientCapabilities,
capabilityRegistry: CapabilityRegistry(clientCapabilities: clientCapabilities),
toolchainRegistry: ToolchainRegistry.shared,
buildSetup: BuildSetup(configuration: .debug, path: buildPath, flags: BuildFlags()),
underlyingBuildSystem: buildSystem,
Expand Down
1 change: 1 addition & 0 deletions Sources/SourceKitLSP/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ if(CMAKE_VERSION VERSION_LESS 3.16)
endif()

add_library(SourceKitLSP
CapabilityRegistry.swift
DocumentManager.swift
IndexStoreDB+MainFilesProvider.swift
SourceKitIndexDelegate.swift
Expand Down
103 changes: 103 additions & 0 deletions Sources/SourceKitLSP/CapabilityRegistry.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,103 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2021 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 LanguageServerProtocol

/// Handler responsible for registering a capability with the client.
public typealias ClientRegistrationHandler = (CapabilityRegistration) -> Void

/// A class which tracks the client's capabilities as well as our dynamic
/// capability registrations in order to avoid registering conflicting
/// capabilities.
public final class CapabilityRegistry {
/// Registered completion options.
private var completion: [CapabilityRegistration: CompletionRegistrationOptions] = [:]

public let clientCapabilities: ClientCapabilities

public init(clientCapabilities: ClientCapabilities) {
self.clientCapabilities = clientCapabilities
}

public var clientHasDynamicCompletionRegistration: Bool {
clientCapabilities.textDocument?.completion?.dynamicRegistration == true
}

/// Dynamically register completion capabilities if the client supports it and
/// we haven't yet registered any completion capabilities for the given
/// languages.
public func registerCompletionIfNeeded(
options: CompletionOptions,
for languages: [Language],
registerOnClient: ClientRegistrationHandler
) {
guard clientHasDynamicCompletionRegistration && !hasCompletionRegistrations(for: languages) else {
return
}
let registrationOptions = CompletionRegistrationOptions(
documentSelector: self.documentSelector(for: languages),
completionOptions: options)
let registration = CapabilityRegistration(
method: CompletionRequest.method,
registerOptions: self.encode(registrationOptions))

self.completion[registration] = registrationOptions

registerOnClient(registration)
}

/// Unregister a previously registered registration, e.g. if no longer needed
/// or if registration fails.
public func remove(registration: CapabilityRegistration) {
if registration.method == CompletionRequest.method {
completion.removeValue(forKey: registration)
}
}

private func hasCompletionRegistrations(for languages: [Language]) -> Bool {
return self.hasAnyRegistrations(for: languages, in: self.completion)
}

private func documentSelector(for langauges: [Language]) -> DocumentSelector {
return DocumentSelector(langauges.map { DocumentFilter(language: $0.rawValue) })
}

private func encode<T: RegistrationOptions>(_ options: T) -> LSPAny {
var dict = [String: LSPAny]()
options.encodeIntoLSPAny(dict: &dict)
return .dictionary(dict)
}

/// Check if we have any text document registration in `registrations` scoped to
/// one or more of the given `languages`.
private func hasAnyRegistrations(
for languages: [Language],
in registrations: [CapabilityRegistration: TextDocumentRegistrationOptionsProtocol]
) -> Bool {
var languageIds: Set<String> = []
for language in languages {
languageIds.insert(language.rawValue)
}

for registration in registrations {
let options = registration.value.textDocumentRegistrationOptions
guard let filters = options.documentSelector else { continue }
for filter in filters {
guard let filterLanguage = filter.language else { continue }
if languageIds.contains(filterLanguage) {
return true
}
}
}
return false
}
}
Loading