forked from CodeEditApp/CodeEdit
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathLSPService.swift
More file actions
320 lines (298 loc) · 12.3 KB
/
LSPService.swift
File metadata and controls
320 lines (298 loc) · 12.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
//
// LSPService.swift
// CodeEdit
//
// Created by Abe Malla on 2/7/24.
//
import os.log
import JSONRPC
import Foundation
import LanguageClient
import LanguageServerProtocol
import CodeEditLanguages
/// `LSPService` is a service class responsible for managing the lifecycle and event handling
/// of Language Server Protocol (LSP) clients within the CodeEdit application. It handles the initialization,
/// communication, and termination of language servers, ensuring that code assistance features
/// such as code completion, diagnostics, and more are available for various programming languages.
///
/// This class uses Swift's concurrency model to manage background tasks and event streams
/// efficiently. Each language server runs in its own asynchronous task, listening for events and
/// handling them as they occur. The `LSPService` class also provides functionality to start
/// and stop individual language servers, as well as to stop all running servers.
///
/// ## Example Usage
///
/// ```swift
/// @Service var lspService
///
/// try await lspService.startServer(
/// for: .python,
/// projectURL: projectURL,
/// workspaceFolders: workspaceFolders
/// )
/// try await lspService.stopServer(for: .python)
/// ```
///
/// ## Completion Example
///
/// ```swift
/// func testCompletion() async throws {
/// do {
/// guard var languageClient = self.languageClient(for: .python) else {
/// print("Failed to get client")
/// throw ServerManagerError.languageClientNotFound
/// }
///
/// let testFilePathStr = ""
/// let testFileURL = URL(fileURLWithPath: testFilePathStr)
///
/// // Tell server we opened a document
/// _ = await languageClient.addDocument(testFileURL)
///
/// // Completion example
/// let textPosition = Position(line: 32, character: 18) // Lines and characters start at 0
/// let completions = try await languageClient.requestCompletion(
/// document: testFileURL.absoluteString,
/// position: textPosition
/// )
/// switch completions {
/// case .optionA(let completionItems):
/// // Handle the case where completions is an array of CompletionItem
/// print("\n*******\nCompletion Items:\n*******\n")
/// for item in completionItems {
/// let textEdits = LSPCompletionItemsUtil.getCompletionItemEdits(
/// startPosition: textPosition,
/// item: item
/// )
/// for edit in textEdits {
/// print(edit)
/// }
/// }
///
/// case .optionB(let completionList):
/// // Handle the case where completions is a CompletionList
/// print("\n*******\nCompletion Items:\n*******\n")
/// for item in completionList.items {
/// let textEdits = LSPCompletionItemsUtil.getCompletionItemEdits(
/// startPosition: textPosition,
/// item: item
/// )
/// for edit in textEdits {
/// print(edit)
/// }
/// }
///
/// print(completionList.items[0])
///
/// case .none:
/// print("No completions found")
/// }
///
/// // Close the document
/// _ = await languageClient.closeDocument(testFilePathStr)
/// } catch {
/// print(error)
/// }
/// }
/// ```
@MainActor
final class LSPService: ObservableObject {
let logger: Logger = Logger(subsystem: Bundle.main.bundleIdentifier ?? "", category: "LSPService")
struct ClientKey: Hashable, Equatable {
let languageId: LanguageIdentifier
let workspacePath: String
init(_ languageId: LanguageIdentifier, _ workspacePath: String) {
self.languageId = languageId
self.workspacePath = workspacePath
}
}
/// Holds the active language clients
var languageClients: [ClientKey: LanguageServer] = [:]
/// Holds the language server configurations for all the installed language servers
var languageConfigs: [LanguageIdentifier: LanguageServerBinary] = [:]
/// Holds all the event listeners for each active language client
var eventListeningTasks: [ClientKey: Task<Void, Never>] = [:]
@AppSettings(\.developerSettings.lspBinaries)
var lspBinaries
init() {
// Load the LSP binaries from the developer menu
for binary in lspBinaries {
if let language = LanguageIdentifier(rawValue: binary.key) {
self.languageConfigs[language] = LanguageServerBinary(
execPath: binary.value,
args: [],
env: ProcessInfo.processInfo.environment
)
}
}
NotificationCenter.default.addObserver(
forName: CodeFileDocument.didOpenNotification,
object: nil,
queue: .main
) { notification in
MainActor.assumeIsolated {
guard let document = notification.object as? CodeFileDocument else { return }
self.openDocument(document)
}
}
NotificationCenter.default.addObserver(
forName: CodeFileDocument.didCloseNotification,
object: nil,
queue: .main
) { notification in
MainActor.assumeIsolated {
guard let url = notification.object as? URL else { return }
self.closeDocument(url)
}
}
}
/// Gets the language server for the specified language and workspace.
func server(for languageId: LanguageIdentifier, workspacePath: String) -> InitializingServer? {
return languageClients[ClientKey(languageId, workspacePath)]?.lspInstance
}
/// Gets the language client for the specified language
func languageClient(for languageId: LanguageIdentifier, workspacePath: String) -> LanguageServer? {
return languageClients[ClientKey(languageId, workspacePath)]
}
/// Given a language and workspace path, will attempt to start the language server
/// - Parameters:
/// - languageId: The ID of the language server to start.
/// - workspacePath: The workspace this language server is being used in.
/// - Returns: The new language server.
func startServer(
for languageId: LanguageIdentifier,
workspacePath: String
) async throws -> LanguageServer {
guard let serverBinary = languageConfigs[languageId] else {
logger.error("Couldn't find language sever binary for \(languageId.rawValue)")
throw LSPError.binaryNotFound
}
logger.info("Starting \(languageId.rawValue) language server")
let server = try await LanguageServer.createServer(
for: languageId,
with: serverBinary,
workspacePath: workspacePath
)
languageClients[ClientKey(languageId, workspacePath)] = server
logger.info("Successfully started \(languageId.rawValue) language server")
self.startListeningToEvents(for: ClientKey(languageId, workspacePath))
return server
}
/// Notify all relevant language clients that a document was opened.
/// - Note: Must be invoked after the contents of the file are available.
/// - Parameter document: The code document that was opened.
func openDocument(_ document: CodeFileDocument) {
guard let workspace = document.findWorkspace(),
let workspacePath = workspace.fileURL?.absoluteURL.path(),
let lspLanguage = document.getLanguage().lspLanguage else {
return
}
Task {
let languageServer: LanguageServer
do {
if let server = self.languageClients[ClientKey(lspLanguage, workspacePath)] {
languageServer = server
} else {
languageServer = try await self.startServer(for: lspLanguage, workspacePath: workspacePath)
}
} catch {
// swiftlint:disable:next line_length
self.logger.error("Failed to find/start server for language: \(lspLanguage.rawValue), workspace: \(workspacePath, privacy: .private)")
return
}
do {
try await languageServer.openDocument(document)
} catch {
let uri = document.languageServerURI
// swiftlint:disable:next line_length
self.logger.error("Failed to close document: \(uri ?? "<NO URI>", privacy: .private), language: \(lspLanguage.rawValue). Error \(error)")
}
}
}
/// Notify all relevant language clients that a document was closed.
/// - Parameter url: The url of the document that was closed
func closeDocument(_ url: URL) {
guard let languageClient = languageClients.first(where: {
$0.value.openFiles.document(for: url.absolutePath) != nil
})?.value else {
return
}
Task {
do {
try await languageClient.closeDocument(url.absolutePath)
} catch {
// swiftlint:disable:next line_length
logger.error("Failed to close document: \(url.absolutePath, privacy: .private), language: \(languageClient.languageId.rawValue). Error \(error)")
}
}
}
/// Close all language clients for a workspace.
///
/// This is intentionally synchronous so we can exit from the workspace document's ``WorkspaceDocument/close()``
/// method ASAP.
///
/// Errors thrown in this method are logged and otherwise not handled.
/// - Parameter workspacePath: The path of the workspace.
func closeWorkspace(_ workspacePath: String) {
Task {
let clientKeys = self.languageClients.filter({ $0.key.workspacePath == workspacePath })
for (key, languageClient) in clientKeys {
do {
try await languageClient.shutdown()
} catch {
logger.error("Failed to shutdown \(key.languageId.rawValue) Language Server: Error \(error)")
}
}
for (key, _) in clientKeys {
self.languageClients.removeValue(forKey: key)
}
}
}
/// Attempts to stop a running language server. Throws an error if the server is not found
/// or if the language server throws an error while trying to shutdown.
/// - Parameters:
/// - languageId: The ID of the language server to stop.
/// - workspacePath: The path of the workspace to stop the language server for.
func stopServer(forLanguage languageId: LanguageIdentifier, workspacePath: String) async throws {
guard let server = server(for: languageId, workspacePath: workspacePath) else {
logger.error("Server not found for language \(languageId.rawValue) during stop operation")
throw ServerManagerError.serverNotFound
}
do {
try await server.shutdownAndExit()
} catch {
logger.error("Failed to stop server for language \(languageId.rawValue): \(error.localizedDescription)")
throw error
}
languageClients.removeValue(forKey: ClientKey(languageId, workspacePath))
logger.info("Server stopped for language \(languageId.rawValue)")
stopListeningToEvents(for: ClientKey(languageId, workspacePath))
}
/// Goes through all active language servers and attempts to shut them down.
func stopAllServers() async {
await withThrowingTaskGroup(of: Void.self) { group in
for (key, server) in languageClients {
group.addTask {
do {
try await server.shutdown()
} catch {
self.logger.error("Shutting down \(key.languageId.rawValue): Error \(error)")
throw error
}
}
}
}
languageClients.removeAll()
eventListeningTasks.forEach { (_, value) in
value.cancel()
}
eventListeningTasks.removeAll()
}
}
// MARK: - Errors
enum ServerManagerError: Error {
case serverNotFound
case serverStartFailed
case serverStopFailed
case languageClientNotFound
}