forked from swiftlang/sourcekit-lsp
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSourceKitLSPServer.swift
2428 lines (2200 loc) · 97.2 KB
/
SourceKitLSPServer.swift
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
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2020 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 BuildServerProtocol
import CAtomics
import Dispatch
import Foundation
import IndexStoreDB
import LSPLogging
import LanguageServerProtocol
import PackageLoading
import SKCore
import SKSupport
import SKSwiftPMWorkspace
import SemanticIndex
import SourceKitD
import struct PackageModel.BuildFlags
import struct TSCBasic.AbsolutePath
import protocol TSCBasic.FileSystem
import var TSCBasic.localFileSystem
public typealias URL = Foundation.URL
/// Disambiguate LanguageServerProtocol.Language and IndexstoreDB.Language
public typealias Language = LanguageServerProtocol.Language
/// A request and a callback that returns the request's reply
fileprivate final class RequestAndReply<Params: RequestType>: Sendable {
let params: Params
private let replyBlock: @Sendable (LSPResult<Params.Response>) -> Void
/// Whether a reply has been made. Every request must reply exactly once.
/// `nonisolated(unsafe)` is fine because `replied` is atomic.
private nonisolated(unsafe) var replied: AtomicBool = AtomicBool(initialValue: false)
public init(_ request: Params, reply: @escaping @Sendable (LSPResult<Params.Response>) -> Void) {
self.params = request
self.replyBlock = reply
}
deinit {
precondition(replied.value, "request never received a reply")
}
/// Call the `replyBlock` with the result produced by the given closure.
func reply(_ body: @Sendable () async throws -> Params.Response) async {
precondition(!replied.value, "replied to request more than once")
replied.value = true
do {
replyBlock(.success(try await body()))
} catch {
replyBlock(.failure(ResponseError(error)))
}
}
}
/// The SourceKit-LSP server.
///
/// This is the client-facing language server implementation, providing indexing, multiple-toolchain
/// and cross-language support. Requests may be dispatched to language-specific services or handled
/// centrally, but this is transparent to the client.
public actor SourceKitLSPServer {
/// The queue on which all messages (notifications, requests, responses) are
/// handled.
///
/// The queue is blocked until the message has been sufficiently handled to
/// avoid out-of-order handling of messages. For sourcekitd, this means that
/// a request has been sent to sourcekitd and for clangd, this means that we
/// have forwarded the request to clangd.
///
/// The actual semantic handling of the message happens off this queue.
private let messageHandlingQueue = AsyncQueue<MessageHandlingDependencyTracker>()
/// The queue on which we start and stop keeping track of cancellation.
///
/// Having a queue for this ensures that we started keeping track of a
/// request's task before handling any cancellation request for it.
private let cancellationMessageHandlingQueue = AsyncQueue<Serial>()
/// The queue on which all modifications of `uriToWorkspaceCache` happen. This means that the value of
/// `workspacesAndIsImplicit` and `uriToWorkspaceCache` can't change while executing a closure on `workspaceQueue`.
private let workspaceQueue = AsyncQueue<Serial>()
/// The connection to the editor.
public let client: Connection
/// Set to `true` after the `SourceKitLSPServer` has send the reply to the `InitializeRequest`.
///
/// Initialization can be awaited using `waitUntilInitialized`.
private var initialized: Bool = false
/// Set to `true` after the user has opened a project that doesn't support background indexing while having background
/// indexing enabled.
///
/// This ensures that we only inform the user about background indexing not being supported for these projects once.
private var didSendBackgroundIndexingNotSupportedNotification = false
var options: Options
let toolchainRegistry: ToolchainRegistry
public var capabilityRegistry: CapabilityRegistry?
var languageServices: [LanguageServerType: [LanguageService]] = [:]
let documentManager = DocumentManager()
/// The `TaskScheduler` that schedules all background indexing tasks.
///
/// Shared process-wide to ensure the scheduled index operations across multiple workspaces don't exceed the maximum
/// number of processor cores that the user allocated to background indexing.
private let indexTaskScheduler: TaskScheduler<AnyIndexTaskDescription>
/// Implicitly unwrapped optional so we can create an `IndexProgressManager` that has a weak reference to
/// `SourceKitLSPServer`.
/// `nonisolated(unsafe)` because `indexProgressManager` will not be modified after it is assigned from the
/// initializer.
private nonisolated(unsafe) var indexProgressManager: IndexProgressManager!
private var packageLoadingWorkDoneProgress = WorkDoneProgressState(
"SourceKitLSP.SourceKitLSPServer.reloadPackage",
title: "SourceKit-LSP: Reloading Package"
)
/// **Public for testing**
public var _documentManager: DocumentManager {
return documentManager
}
/// Caches which workspace a document with the given URI should be opened in.
///
/// - Important: Must only be modified from `workspaceQueue`. This means that the value of `uriToWorkspaceCache`
/// can't change while executing an operation on `workspaceQueue`.
private var uriToWorkspaceCache: [DocumentURI: WeakWorkspace] = [:]
/// The open workspaces.
///
/// Implicit workspaces are workspaces that weren't actually specified by the client during initialization or by a
/// `didChangeWorkspaceFolders` request. Instead, they were opened by sourcekit-lsp because a file could not be
/// handled by any of the open workspaces but one of the file's parent directories had handling capabilities for it.
///
/// - Important: Must only be modified from `workspaceQueue`. This means that the value of `workspacesAndIsImplicit`
/// can't change while executing an operation on `workspaceQueue`.
private var workspacesAndIsImplicit: [(workspace: Workspace, isImplicit: Bool)] = [] {
didSet {
uriToWorkspaceCache = [:]
// `indexProgressManager` iterates over all workspaces in the SourceKitLSPServer. Modifying workspaces might thus
// update the index progress status.
indexProgressManager.indexProgressStatusDidChange()
}
}
var workspaces: [Workspace] {
return workspacesAndIsImplicit.map(\.workspace)
}
@_spi(Testing)
public func setWorkspaces(_ newValue: [(workspace: Workspace, isImplicit: Bool)]) {
workspaceQueue.async {
self.workspacesAndIsImplicit = newValue
}
}
/// The requests that we are currently handling.
///
/// Used to cancel the tasks if the client requests cancellation.
private var inProgressRequests: [RequestID: Task<(), Never>] = [:]
/// - Note: Needed so we can set an in-progress request from a different
/// isolation context.
private func setInProgressRequest(for id: RequestID, task: Task<(), Never>?) {
self.inProgressRequests[id] = task
}
var onExit: () -> Void
/// Creates a language server for the given client.
public init(
client: Connection,
toolchainRegistry: ToolchainRegistry,
options: Options,
onExit: @escaping () -> Void = {}
) {
self.toolchainRegistry = toolchainRegistry
self.options = options
self.onExit = onExit
self.client = client
let processorCount = ProcessInfo.processInfo.processorCount
let lowPriorityCores = options.indexOptions.maxCoresPercentageToUseForBackgroundIndexing * Double(processorCount)
self.indexTaskScheduler = TaskScheduler(maxConcurrentTasksByPriority: [
(TaskPriority.medium, processorCount),
(TaskPriority.low, max(Int(lowPriorityCores), 1)),
])
self.indexProgressManager = nil
self.indexProgressManager = IndexProgressManager(sourceKitLSPServer: self)
}
/// Await until the server has send the reply to the initialize request.
func waitUntilInitialized() async {
// The polling of `initialized` is not perfect but it should be OK, because
// - In almost all cases the server should already be initialized.
// - If it's not initialized, we expect initialization to finish fairly quickly. Even if initialization takes 5s
// this only results in 50 polls, which is acceptable.
// Alternative solutions that signal via an async sequence seem overkill here.
while !initialized {
do {
try await Task.sleep(for: .seconds(0.1))
} catch {
break
}
}
}
/// Search through all the parent directories of `uri` and check if any of these directories contain a workspace
/// capable of handling `uri`.
///
/// The search will not consider any directory that is not a child of any of the directories in `rootUris`. This
/// prevents us from picking up a workspace that is outside of the folders that the user opened.
private func findWorkspaceCapableOfHandlingDocument(at uri: DocumentURI) async -> Workspace? {
guard var url = uri.fileURL?.deletingLastPathComponent() else {
return nil
}
let projectRoots = await self.workspacesAndIsImplicit.filter { !$0.isImplicit }.asyncCompactMap {
await $0.workspace.buildSystemManager.projectRoot
}
let rootURLs = workspacesAndIsImplicit.filter { !$0.isImplicit }.compactMap { $0.workspace.rootUri?.fileURL }
while url.pathComponents.count > 1 && rootURLs.contains(where: { $0.isPrefix(of: url) }) {
// Ignore workspaces that can't handle this file or that have the same project root as an existing workspace.
// The latter might happen if there is an existing SwiftPM workspace that hasn't been reloaded after a new file
// was added to it and thus currently doesn't know that it can handle that file. In that case, we shouldn't open
// a new workspace for the same root. Instead, the existing workspace's build system needs to be reloaded.
let workspace = await self.createWorkspace(WorkspaceFolder(uri: DocumentURI(url))) { buildSystem in
guard let buildSystem, !projectRoots.contains(await buildSystem.projectRoot) else {
// If we didn't create a build system, `url` is not capable of handling the document.
// If we already have a workspace at the same project root, don't create another one.
return false
}
do {
try await buildSystem.generateBuildGraph(allowFileSystemWrites: false)
} catch {
return false
}
return await buildSystem.fileHandlingCapability(for: uri) == .handled
}
if let workspace {
return workspace
}
url.deleteLastPathComponent()
}
return nil
}
public func workspaceForDocument(uri: DocumentURI) async -> Workspace? {
if let cachedWorkspace = self.uriToWorkspaceCache[uri]?.value {
return cachedWorkspace
}
// Execute the computation of the workspace on `workspaceQueue` to ensure that the file handling capabilities of the
// workspaces don't change during the computation. Otherwise, we could run into a race condition like the following:
// 1. We don't have an entry for file `a.swift` in `uriToWorkspaceCache` and start the computation
// 2. We find that the first workspace in `self.workspaces` can handle this file.
// 3. During the `await ... .fileHandlingCapability` for a second workspace the file handling capabilities for the
// first workspace change, meaning it can no longer handle the document. This resets `uriToWorkspaceCache`
// assuming that the URI to workspace relation will get re-computed.
// 4. But we then set `uriToWorkspaceCache[uri]` to the workspace found in step (2), caching an out-of-date result.
//
// Furthermore, the computation of the workspace for a URI can create a new implicit workspace, which modifies
// `workspacesAndIsImplicit` and which must only be modified on `workspaceQueue`.
return await self.workspaceQueue.async {
// Pick the workspace with the best FileHandlingCapability for this file.
// If there is a tie, use the workspace that occurred first in the list.
var bestWorkspace: (workspace: Workspace?, fileHandlingCapability: FileHandlingCapability) = (nil, .unhandled)
for workspace in self.workspaces {
let fileHandlingCapability = await workspace.buildSystemManager.fileHandlingCapability(for: uri)
if fileHandlingCapability > bestWorkspace.fileHandlingCapability {
bestWorkspace = (workspace, fileHandlingCapability)
}
}
if bestWorkspace.fileHandlingCapability < .handled {
// We weren't able to handle the document with any of the known workspaces. See if any of the document's parent
// directories contain a workspace that can handle the document.
if let workspace = await self.findWorkspaceCapableOfHandlingDocument(at: uri) {
// Appending a workspace is fine and doesn't require checking if we need to re-open any documents because:
// - Any currently open documents that have FileHandlingCapability `.handled` will continue to be opened in
// their current workspace because it occurs further in front inside the workspace list
// - Any currently open documents that have FileHandlingCapability < `.handled` also went through this check
// and didn't find any parent workspace that was able to handle them. We assume that a workspace can only
// properly handle files within its root directory, so those files now also can't be handled by the new
// workspace.
logger.log("Opening implicit workspace at \(workspace.rootUri.forLogging) to handle \(uri.forLogging)")
self.workspacesAndIsImplicit.append((workspace: workspace, isImplicit: true))
bestWorkspace = (workspace, .handled)
}
}
self.uriToWorkspaceCache[uri] = WeakWorkspace(bestWorkspace.workspace)
if let workspace = bestWorkspace.workspace {
return workspace
}
if let workspace = self.workspaces.only {
// Special handling: If there is only one workspace, open all files in it, even it it cannot handle the document.
// This retains the behavior of SourceKit-LSP before it supported multiple workspaces.
return workspace
}
return nil
}.valuePropagatingCancellation
}
/// Execute `notificationHandler` with the request as well as the workspace
/// and language that handle this document.
private func withLanguageServiceAndWorkspace<NotificationType: TextDocumentNotification>(
for notification: NotificationType,
notificationHandler: @escaping (NotificationType, LanguageService) async -> Void
) async {
let doc = notification.textDocument.uri
guard let workspace = await self.workspaceForDocument(uri: doc) else {
return
}
// This should be created as soon as we receive an open call, even if the document
// isn't yet ready.
guard let languageService = workspace.documentService.value[doc] else {
return
}
await notificationHandler(notification, languageService)
}
private func handleRequest<RequestType: TextDocumentRequest>(
for request: RequestAndReply<RequestType>,
requestHandler: @Sendable @escaping (
RequestType, Workspace, LanguageService
) async throws ->
RequestType.Response
) async {
await request.reply {
let request = request.params
let doc = request.textDocument.uri
guard let workspace = await self.workspaceForDocument(uri: request.textDocument.uri) else {
throw ResponseError.workspaceNotOpen(request.textDocument.uri)
}
guard let languageService = workspace.documentService.value[doc] else {
throw ResponseError.unknown("No language service for '\(request.textDocument.uri)' found")
}
return try await requestHandler(request, workspace, languageService)
}
}
/// Send the given notification to the editor.
public nonisolated func sendNotificationToClient(_ notification: some NotificationType) {
client.send(notification)
}
/// Send the given request to the editor.
public func sendRequestToClient<R: RequestType>(_ request: R) async throws -> R.Response {
return try await client.send(request)
}
/// After the language service has crashed, send `DidOpenTextDocumentNotification`s to a newly instantiated language service for previously open documents.
func reopenDocuments(for languageService: LanguageService) async {
for documentUri in self.documentManager.openDocuments {
guard let workspace = await self.workspaceForDocument(uri: documentUri) else {
continue
}
guard workspace.documentService.value[documentUri] === languageService else {
continue
}
guard let snapshot = try? self.documentManager.latestSnapshot(documentUri) else {
// The document has been closed since we retrieved its URI. We don't care about it anymore.
continue
}
// Close the document properly in the document manager and build system manager to start with a clean sheet when re-opening it.
let closeNotification = DidCloseTextDocumentNotification(textDocument: TextDocumentIdentifier(documentUri))
await self.closeDocument(closeNotification, workspace: workspace)
let textDocument = TextDocumentItem(
uri: documentUri,
language: snapshot.language,
version: snapshot.version,
text: snapshot.text
)
await self.openDocument(DidOpenTextDocumentNotification(textDocument: textDocument), workspace: workspace)
}
}
/// If a language service of type `serverType` that can handle `workspace` has
/// already been started, return it, otherwise return `nil`.
private func existingLanguageService(
_ serverType: LanguageServerType,
workspace: Workspace
) -> LanguageService? {
for languageService in languageServices[serverType, default: []] {
if languageService.canHandle(workspace: workspace) {
return languageService
}
}
return nil
}
func languageService(
for toolchain: Toolchain,
_ language: Language,
in workspace: Workspace
) async -> LanguageService? {
guard let serverType = LanguageServerType(language: language) else {
return nil
}
// Pick the first language service that can handle this workspace.
if let languageService = existingLanguageService(serverType, workspace: workspace) {
return languageService
}
// Start a new service.
return await orLog("failed to start language service", level: .error) {
let service = try await serverType.serverType.init(
sourceKitLSPServer: self,
toolchain: toolchain,
options: options,
workspace: workspace
)
guard let service else {
return nil
}
let pid = Int(ProcessInfo.processInfo.processIdentifier)
let resp = try await service.initialize(
InitializeRequest(
processId: pid,
rootPath: nil,
rootURI: workspace.rootUri,
initializationOptions: nil,
capabilities: workspace.capabilityRegistry.clientCapabilities,
trace: .off,
workspaceFolders: nil
)
)
let languages = languageClass(for: language)
await self.registerCapabilities(
for: resp.capabilities,
languages: languages,
registry: workspace.capabilityRegistry
)
// FIXME: store the server capabilities.
var syncKind: TextDocumentSyncKind
switch resp.capabilities.textDocumentSync {
case .options(let options):
syncKind = options.change ?? .incremental
case .kind(let kind):
syncKind = kind
default:
syncKind = .incremental
}
guard syncKind == .incremental else {
fatalError("non-incremental update not implemented")
}
await service.clientInitialized(InitializedNotification())
if let concurrentlyInitializedService = existingLanguageService(serverType, workspace: workspace) {
// Since we 'await' above, another call to languageService might have
// happened concurrently, passed the `existingLanguageService` check at
// the top and started initializing another language service.
// If this race happened, just shut down our server and return the
// other one.
await service.shutdown()
return concurrentlyInitializedService
}
languageServices[serverType, default: []].append(service)
return service
}
}
/// **Public for testing purposes only**
public func _languageService(
for uri: DocumentURI,
_ language: Language,
in workspace: Workspace
) async -> LanguageService? {
return await languageService(for: uri, language, in: workspace)
}
func languageService(
for uri: DocumentURI,
_ language: Language,
in workspace: Workspace
) async -> LanguageService? {
if let service = workspace.documentService.value[uri] {
return service
}
guard let toolchain = await workspace.buildSystemManager.toolchain(for: uri, language),
let service = await languageService(for: toolchain, language, in: workspace)
else {
logger.error("Failed to create language service for \(uri)")
return nil
}
logger.log("Using toolchain \(toolchain.displayName) (\(toolchain.identifier)) for \(uri.forLogging)")
return workspace.documentService.withLock { documentService in
if let concurrentlySetService = documentService[uri] {
// Since we await the construction of `service`, another call to this
// function might have happened and raced us, setting
// `workspace.documentServices[uri]`. If this is the case, return the
// existing value and discard the service that we just retrieved.
return concurrentlySetService
}
documentService[uri] = service
return service
}
}
}
// MARK: - MessageHandler
// nonisolated(unsafe) is fine because `notificationIDForLogging` is atomic.
private nonisolated(unsafe) var notificationIDForLogging = AtomicUInt32(initialValue: 1)
extension SourceKitLSPServer: MessageHandler {
public nonisolated func handle(_ params: some NotificationType) {
if let params = params as? CancelRequestNotification {
// Request cancellation needs to be able to overtake any other message we
// are currently handling. Ordering is not important here. We thus don't
// need to execute it on `messageHandlingQueue`.
self.cancelRequest(params)
}
let notificationID = notificationIDForLogging.fetchAndIncrement()
let signposter = Logger(subsystem: LoggingScope.subsystem, category: "notification-\(notificationID)")
.makeSignposter()
let signpostID = signposter.makeSignpostID()
let state = signposter.beginInterval("Notification", id: signpostID, "\(type(of: params))")
messageHandlingQueue.async(metadata: MessageHandlingDependencyTracker(params)) {
signposter.emitEvent("Start handling", id: signpostID)
// Only use the last two digits of the notification ID for the logging scope to avoid creating too many scopes.
// See comment in `withLoggingScope`.
// The last 2 digits should be sufficient to differentiate between multiple concurrently running notifications.
await withLoggingScope("notification-\(notificationID % 100)") {
await self.handleImpl(params)
signposter.endInterval("Notification", state, "Done")
}
}
}
private func handleImpl(_ notification: some NotificationType) async {
logger.log("Received notification: \(notification.forLogging)")
switch notification {
case let notification as InitializedNotification:
self.clientInitialized(notification)
case let notification as ExitNotification:
await self.exit(notification)
case let notification as DidOpenTextDocumentNotification:
await self.openDocument(notification)
case let notification as DidCloseTextDocumentNotification:
await self.closeDocument(notification)
case let notification as DidChangeTextDocumentNotification:
await self.changeDocument(notification)
case let notification as DidChangeWorkspaceFoldersNotification:
await self.didChangeWorkspaceFolders(notification)
case let notification as DidChangeWatchedFilesNotification:
await self.didChangeWatchedFiles(notification)
case let notification as WillSaveTextDocumentNotification:
await self.withLanguageServiceAndWorkspace(for: notification, notificationHandler: self.willSaveDocument)
case let notification as DidSaveTextDocumentNotification:
await self.withLanguageServiceAndWorkspace(for: notification, notificationHandler: self.didSaveDocument)
// IMPORTANT: When adding a new entry to this switch, also add it to the `MessageHandlingDependencyTracker` initializer.
default:
break
}
}
public nonisolated func handle<R: RequestType>(
_ params: R,
id: RequestID,
reply: @Sendable @escaping (LSPResult<R.Response>) -> Void
) {
let signposter = Logger(subsystem: LoggingScope.subsystem, category: "request-\(id)").makeSignposter()
let signpostID = signposter.makeSignpostID()
let state = signposter.beginInterval("Request", id: signpostID, "\(R.self)")
let task = messageHandlingQueue.async(metadata: MessageHandlingDependencyTracker(params)) {
signposter.emitEvent("Start handling", id: signpostID)
// Only use the last two digits of the request ID for the logging scope to avoid creating too many scopes.
// See comment in `withLoggingScope`.
// The last 2 digits should be sufficient to differentiate between multiple concurrently running requests.
await withLoggingScope("request-\(id.numericValue % 100)") {
await self.handleImpl(params, id: id, reply: reply)
signposter.endInterval("Request", state, "Done")
}
// We have handled the request and can't cancel it anymore.
// Stop keeping track of it to free the memory.
self.cancellationMessageHandlingQueue.async(priority: .background) {
await self.setInProgressRequest(for: id, task: nil)
}
}
// Keep track of the ID -> Task management with low priority. Once we cancel
// a request, the cancellation task runs with a high priority and depends on
// this task, which will elevate this task's priority.
cancellationMessageHandlingQueue.async(priority: .background) {
await self.setInProgressRequest(for: id, task: task)
}
}
private func handleImpl<R: RequestType>(
_ params: R,
id: RequestID,
reply: @Sendable @escaping (LSPResult<R.Response>) -> Void
) async {
let startDate = Date()
let request = RequestAndReply(params) { result in
reply(result)
let endDate = Date()
Task {
switch result {
case .success(let response):
logger.log(
"""
Succeeded (took \(endDate.timeIntervalSince(startDate) * 1000, privacy: .public)ms)
\(R.method, privacy: .public)
\(response.forLogging)
"""
)
case .failure(let error):
logger.log(
"""
Failed (took \(endDate.timeIntervalSince(startDate) * 1000, privacy: .public)ms)
\(R.method, privacy: .public)(\(id, privacy: .public))
\(error.forLogging, privacy: .private)
"""
)
}
}
}
logger.log("Received request \(id): \(params.forLogging)")
if let textDocumentRequest = params as? any TextDocumentRequest {
// When we are requesting information from a document, poke preparation of its target. We don't want to wait for
// the preparation to finish because that would cause too big a delay.
// In practice, while the user is working on a file, we'll get a text document request for it on a regular basis,
// which prepares the files. For files that are open but aren't being worked on (eg. a different tab), we don't
// get requests, ensuring that we don't unnecessarily prepare them.
let workspace = await self.workspaceForDocument(uri: textDocumentRequest.textDocument.uri)
await workspace?.semanticIndexManager?.schedulePreparationForEditorFunctionality(
of: textDocumentRequest.textDocument.uri
)
}
switch request {
case let request as RequestAndReply<InitializeRequest>:
await request.reply { try await initialize(request.params) }
// Only set `initialized` to `true` after we have sent the response to the initialize request to the client.
initialized = true
case let request as RequestAndReply<ShutdownRequest>:
await request.reply { try await shutdown(request.params) }
case let request as RequestAndReply<WorkspaceSymbolsRequest>:
await request.reply { try await workspaceSymbols(request.params) }
case let request as RequestAndReply<WorkspaceTestsRequest>:
await request.reply { try await workspaceTests(request.params) }
case let request as RequestAndReply<DocumentTestsRequest>:
await self.handleRequest(for: request, requestHandler: self.documentTests)
case let request as RequestAndReply<PollIndexRequest>:
await request.reply { try await pollIndex(request.params) }
case let request as RequestAndReply<BarrierRequest>:
await request.reply { VoidResponse() }
case let request as RequestAndReply<ExecuteCommandRequest>:
await request.reply { try await executeCommand(request.params) }
case let request as RequestAndReply<CallHierarchyIncomingCallsRequest>:
await request.reply { try await incomingCalls(request.params) }
case let request as RequestAndReply<CallHierarchyOutgoingCallsRequest>:
await request.reply { try await outgoingCalls(request.params) }
case let request as RequestAndReply<TypeHierarchySupertypesRequest>:
await request.reply { try await supertypes(request.params) }
case let request as RequestAndReply<TypeHierarchySubtypesRequest>:
await request.reply { try await subtypes(request.params) }
case let request as RequestAndReply<RenameRequest>:
await request.reply { try await rename(request.params) }
case let request as RequestAndReply<CompletionRequest>:
await self.handleRequest(for: request, requestHandler: self.completion)
case let request as RequestAndReply<HoverRequest>:
await self.handleRequest(for: request, requestHandler: self.hover)
case let request as RequestAndReply<OpenInterfaceRequest>:
await self.handleRequest(for: request, requestHandler: self.openInterface)
case let request as RequestAndReply<DeclarationRequest>:
await self.handleRequest(for: request, requestHandler: self.declaration)
case let request as RequestAndReply<DefinitionRequest>:
await self.handleRequest(for: request, requestHandler: self.definition)
case let request as RequestAndReply<ReferencesRequest>:
await self.handleRequest(for: request, requestHandler: self.references)
case let request as RequestAndReply<ImplementationRequest>:
await self.handleRequest(for: request, requestHandler: self.implementation)
case let request as RequestAndReply<CallHierarchyPrepareRequest>:
await self.handleRequest(for: request, requestHandler: self.prepareCallHierarchy)
case let request as RequestAndReply<TypeHierarchyPrepareRequest>:
await self.handleRequest(for: request, requestHandler: self.prepareTypeHierarchy)
case let request as RequestAndReply<SymbolInfoRequest>:
await self.handleRequest(for: request, requestHandler: self.symbolInfo)
case let request as RequestAndReply<DocumentHighlightRequest>:
await self.handleRequest(for: request, requestHandler: self.documentSymbolHighlight)
case let request as RequestAndReply<DocumentFormattingRequest>:
await self.handleRequest(for: request, requestHandler: self.documentFormatting)
case let request as RequestAndReply<FoldingRangeRequest>:
await self.handleRequest(for: request, requestHandler: self.foldingRange)
case let request as RequestAndReply<DocumentSymbolRequest>:
await self.handleRequest(for: request, requestHandler: self.documentSymbol)
case let request as RequestAndReply<DocumentColorRequest>:
await self.handleRequest(for: request, requestHandler: self.documentColor)
case let request as RequestAndReply<DocumentSemanticTokensRequest>:
await self.handleRequest(for: request, requestHandler: self.documentSemanticTokens)
case let request as RequestAndReply<DocumentSemanticTokensDeltaRequest>:
await self.handleRequest(for: request, requestHandler: self.documentSemanticTokensDelta)
case let request as RequestAndReply<DocumentSemanticTokensRangeRequest>:
await self.handleRequest(for: request, requestHandler: self.documentSemanticTokensRange)
case let request as RequestAndReply<ColorPresentationRequest>:
await self.handleRequest(for: request, requestHandler: self.colorPresentation)
case let request as RequestAndReply<CodeActionRequest>:
await self.handleRequest(for: request, requestHandler: self.codeAction)
case let request as RequestAndReply<InlayHintRequest>:
await self.handleRequest(for: request, requestHandler: self.inlayHint)
case let request as RequestAndReply<DocumentDiagnosticsRequest>:
await self.handleRequest(for: request, requestHandler: self.documentDiagnostic)
case let request as RequestAndReply<PrepareRenameRequest>:
await self.handleRequest(for: request, requestHandler: self.prepareRename)
case let request as RequestAndReply<IndexedRenameRequest>:
await self.handleRequest(for: request, requestHandler: self.indexedRename)
// IMPORTANT: When adding a new entry to this switch, also add it to the `MessageHandlingDependencyTracker` initializer.
default:
await request.reply { throw ResponseError.methodNotFound(R.method) }
}
}
}
// MARK: - Build System Delegate
extension SourceKitLSPServer: BuildSystemDelegate {
public func buildTargetsChanged(_ changes: [BuildTargetEvent]) {
// TODO: do something with these changes once build target support is in place
}
private func affectedOpenDocumentsForChangeSet(
_ changes: Set<DocumentURI>,
_ documentManager: DocumentManager
) -> Set<DocumentURI> {
// An empty change set is treated as if all open files have been modified.
guard !changes.isEmpty else {
return documentManager.openDocuments
}
return documentManager.openDocuments.intersection(changes)
}
/// Handle a build settings change notification from the `BuildSystem`.
/// This has two primary cases:
/// - Initial settings reported for a given file, now we can fully open it
/// - Changed settings for an already open file
public func fileBuildSettingsChanged(_ changedFiles: Set<DocumentURI>) async {
for uri in changedFiles {
guard self.documentManager.openDocuments.contains(uri) else {
continue
}
guard let service = await self.workspaceForDocument(uri: uri)?.documentService.value[uri] else {
continue
}
await service.documentUpdatedBuildSettings(uri)
}
}
/// Handle a dependencies updated notification from the `BuildSystem`.
/// We inform the respective language services as long as the given file is open
/// (not queued for opening).
public func filesDependenciesUpdated(_ changedFiles: Set<DocumentURI>) async {
// Split the changedFiles into the workspaces they belong to.
// Then invoke affectedOpenDocumentsForChangeSet for each workspace with its affected files.
let changedFilesAndWorkspace = await changedFiles.asyncMap {
return (uri: $0, workspace: await self.workspaceForDocument(uri: $0))
}
for workspace in self.workspaces {
let changedFilesForWorkspace = Set(changedFilesAndWorkspace.filter({ $0.workspace === workspace }).map(\.uri))
if changedFilesForWorkspace.isEmpty {
continue
}
for uri in self.affectedOpenDocumentsForChangeSet(changedFilesForWorkspace, self.documentManager) {
logger.log("Dependencies updated for opened file \(uri.forLogging)")
if let service = workspace.documentService.value[uri] {
await service.documentDependenciesUpdated(uri)
}
}
}
}
public func fileHandlingCapabilityChanged() {
workspaceQueue.async {
logger.log("Resetting URI to workspace cache because file handling capability of a workspace changed")
self.uriToWorkspaceCache = [:]
}
}
}
extension LanguageServerProtocol.BuildConfiguration {
/// Convert `LanguageServerProtocol.BuildConfiguration` to `SKSupport.BuildConfiguration`.
var configuration: SKSupport.BuildConfiguration {
switch self {
case .debug: return .debug
case .release: return .release
}
}
}
private extension LanguageServerProtocol.WorkspaceType {
/// Convert `LanguageServerProtocol.WorkspaceType` to `SkSupport.WorkspaceType`.
var workspaceType: SKSupport.WorkspaceType {
switch self {
case .buildServer: return .buildServer
case .compilationDatabase: return .compilationDatabase
case .swiftPM: return .swiftPM
}
}
}
extension SourceKitLSPServer {
nonisolated func indexTaskDidProduceResult(_ result: IndexProcessResult) {
self.sendNotificationToClient(
LogMessageNotification(
type: result.failed ? .warning : .info,
message: """
\(result.taskDescription) finished in \(result.duration)
\(result.command)
\(result.output)
"""
)
)
}
}
// MARK: - Request and notification handling
extension SourceKitLSPServer {
// MARK: - General
/// Returns the build setup for the parameters specified for the given `WorkspaceFolder`.
private func buildSetup(for workspaceFolder: WorkspaceFolder) -> BuildSetup {
let buildParams = workspaceFolder.buildSetup
let scratchPath: AbsolutePath?
if let scratchPathParam = buildParams?.scratchPath {
scratchPath = try? AbsolutePath(validating: scratchPathParam.pseudoPath)
} else {
scratchPath = nil
}
return SKCore.BuildSetup(
configuration: buildParams?.buildConfiguration?.configuration,
defaultWorkspaceType: buildParams?.defaultWorkspaceType?.workspaceType,
path: scratchPath,
flags: BuildFlags(
cCompilerFlags: buildParams?.cFlags ?? [],
cxxCompilerFlags: buildParams?.cxxFlags ?? [],
swiftCompilerFlags: buildParams?.swiftFlags ?? [],
linkerFlags: buildParams?.linkerFlags ?? [],
xcbuildFlags: []
)
)
}
/// Creates a workspace at the given `uri`.
///
/// If the build system that was determined for the workspace does not satisfy `condition`, `nil` is returned.
private func createWorkspace(
_ workspaceFolder: WorkspaceFolder,
condition: (BuildSystem?) async -> Bool = { _ in true }
) async -> Workspace? {
guard let capabilityRegistry = capabilityRegistry else {
logger.log("Cannot open workspace before server is initialized")
return nil
}
var options = self.options
options.buildSetup = self.options.buildSetup.merging(buildSetup(for: workspaceFolder))
let buildSystem = await createBuildSystem(
rootUri: workspaceFolder.uri,
options: options,
toolchainRegistry: toolchainRegistry,
reloadPackageStatusCallback: { [weak self] status in
guard let self else { return }
switch status {
case .start:
await self.packageLoadingWorkDoneProgress.startProgress(server: self)
case .end:
await self.packageLoadingWorkDoneProgress.endProgress(server: self)
}
}
)
guard await condition(buildSystem) else {
return nil
}
do {
try await buildSystem?.generateBuildGraph(allowFileSystemWrites: true)
} catch {
logger.error("failed to generate build graph at \(workspaceFolder.uri.forLogging): \(error.forLogging)")
return nil
}
let projectRoot = await buildSystem?.projectRoot.pathString
logger.log(
"Created workspace at \(workspaceFolder.uri.forLogging) as \(type(of: buildSystem)) with project root \(projectRoot ?? "<nil>")"
)
let workspace = try? await Workspace(
documentManager: self.documentManager,
rootUri: workspaceFolder.uri,
capabilityRegistry: capabilityRegistry,
buildSystem: buildSystem,
toolchainRegistry: self.toolchainRegistry,
options: options,
indexOptions: self.options.indexOptions,
indexTaskScheduler: indexTaskScheduler,
indexProcessDidProduceResult: { [weak self] in
self?.indexTaskDidProduceResult($0)
},
indexTasksWereScheduled: { [weak self] count in
self?.indexProgressManager.indexTasksWereScheduled(count: count)
},
indexProgressStatusDidChange: { [weak self] in
self?.indexProgressManager.indexProgressStatusDidChange()
}
)
if let workspace, options.indexOptions.enableBackgroundIndexing, workspace.semanticIndexManager == nil,
!self.didSendBackgroundIndexingNotSupportedNotification
{
self.sendNotificationToClient(
ShowMessageNotification(
type: .info,
message: """
Background indexing is currently only supported for SwiftPM projects. \
For all other project types, please run a build to update the index.
"""
)
)
self.didSendBackgroundIndexingNotSupportedNotification = true
}
return workspace
}
func initialize(_ req: InitializeRequest) async throws -> InitializeResult {
if case .dictionary(let options) = req.initializationOptions {
if case .bool(let listenToUnitEvents) = options["listenToUnitEvents"] {
self.options.indexOptions.listenToUnitEvents = listenToUnitEvents
}
if case .dictionary(let completionOptions) = options["completion"] {
switch completionOptions["maxResults"] {
case .none:
break
case .some(.null):
self.options.completionOptions.maxResults = nil
case .some(.int(let maxResults)):
self.options.completionOptions.maxResults = maxResults
case .some(let invalid):
logger.error("expected null or int for 'maxResults'; got \(String(reflecting: invalid))")
}
}
}
capabilityRegistry = CapabilityRegistry(clientCapabilities: req.capabilities)
await workspaceQueue.async {
if let workspaceFolders = req.workspaceFolders {
self.workspacesAndIsImplicit += await workspaceFolders.asyncCompactMap {
guard let workspace = await self.createWorkspace($0) else {
return nil
}
return (workspace: workspace, isImplicit: false)
}
} else if let uri = req.rootURI {
let workspaceFolder = WorkspaceFolder(uri: uri)
if let workspace = await self.createWorkspace(workspaceFolder) {
self.workspacesAndIsImplicit.append((workspace: workspace, isImplicit: false))
}
} else if let path = req.rootPath {
let workspaceFolder = WorkspaceFolder(uri: DocumentURI(URL(fileURLWithPath: path)))
if let workspace = await self.createWorkspace(workspaceFolder) {
self.workspacesAndIsImplicit.append((workspace: workspace, isImplicit: false))
}
}