forked from swiftlang/sourcekit-lsp
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathSourceKitLSPServer.swift
More file actions
2744 lines (2482 loc) · 109 KB
/
SourceKitLSPServer.swift
File metadata and controls
2744 lines (2482 loc) · 109 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
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 BuildSystemIntegration
import Dispatch
import Foundation
import IndexStoreDB
package import LanguageServerProtocol
package import LanguageServerProtocolExtensions
import LanguageServerProtocolJSONRPC
import SKLogging
package import SKOptions
import SemanticIndex
import SourceKitD
package import SwiftExtensions
package import ToolchainRegistry
import struct TSCBasic.AbsolutePath
import protocol TSCBasic.FileSystem
/// Disambiguate LanguageServerProtocol.Language and IndexstoreDB.Language
package typealias Language = LanguageServerProtocol.Language
/// 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.
package actor SourceKitLSPServer {
package let messageHandlingHelper = QueueBasedMessageHandlerHelper(
signpostLoggingCategory: "message-handling",
createLoggingScope: true
)
package let messageHandlingQueue = AsyncQueue<MessageHandlingDependencyTracker>()
/// The queue on which we keep track of `inProgressTextDocumentRequests` to ensure updates to
/// `inProgressTextDocumentRequests` are handled in order.
package let textDocumentTrackingQueue = AsyncQueue<Serial>()
/// The queue on which all modifications of `workspaceForUri` happen. This means that the value of
/// `workspacesAndIsImplicit` and `workspaceForUri` can't change while executing a closure on `workspaceQueue`.
private let workspaceQueue = AsyncQueue<Serial>()
/// The connection to the editor.
package 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
private let _options: ThreadSafeBox<SourceKitLSPOptions>
nonisolated var options: SourceKitLSPOptions {
_options.value
}
let hooks: Hooks
let toolchainRegistry: ToolchainRegistry
package var capabilityRegistry: CapabilityRegistry?
var languageServices: [LanguageServerType: [LanguageService]] = [:]
package let documentManager = DocumentManager()
#if canImport(SwiftDocC)
/// The `DocumentationManager` that handles all documentation related requests
///
/// Implicitly unwrapped optional so we can create an `DocumentationManager` that has a weak reference to
/// `SourceKitLSPServer`.
/// `nonisolated(unsafe)` because `documentationManager` will not be modified after it is assigned from the
/// initializer.
private(set) nonisolated(unsafe) var documentationManager: DocumentationManager!
#endif
/// 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(set) nonisolated(unsafe) var indexProgressManager: IndexProgressManager!
/// Implicitly unwrapped optional so we can create an `SharedWorkDoneProgressManager` that has a weak reference to
/// `SourceKitLSPServer`.
/// `nonisolated(unsafe)` because `sourcekitdCrashedWorkDoneProgress` will not be modified after it is assigned from
/// the initializer.
nonisolated(unsafe) var sourcekitdCrashedWorkDoneProgress: SharedWorkDoneProgressManager!
/// Stores which workspace the given URI has been opened in.
///
/// - Important: Must only be modified from `workspaceQueue`. This means that the value of `workspaceForUri`
/// can't change while executing an operation on `workspaceQueue`.
private var workspaceForUri: [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 {
self.scheduleUpdateOfUriToWorkspace()
}
}
var workspaces: [Workspace] {
return workspacesAndIsImplicit.map(\.workspace)
}
package func setWorkspaces(_ newValue: [(workspace: Workspace, isImplicit: Bool)]) {
workspaceQueue.async {
self.workspacesAndIsImplicit = newValue
}
}
/// For all currently handled text document requests a mapping from the document to the corresponding request ID and
/// the method of the request (ie. the value of `TextDocumentRequest.method`).
private var inProgressTextDocumentRequests: [DocumentURI: [(id: RequestID, requestMethod: String)]] = [:]
var onExit: () -> Void
/// The files that we asked the client to watch.
private var watchers: Set<FileSystemWatcher> = []
private static func maxConcurrentIndexingTasksByPriority(
isIndexingPaused: Bool,
options: SourceKitLSPOptions
) -> [(priority: TaskPriority, maxConcurrentTasks: Int)] {
let processorCount = ProcessInfo.processInfo.processorCount
let lowPriorityCores =
if isIndexingPaused {
0
} else {
max(
Int(options.indexOrDefault.maxCoresPercentageToUseForBackgroundIndexingOrDefault * Double(processorCount)),
1
)
}
return [
(TaskPriority.medium, processorCount),
(TaskPriority.low, lowPriorityCores),
]
}
/// Creates a language server for the given client.
package init(
client: Connection,
toolchainRegistry: ToolchainRegistry,
options: SourceKitLSPOptions,
hooks: Hooks,
onExit: @escaping () -> Void = {}
) {
self.toolchainRegistry = toolchainRegistry
self._options = ThreadSafeBox(initialValue: options)
self.hooks = hooks
self.onExit = onExit
self.client = client
self.indexTaskScheduler = TaskScheduler(
maxConcurrentTasksByPriority: Self.maxConcurrentIndexingTasksByPriority(isIndexingPaused: false, options: options)
)
self.indexProgressManager = nil
#if canImport(SwiftDocC)
self.documentationManager = nil
self.documentationManager = DocumentationManager(sourceKitLSPServer: self)
#endif
self.indexProgressManager = IndexProgressManager(sourceKitLSPServer: self)
self.sourcekitdCrashedWorkDoneProgress = SharedWorkDoneProgressManager(
sourceKitLSPServer: self,
tokenPrefix: "sourcekitd-crashed",
title: "SourceKit-LSP: Restoring functionality",
message: "Please run 'sourcekit-lsp diagnose' to file an issue"
)
}
/// Await until the server has send the reply to the initialize request.
package 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 with
/// a build system.
///
/// 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 findImplicitWorkspace(for uri: DocumentURI) async -> Workspace? {
guard var url = uri.fileURL?.deletingLastPathComponent() else {
return nil
}
// Roots of opened workspaces - only consider explicit here (all implicit must necessarily be subdirectories of
// the explicit workspace roots)
let workspaceRoots = workspacesAndIsImplicit.filter { !$0.isImplicit }.compactMap { $0.workspace.rootUri?.fileURL }
// We want to skip creating another workspace if any existing already has the same config path. This could happen if
// an existing workspace hasn't realoaded after a new file was added to it (and thus that build system needs to be
// reloaded).
let configPaths = await workspacesAndIsImplicit.asyncCompactMap {
await $0.workspace.buildSystemManager.configPath
}
while url.pathComponents.count > 1 && workspaceRoots.contains(where: { $0.isPrefix(of: url) }) {
defer {
url.deleteLastPathComponent()
}
let uri = DocumentURI(url)
let options = SourceKitLSPOptions.merging(base: self.options, workspaceFolder: uri)
// Some build systems consider paths outside of the folder (eg. BSP has settings in the home directory). If we
// allowed those paths, then the very first folder that the file is in would always be its own build system - so
// skip them in that case.
guard
let buildSystemSpec = determineBuildSystem(
forWorkspaceFolder: uri,
onlyConsiderRoot: true,
options: options,
hooks: hooks.buildSystemHooks
)
else {
continue
}
if configPaths.contains(buildSystemSpec.configPath) {
continue
}
// No existing workspace matches this root - create one.
guard
let workspace = await orLog(
"Creating implicit workspace",
{ try await createWorkspace(workspaceFolder: uri, options: options, buildSystemSpec: buildSystemSpec) }
)
else {
continue
}
return workspace
}
return nil
}
package func workspaceForDocument(uri: DocumentURI) async -> Workspace? {
let uri = uri.buildSettingsFile
if let cachedWorkspace = self.workspaceForUri[uri]?.value {
return cachedWorkspace
}
return await self.workspaceQueue.async {
await self.computeWorkspaceForDocument(uri: uri)
}.valuePropagatingCancellation
}
private func documentService(for uri: DocumentURI) async throws -> LanguageService {
guard let workspace = await self.workspaceForDocument(uri: uri) else {
throw ResponseError.workspaceNotOpen(uri)
}
guard let languageService = workspace.documentService(for: uri) else {
throw ResponseError.unknown("No language service for '\(uri)' found")
}
return languageService
}
/// This method must be executed 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 `workspaceForUri` 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 `workspaceForUri`
/// assuming that the URI to workspace relation will get re-computed.
/// 4. But we then set `workspaceForUri[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`.
///
/// - Important: Must only be invoked from `workspaceQueue`.
private func computeWorkspaceForDocument(uri: DocumentURI) async -> Workspace? {
// 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 = await self.workspaces.asyncFirst {
await !$0.buildSystemManager.targets(for: uri).isEmpty
}
if bestWorkspace == nil {
// 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 might be able to handle the document
if let workspace = await self.findImplicitWorkspace(for: uri) {
logger.log("Opening implicit workspace at \(workspace.rootUri.forLogging) to handle \(uri.forLogging)")
self.workspacesAndIsImplicit.append((workspace: workspace, isImplicit: true))
bestWorkspace = workspace
}
}
let workspace = bestWorkspace ?? self.workspaces.first
self.workspaceForUri[uri] = WeakWorkspace(workspace)
return workspace
}
/// Check that the entries in `workspaceForUri` are still up-to-date after workspaces might have changed.
///
/// For any entries that are not up-to-date, close the document in the old workspace and open it in the new document.
///
/// This method returns immediately and schedules the check in the background as a global configuration change.
/// Requests may still be served by their old workspace until this configuration change is executed by
/// `SourceKitLSPServer`.
private func scheduleUpdateOfUriToWorkspace() {
messageHandlingQueue.async(priority: .low, metadata: .globalConfigurationChange) {
logger.info("Updating URI to workspace")
// For each document that has moved to a different workspace, close it in
// the old workspace and open it in the new workspace.
for docUri in self.documentManager.openDocuments {
await self.workspaceQueue.async {
let oldWorkspace = self.workspaceForUri[docUri]?.value
let newWorkspace = await self.computeWorkspaceForDocument(uri: docUri)
guard newWorkspace !== oldWorkspace else {
return // Nothing to do, workspace didn't change for this document
}
guard let snapshot = try? self.documentManager.latestSnapshot(docUri) else {
return
}
if let oldWorkspace = oldWorkspace {
await self.closeDocument(
DidCloseTextDocumentNotification(
textDocument: TextDocumentIdentifier(docUri)
),
workspace: oldWorkspace
)
}
logger.info(
"Changing workspace of \(docUri.forLogging) from \(oldWorkspace?.rootUri?.forLogging) to \(newWorkspace?.rootUri?.forLogging)"
)
self.workspaceForUri[docUri] = WeakWorkspace(newWorkspace)
if let newWorkspace = newWorkspace {
await self.openDocument(
DidOpenTextDocumentNotification(
textDocument: TextDocumentItem(
uri: docUri,
language: snapshot.language,
version: snapshot.version,
text: snapshot.text
)
),
workspace: newWorkspace
)
}
}.valuePropagatingCancellation
}
// `indexProgressManager` iterates over all workspaces in the SourceKitLSPServer. Modifying workspaces might thus
// update the index progress status.
self.indexProgressManager.indexProgressStatusDidChange()
}
}
/// 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(for: 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(for: 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.
package nonisolated func sendNotificationToClient(_ notification: some NotificationType) {
client.send(notification)
}
/// Send the given request to the editor.
package 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(for: 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` using the given toolchain has already been
/// started, return it, otherwise return `nil`.
private func existingLanguageService(
_ serverType: LanguageServerType,
toolchain: Toolchain,
workspace: Workspace
) -> LanguageService? {
for languageService in languageServices[serverType, default: []] {
if languageService.canHandle(workspace: workspace, toolchain: toolchain) {
return languageService
}
}
return nil
}
func languageService(
for toolchain: Toolchain,
_ language: Language,
in workspace: Workspace
) async -> LanguageService? {
guard let serverType = LanguageServerType(language: language) else {
logger.error("Unable to infer language server type for language '\(language)'")
return nil
}
// Pick the first language service that can handle this workspace.
if let languageService = existingLanguageService(serverType, toolchain: toolchain, workspace: workspace) {
return languageService
}
// Start a new service.
return await orLog("failed to start language service", level: .error) { [options = workspace.options, hooks] in
let service = try await serverType.serverType.init(
sourceKitLSPServer: self,
toolchain: toolchain,
options: options,
hooks: hooks,
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
)
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,
toolchain: toolchain,
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
}
}
package func languageService(
for uri: DocumentURI,
_ language: Language,
in workspace: Workspace
) async -> LanguageService? {
if let service = workspace.documentService(for: uri) {
return service
}
let toolchain = await workspace.buildSystemManager.toolchain(
for: uri,
in: workspace.buildSystemManager.canonicalTarget(for: uri),
language: language
)
guard let toolchain else {
logger.error("Failed to determine toolchain for \(uri)")
return nil
}
guard 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 at \(toolchain.path.description) (\(toolchain.identifier, privacy: .public)) \
for \(uri.forLogging)
"""
)
return workspace.setDocumentService(for: uri, service)
}
}
// MARK: - MessageHandler
extension SourceKitLSPServer: QueueBasedMessageHandler {
private enum ImplicitTextDocumentRequestCancellationReason {
case documentChanged
case documentClosed
}
package nonisolated func didReceive(notification: some NotificationType) {
let textDocumentUri: DocumentURI
let cancellationReason: ImplicitTextDocumentRequestCancellationReason
switch notification {
case let params as DidChangeTextDocumentNotification:
textDocumentUri = params.textDocument.uri
cancellationReason = .documentChanged
case let params as DidCloseTextDocumentNotification:
textDocumentUri = params.textDocument.uri
cancellationReason = .documentClosed
default:
return
}
textDocumentTrackingQueue.async(priority: .high) {
await self.cancelTextDocumentRequests(for: textDocumentUri, reason: cancellationReason)
}
}
/// Cancel all in-progress text document requests for the given document.
///
/// As a user makes an edit to a file, these requests are most likely no longer relevant. It also makes sure that a
/// long-running sourcekitd request can't block the entire language server if the client does not cancel all requests.
/// For example, consider the following sequence of requests:
/// - `textDocument/semanticTokens/full` for document A
/// - `textDocument/didChange` for document A
/// - `textDocument/formatting` for document A
///
/// If the editor is not cancelling the semantic tokens request on edit (like VS Code does), then the `didChange`
/// notification is blocked on the semantic tokens request finishing. Hence, we also can't run the
/// `textDocument/formatting` request. Cancelling the semantic tokens on the edit fixes the issue.
///
/// This method is a no-op if `cancelTextDocumentRequestsOnEditAndClose` is disabled.
///
/// - Important: Should be invoked on `textDocumentTrackingQueue` to ensure that new text document requests are
/// registered before a notification that triggers cancellation might come in.
private func cancelTextDocumentRequests(for uri: DocumentURI, reason: ImplicitTextDocumentRequestCancellationReason) {
guard self.options.cancelTextDocumentRequestsOnEditAndCloseOrDefault else {
return
}
for (requestID, requestMethod) in self.inProgressTextDocumentRequests[uri, default: []] {
if reason == .documentChanged && requestMethod == CompletionRequest.method {
// As the user types, we filter the code completion results. Cancelling the completion request on every
// keystroke means that we will never build the initial list of completion results for this code
// completion session if building that list takes longer than the user's typing cadence (eg. for global
// completions) and we will thus not show any completions.
continue
}
logger.info("Implicitly cancelling request \(requestID)")
self.messageHandlingHelper.cancelRequest(id: requestID)
}
}
package func handle(notification: some NotificationType) async {
logger.log("Received notification: \(notification.forLogging)")
switch notification {
case let notification as DidChangeActiveDocumentNotification:
await self.didChangeActiveDocument(notification)
case let notification as DidChangeTextDocumentNotification:
await self.changeDocument(notification)
case let notification as DidChangeWorkspaceFoldersNotification:
await self.didChangeWorkspaceFolders(notification)
case let notification as DidCloseTextDocumentNotification:
await self.closeDocument(notification)
case let notification as DidChangeWatchedFilesNotification:
await self.didChangeWatchedFiles(notification)
case let notification as DidOpenTextDocumentNotification:
await self.openDocument(notification)
case let notification as DidSaveTextDocumentNotification:
await self.withLanguageServiceAndWorkspace(for: notification, notificationHandler: self.didSaveDocument)
case let notification as InitializedNotification:
self.clientInitialized(notification)
case let notification as ExitNotification:
await self.exit(notification)
case let notification as ReopenTextDocumentNotification:
await self.reopenDocument(notification)
case let notification as WillSaveTextDocumentNotification:
await self.withLanguageServiceAndWorkspace(for: notification, notificationHandler: self.willSaveDocument)
// IMPORTANT: When adding a new entry to this switch, also add it to the `MessageHandlingDependencyTracker` initializer.
default:
break
}
}
package nonisolated func didReceive(request: some RequestType, id: RequestID) {
guard let request = request as? any TextDocumentRequest else {
return
}
textDocumentTrackingQueue.async(priority: .background) {
await self.registerInProgressTextDocumentRequest(request, id: id)
}
}
/// - Important: Should be invoked on `textDocumentTrackingQueue` to ensure that new text document requests are
/// registered before a notification that triggers cancellation might come in.
private func registerInProgressTextDocumentRequest<T: TextDocumentRequest>(_ request: T, id: RequestID) {
self.inProgressTextDocumentRequests[request.textDocument.uri, default: []].append((id: id, requestMethod: T.method))
}
package func handle<Request: RequestType>(
request params: Request,
id: RequestID,
reply: @Sendable @escaping (LSPResult<Request.Response>) -> Void
) async {
defer {
if let request = params as? any TextDocumentRequest {
textDocumentTrackingQueue.async(priority: .background) {
self.inProgressTextDocumentRequests[request.textDocument.uri, default: []].removeAll { $0.id == id }
}
}
}
await self.hooks.preHandleRequest?(params)
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)
\(Request.method, privacy: .public)
\(response.forLogging)
"""
)
case .failure(let error):
logger.log(
"""
Failed (took \(endDate.timeIntervalSince(startDate) * 1000, privacy: .public)ms)
\(Request.method, privacy: .public)(\(id, privacy: .public))
\(error.forLogging, privacy: .private)
"""
)
}
}
}
logger.log("Received request \(id, privacy: .public): \(params.forLogging)")
if let textDocumentRequest = params as? any TextDocumentRequest {
await self.clientInteractedWithDocument(textDocumentRequest.textDocument.uri)
}
switch request {
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<CallHierarchyPrepareRequest>:
await self.handleRequest(for: request, requestHandler: self.prepareCallHierarchy)
case let request as RequestAndReply<CodeActionRequest>:
await self.handleRequest(for: request, requestHandler: self.codeAction)
case let request as RequestAndReply<CodeLensRequest>:
await self.handleRequest(for: request, requestHandler: self.codeLens)
case let request as RequestAndReply<ColorPresentationRequest>:
await self.handleRequest(for: request, requestHandler: self.colorPresentation)
case let request as RequestAndReply<CompletionRequest>:
await self.handleRequest(for: request, requestHandler: self.completion)
case let request as RequestAndReply<CompletionItemResolveRequest>:
await request.reply { try await completionItemResolve(request: request.params) }
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)
#if canImport(SwiftDocC)
case let request as RequestAndReply<DoccDocumentationRequest>:
await request.reply { try await doccDocumentation(request.params) }
#endif
case let request as RequestAndReply<DocumentColorRequest>:
await self.handleRequest(for: request, requestHandler: self.documentColor)
case let request as RequestAndReply<DocumentDiagnosticsRequest>:
await self.handleRequest(for: request, requestHandler: self.documentDiagnostic)
case let request as RequestAndReply<DocumentFormattingRequest>:
await self.handleRequest(for: request, requestHandler: self.documentFormatting)
case let request as RequestAndReply<DocumentRangeFormattingRequest>:
await self.handleRequest(for: request, requestHandler: self.documentRangeFormatting)
case let request as RequestAndReply<DocumentOnTypeFormattingRequest>:
await self.handleRequest(for: request, requestHandler: self.documentOnTypeFormatting)
case let request as RequestAndReply<DocumentHighlightRequest>:
await self.handleRequest(for: request, requestHandler: self.documentSymbolHighlight)
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<DocumentSemanticTokensRequest>:
await self.handleRequest(for: request, requestHandler: self.documentSemanticTokens)
case let request as RequestAndReply<DocumentSymbolRequest>:
await self.handleRequest(for: request, requestHandler: self.documentSymbol)
case let request as RequestAndReply<DocumentTestsRequest>:
await self.handleRequest(for: request, requestHandler: self.documentTests)
case let request as RequestAndReply<ExecuteCommandRequest>:
await request.reply { try await executeCommand(request.params) }
case let request as RequestAndReply<FoldingRangeRequest>:
await self.handleRequest(for: request, requestHandler: self.foldingRange)
case let request as RequestAndReply<GetReferenceDocumentRequest>:
await request.reply { try await getReferenceDocument(request.params) }
case let request as RequestAndReply<HoverRequest>:
await self.handleRequest(for: request, requestHandler: self.hover)
case let request as RequestAndReply<ImplementationRequest>:
await self.handleRequest(for: request, requestHandler: self.implementation)
case let request as RequestAndReply<IndexedRenameRequest>:
await self.handleRequest(for: request, requestHandler: self.indexedRename)
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<InlayHintRequest>:
await self.handleRequest(for: request, requestHandler: self.inlayHint)
case let request as RequestAndReply<IsIndexingRequest>:
await request.reply { try await self.isIndexing(request.params) }
case let request as RequestAndReply<OutputPathsRequest>:
await request.reply { try await outputPaths(request.params) }
case let request as RequestAndReply<PrepareRenameRequest>:
await self.handleRequest(for: request, requestHandler: self.prepareRename)
case let request as RequestAndReply<ReferencesRequest>:
await self.handleRequest(for: request, requestHandler: self.references)
case let request as RequestAndReply<RenameRequest>:
await request.reply { try await rename(request.params) }
case let request as RequestAndReply<SetOptionsRequest>:
await request.reply { try await self.setBackgroundIndexingPaused(request.params) }
case let request as RequestAndReply<SourceKitOptionsRequest>:
await request.reply { try await sourceKitOptions(request.params) }
case let request as RequestAndReply<ShutdownRequest>:
await request.reply { try await shutdown(request.params) }
case let request as RequestAndReply<SymbolInfoRequest>:
await self.handleRequest(for: request, requestHandler: self.symbolInfo)
case let request as RequestAndReply<SynchronizeRequest>:
await request.reply { try await synchronize(request.params) }
case let request as RequestAndReply<TriggerReindexRequest>:
await request.reply { try await triggerReindex(request.params) }
case let request as RequestAndReply<TypeHierarchyPrepareRequest>:
await self.handleRequest(for: request, requestHandler: self.prepareTypeHierarchy)
case let request as RequestAndReply<TypeHierarchySubtypesRequest>:
await request.reply { try await subtypes(request.params) }
case let request as RequestAndReply<TypeHierarchySupertypesRequest>:
await request.reply { try await supertypes(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) }
// IMPORTANT: When adding a new entry to this switch, also add it to the `MessageHandlingDependencyTracker` initializer.
default:
await request.reply { throw ResponseError.methodNotFound(Request.method) }
}
}
}
extension SourceKitLSPServer {
nonisolated package func logMessageToIndexLog(
message: String,
type: WindowMessageType,
structure: StructuredLogKind?
) {
self.sendNotificationToClient(
LogMessageNotification(
type: type,
message: message,
logName: "SourceKit-LSP: Indexing",
structure: structure
).representingTaskIDUsingEmojiPrefixIfNecessary(options: options)
)
}
func fileHandlingCapabilityChanged() {
logger.log("Scheduling update of URI to workspace because file handling capability of a workspace changed")
self.scheduleUpdateOfUriToWorkspace()
}
}
// MARK: - Request and notification handling
extension SourceKitLSPServer {
// MARK: - General
/// Creates a workspace at the given `uri`.
///
/// A workspace does not necessarily have any build system attached to it, in which case `buildSystemSpec` may be
/// `nil` - consider eg. a top level workspace folder with multiple SwiftPM projects inside it.
private func createWorkspace(
workspaceFolder: DocumentURI,
options: SourceKitLSPOptions,
buildSystemSpec: BuildSystemSpec?
) async throws -> Workspace {
guard let capabilityRegistry = capabilityRegistry else {
struct NoCapabilityRegistryError: Error {}
logger.log("Cannot open workspace before server is initialized")
throw NoCapabilityRegistryError()
}
let options = SourceKitLSPOptions.merging(
base: self.options,
override: SourceKitLSPOptions(
path: workspaceFolder.fileURL?
.appendingPathComponent(".sourcekit-lsp")
.appendingPathComponent("config.json")
)
)
logger.log("Creating workspace at \(workspaceFolder.forLogging)")
logger.logFullObjectInMultipleLogMessages(header: "Options for workspace", options.loggingProxy)
let workspace = await Workspace(
sourceKitLSPServer: self,
documentManager: self.documentManager,
rootUri: workspaceFolder,
capabilityRegistry: capabilityRegistry,
buildSystemSpec: buildSystemSpec,
toolchainRegistry: self.toolchainRegistry,
options: options,
hooks: hooks,
indexTaskScheduler: indexTaskScheduler
)
return workspace
}
/// Determines the build system for the given workspace folder and creates a `Workspace` that uses this inferred build
/// system.
private func createWorkspaceWithInferredBuildSystem(workspaceFolder: DocumentURI) async throws -> Workspace {
let options = SourceKitLSPOptions.merging(base: self.options, workspaceFolder: workspaceFolder)
let buildSystemSpec = determineBuildSystem(
forWorkspaceFolder: workspaceFolder,
onlyConsiderRoot: false,
options: options,
hooks: hooks.buildSystemHooks
)
return try await self.createWorkspace(
workspaceFolder: workspaceFolder,
options: options,
buildSystemSpec: buildSystemSpec
)
}
func initialize(_ req: InitializeRequest) async throws -> InitializeResult {
logger.logFullObjectInMultipleLogMessages(header: "Initialize request", AnyRequestType(request: req))
// If the client can handle `PeekDocumentsRequest`, they can enable the
// experimental client capability `"workspace/peekDocuments"` through the `req.capabilities.experimental`.
//
// The below is a workaround for the vscode-swift extension since it cannot set client capabilities.
// It passes "workspace/peekDocuments" through the `initializationOptions`.
var clientCapabilities = req.capabilities
if case .dictionary(let initializationOptions) = req.initializationOptions {
let experimentalClientCapabilities = [
PeekDocumentsRequest.method,
GetReferenceDocumentRequest.method,
DidChangeActiveDocumentNotification.method,
]
for capabilityName in experimentalClientCapabilities {
guard let experimentalCapability = initializationOptions[capabilityName] else {
continue
}
if case .dictionary(var experimentalCapabilities) = clientCapabilities.experimental {
experimentalCapabilities[capabilityName] = experimentalCapability
clientCapabilities.experimental = .dictionary(experimentalCapabilities)
} else {
clientCapabilities.experimental = .dictionary([capabilityName: experimentalCapability])
}
}
// The client announces what CodeLenses it supports, and the LSP will only return
// ones found in the supportedCommands dictionary.
if let codeLens = initializationOptions["textDocument/codeLens"],
case let .dictionary(codeLensConfig) = codeLens,
case let .dictionary(supportedCommands) = codeLensConfig["supportedCommands"]
{
let commandMap = supportedCommands.compactMap { (key, value) in
if case let .string(clientCommand) = value {
return (SupportedCodeLensCommand(rawValue: key), clientCommand)
}
return nil
}
clientCapabilities.textDocument?.codeLens?.supportedCommands = Dictionary(uniqueKeysWithValues: commandMap)
}
}
capabilityRegistry = CapabilityRegistry(clientCapabilities: clientCapabilities)
let initializeOptions = orLog("Parsing options") { try SourceKitLSPOptions(fromLSPAny: req.initializationOptions) }
_options.withLock { options in
options = SourceKitLSPOptions.merging(base: options, override: initializeOptions)
}
logger.log("Initialized SourceKit-LSP")
logger.logFullObjectInMultipleLogMessages(header: "SourceKit-LSP Options", options.loggingProxy)
await workspaceQueue.async { [hooks] in
if let workspaceFolders = req.workspaceFolders {
self.workspacesAndIsImplicit += await workspaceFolders.asyncCompactMap { workspaceFolder in
await orLog("Creating workspace from workspaceFolders") {
return (
workspace: try await self.createWorkspaceWithInferredBuildSystem(workspaceFolder: workspaceFolder.uri),
isImplicit: false
)
}
}
} else if let uri = req.rootURI {
await orLog("Creating workspace from rootURI") {
self.workspacesAndIsImplicit.append(
(workspace: try await self.createWorkspaceWithInferredBuildSystem(workspaceFolder: uri), isImplicit: false)
)
}