forked from apple/sourcekit-lsp
-
Notifications
You must be signed in to change notification settings - Fork 1
/
SourceKitServer.swift
1963 lines (1747 loc) · 71.5 KB
/
SourceKitServer.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 Dispatch
import Foundation
import IndexStoreDB
import LanguageServerProtocol
import LSPLogging
import SKCore
import SKSupport
import PackageLoading
import protocol TSCBasic.FileSystem
import struct TSCBasic.AbsolutePath
import var TSCBasic.localFileSystem
public typealias URL = Foundation.URL
private struct WeakWorkspace {
weak var value: Workspace?
}
/// Exhaustive enumeration of all toolchain language servers known to SourceKit-LSP.
enum LanguageServerType: Hashable {
case clangd
case swift
init?(language: Language) {
switch language {
case .c, .cpp, .objective_c, .objective_cpp:
self = .clangd
case .swift:
self = .swift
default:
return nil
}
}
/// The `ToolchainLanguageServer` class used to provide functionality for this language class.
var serverType: ToolchainLanguageServer.Type {
switch self {
case .clangd:
return ClangLanguageServerShim.self
case .swift:
return SwiftLanguageServer.self
}
}
}
/// Keeps track of the state to send work done progress updates to the client
final class WorkDoneProgressState {
private enum State {
/// No `WorkDoneProgress` has been created.
case noProgress
/// We have sent the request to create a `WorkDoneProgress` but haven’t received a respose yet.
case creating
/// A `WorkDoneProgress` has been created.
case created
/// The creation of a `WorkDoneProgress has failed`.
///
/// This causes us to just give up creating any more `WorkDoneProgress` in
/// the future as those will most likely also fail.
case progressCreationFailed
}
/// How many active tasks are running.
///
/// A work done progress should be displayed if activeTasks > 0
private var activeTasks: Int = 0
private var state: State = .noProgress
/// The token by which we track the `WorkDoneProgress`.
private let token: ProgressToken
/// The title that should be displayed to the user in the UI.
private let title: String
init(_ token: String, title: String) {
self.token = ProgressToken.string(token)
self.title = title
}
/// Start a new task, creating a new `WorkDoneProgress` if none is running right now.
///
/// - Parameter server: The server that is used to create the `WorkDoneProgress` on the client
///
/// - Important: Must be called on `server.queue`.
func startProgress(server: SourceKitServer) {
dispatchPrecondition(condition: .onQueue(server.queue))
activeTasks += 1
if state == .noProgress {
state = .creating
// Discard the handle. We don't support cancellation of the creation of a work done progress.
_ = server.client.send(CreateWorkDoneProgressRequest(token: token), queue: server.queue) { result in
if result.success != nil {
if self.activeTasks == 0 {
// ActiveTasks might have been decreased while we created the `WorkDoneProgress`
self.state = .noProgress
server.client.send(WorkDoneProgress(token: self.token, value: .end(WorkDoneProgressEnd())))
} else {
self.state = .created
server.client.send(WorkDoneProgress(token: self.token, value: .begin(WorkDoneProgressBegin(title: self.title))))
}
} else {
self.state = .progressCreationFailed
}
}
}
}
/// End a new task stated using `startProgress`.
///
/// If this drops the active task count to 0, the work done progress is ended on the client.
///
/// - Parameter server: The server that is used to send and update of the `WorkDoneProgress` to the client
///
/// - Important: Must be called on `server.queue`.
func endProgress(server: SourceKitServer) {
dispatchPrecondition(condition: .onQueue(server.queue))
assert(activeTasks > 0, "Unbalanced startProgress/endProgress calls")
activeTasks -= 1
if state == .created && activeTasks == 0 {
server.client.send(WorkDoneProgress(token: token, value: .end(WorkDoneProgressEnd())))
}
}
}
/// The SourceKit language 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 final class SourceKitServer: LanguageServer {
var options: Options
let toolchainRegistry: ToolchainRegistry
var capabilityRegistry: CapabilityRegistry?
var languageServices: [LanguageServerType: [ToolchainLanguageServer]] = [:]
/// Documents that are ready for requests and notifications.
/// This generally means that the `BuildSystem` has notified of us of build settings.
var documentsReady: Set<DocumentURI> = []
private var documentToPendingQueue: [DocumentURI: DocumentNotificationRequestQueue] = [:]
private let documentManager = DocumentManager()
private var packageLoadingWorkDoneProgress = WorkDoneProgressState("SourceKitLSP.SoruceKitServer.reloadPackage", title: "Reloading Package")
/// **Public for testing**
public var _documentManager: DocumentManager {
return documentManager
}
/// Caches which workspace a document with the given URI should be opened in.
/// Must only be accessed from `queue`.
private var uriToWorkspaceCache: [DocumentURI: WeakWorkspace] = [:] {
didSet {
dispatchPrecondition(condition: .onQueue(queue))
}
}
/// Must only be accessed from `queue`.
private var workspaces: [Workspace] = [] {
didSet {
dispatchPrecondition(condition: .onQueue(queue))
uriToWorkspaceCache = [:]
}
}
/// **Public for testing**
public var _workspaces: [Workspace] {
get {
return queue.sync {
return self.workspaces
}
}
set {
queue.sync {
self.workspaces = newValue
}
}
}
let fs: FileSystem
var onExit: () -> Void
/// Creates a language server for the given client.
public init(client: Connection, fileSystem: FileSystem = localFileSystem, options: Options, onExit: @escaping () -> Void = {}) {
self.fs = fileSystem
self.toolchainRegistry = ToolchainRegistry.shared
self.options = options
self.onExit = onExit
super.init(client: client)
}
public func workspaceForDocument(uri: DocumentURI) -> Workspace? {
dispatchPrecondition(condition: .onQueue(queue))
if workspaces.count == 1 {
// Special handling: If there is only one workspace, open all files in it.
// This retains the behavior of SourceKit-LSP before it supported multiple workspaces.
return workspaces.first
}
if let cachedWorkspace = uriToWorkspaceCache[uri]?.value {
return cachedWorkspace
}
// 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 workspaces {
let fileHandlingCapability = workspace.buildSystemManager.fileHandlingCapability(for: uri)
if fileHandlingCapability > bestWorkspace.fileHandlingCapability {
bestWorkspace = (workspace, fileHandlingCapability)
}
}
uriToWorkspaceCache[uri] = WeakWorkspace(value: bestWorkspace.workspace)
return bestWorkspace.workspace
}
public override func _registerBuiltinHandlers() {
_register(SourceKitServer.initialize)
_register(SourceKitServer.clientInitialized)
_register(SourceKitServer.cancelRequest)
_register(SourceKitServer.shutdown)
_register(SourceKitServer.exit)
_register(SourceKitServer.openDocument)
_register(SourceKitServer.closeDocument)
_register(SourceKitServer.changeDocument)
_register(SourceKitServer.didChangeWorkspaceFolders)
_register(SourceKitServer.didChangeWatchedFiles)
registerToolchainTextDocumentNotification(SourceKitServer.willSaveDocument)
registerToolchainTextDocumentNotification(SourceKitServer.didSaveDocument)
_register(SourceKitServer.workspaceSymbols)
_register(SourceKitServer.pollIndex)
_register(SourceKitServer.executeCommand)
_register(SourceKitServer.incomingCalls)
_register(SourceKitServer.outgoingCalls)
_register(SourceKitServer.supertypes)
_register(SourceKitServer.subtypes)
registerToolchainTextDocumentRequest(SourceKitServer.completion,
CompletionList(isIncomplete: false, items: []))
registerToolchainTextDocumentRequest(SourceKitServer.hover, nil)
registerToolchainTextDocumentRequest(SourceKitServer.openInterface, nil)
registerToolchainTextDocumentRequest(SourceKitServer.declaration, .locations([]))
registerToolchainTextDocumentRequest(SourceKitServer.definition, .locations([]))
registerToolchainTextDocumentRequest(SourceKitServer.references, [])
registerToolchainTextDocumentRequest(SourceKitServer.implementation, .locations([]))
registerToolchainTextDocumentRequest(SourceKitServer.prepareCallHierarchy, [])
registerToolchainTextDocumentRequest(SourceKitServer.prepareTypeHierarchy, [])
registerToolchainTextDocumentRequest(SourceKitServer.symbolInfo, [])
registerToolchainTextDocumentRequest(SourceKitServer.documentSymbolHighlight, nil)
registerToolchainTextDocumentRequest(SourceKitServer.foldingRange, nil)
registerToolchainTextDocumentRequest(SourceKitServer.documentSymbol, nil)
registerToolchainTextDocumentRequest(SourceKitServer.documentColor, [])
registerToolchainTextDocumentRequest(SourceKitServer.documentSemanticTokens, nil)
registerToolchainTextDocumentRequest(SourceKitServer.documentSemanticTokensDelta, nil)
registerToolchainTextDocumentRequest(SourceKitServer.documentSemanticTokensRange, nil)
registerToolchainTextDocumentRequest(SourceKitServer.colorPresentation, [])
registerToolchainTextDocumentRequest(SourceKitServer.codeAction, nil)
registerToolchainTextDocumentRequest(SourceKitServer.inlayHint, [])
registerToolchainTextDocumentRequest(SourceKitServer.documentDiagnostic,
.full(.init(items: [])))
}
/// Register a `TextDocumentRequest` that requires a valid `Workspace`, `ToolchainLanguageServer`,
/// and open file with resolved (yet potentially invalid) build settings.
func registerToolchainTextDocumentRequest<PositionRequest: TextDocumentRequest>(
_ requestHandler: @escaping (SourceKitServer) ->
(Request<PositionRequest>, Workspace, ToolchainLanguageServer) -> Void,
_ fallback: PositionRequest.Response
) {
_register { [unowned self] (req: Request<PositionRequest>) in
let doc = req.params.textDocument.uri
guard let workspace = self.workspaceForDocument(uri: doc) else {
return req.reply(.failure(.workspaceNotOpen(doc)))
}
// 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[doc] else {
return req.reply(fallback)
}
// If the document is ready, we can handle it right now.
guard !self.documentsReady.contains(doc) else {
requestHandler(self)(req, workspace, languageService)
return
}
// Not ready to handle it, we'll queue it and handle it later.
self.documentToPendingQueue[doc, default: DocumentNotificationRequestQueue()].add(operation: {
[weak self] in
guard let self = self else { return }
requestHandler(self)(req, workspace, languageService)
}, cancellationHandler: {
req.reply(fallback)
})
}
}
/// Register a `TextDocumentNotification` that requires a valid
/// `ToolchainLanguageServer` and open file with resolved (yet
/// potentially invalid) build settings.
func registerToolchainTextDocumentNotification<TextNotification: TextDocumentNotification>(
_ notificationHandler: @escaping (SourceKitServer) ->
(Notification<TextNotification>, ToolchainLanguageServer) -> Void
) {
_register { [unowned self] (note: Notification<TextNotification>) in
let doc = note.params.textDocument.uri
guard let workspace = 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[doc] else {
return
}
// If the document is ready, we can handle it right now.
guard !self.documentsReady.contains(doc) else {
notificationHandler(self)(note, languageService)
return
}
// Not ready to handle it, we'll queue it and handle it later.
self.documentToPendingQueue[doc, default: DocumentNotificationRequestQueue()].add(operation: {
[weak self] in
guard let self = self else { return }
notificationHandler(self)(note, languageService)
})
}
}
public override func _handleUnknown<R>(_ req: Request<R>) {
if req.clientID == ObjectIdentifier(client) {
return super._handleUnknown(req)
}
// Unknown requests from a language server are passed on to the client.
let id = client.send(req.params, queue: queue) { result in
req.reply(result)
}
req.cancellationToken.addCancellationHandler {
self.client.send(CancelRequestNotification(id: id))
}
}
/// Handle an unknown notification.
public override func _handleUnknown<N>(_ note: Notification<N>) {
if note.clientID == ObjectIdentifier(client) {
return super._handleUnknown(note)
}
// Unknown notifications from a language server are passed on to the client.
client.send(note.params)
}
func toolchain(for uri: DocumentURI, _ language: Language) -> Toolchain? {
let supportsLang = { (toolchain: Toolchain) -> Bool in
// FIXME: the fact that we're looking at clangd/sourcekitd instead of the compiler indicates this method needs a parameter stating what kind of tool we're looking for.
switch language {
case .swift:
return toolchain.sourcekitd != nil
case .c, .cpp, .objective_c, .objective_cpp:
return toolchain.clangd != nil
default:
return false
}
}
if let toolchain = toolchainRegistry.default, supportsLang(toolchain) {
return toolchain
}
for toolchain in toolchainRegistry.toolchains {
if supportsLang(toolchain) {
return toolchain
}
}
return nil
}
/// After the language service has crashed, send `DidOpenTextDocumentNotification`s to a newly instantiated language service for previously open documents.
func reopenDocuments(for languageService: ToolchainLanguageServer) {
queue.async {
for documentUri in self.documentManager.openDocuments {
guard let workspace = self.workspaceForDocument(uri: documentUri) else {
continue
}
guard workspace.documentService[documentUri] === languageService else {
continue
}
guard let snapshot = 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 docuemnt 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))
self.closeDocument(closeNotification, workspace: workspace)
let textDocument = TextDocumentItem(uri: documentUri,
language: snapshot.document.language,
version: snapshot.version,
text: snapshot.text)
self.openDocument(DidOpenTextDocumentNotification(textDocument: textDocument), workspace: workspace)
}
}
}
func languageService(
for toolchain: Toolchain,
_ language: Language,
in workspace: Workspace
) -> ToolchainLanguageServer? {
guard let serverType = LanguageServerType(language: language) else {
return nil
}
// Pick the first language service that can handle this workspace.
for languageService in languageServices[serverType, default: []] {
if languageService.canHandle(workspace: workspace) {
return languageService
}
}
// Start a new service.
return orLog("failed to start language service", level: .error) {
guard let service = try SourceKitLSP.languageService(
for: toolchain, serverType, options: options, client: self, in: workspace, reopenDocuments: { [weak self] in self?.reopenDocuments(for: $0) })
else {
return nil
}
let pid = Int(ProcessInfo.processInfo.processIdentifier)
let resp = try service.initializeSync(InitializeRequest(
processId: pid,
rootPath: nil,
rootURI: workspace.rootUri,
initializationOptions: nil,
capabilities: workspace.capabilityRegistry.clientCapabilities,
trace: .off,
workspaceFolders: nil))
let languages = languageClass(for: language)
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")
}
service.clientInitialized(InitializedNotification())
languageServices[serverType, default: []].append(service)
return service
}
}
/// **Public for testing purposes only**
public func _languageService(for uri: DocumentURI, _ language: Language, in workspace: Workspace) -> ToolchainLanguageServer? {
return languageService(for: uri, language, in: workspace)
}
func languageService(for uri: DocumentURI, _ language: Language, in workspace: Workspace) -> ToolchainLanguageServer? {
if let service = workspace.documentService[uri] {
return service
}
guard let toolchain = toolchain(for: uri, language),
let service = languageService(for: toolchain, language, in: workspace)
else {
return nil
}
log("Using toolchain \(toolchain.displayName) (\(toolchain.identifier)) for \(uri)")
workspace.documentService[uri] = service
return service
}
}
// MARK: - Build System Delegate
extension SourceKitServer: 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: [DocumentURI: FileBuildSettingsChange]
) {
queue.async {
for (uri, change) in changedFiles {
// Non-ready documents should be considered open even though we haven't
// opened it with the language service yet.
guard self.documentManager.openDocuments.contains(uri) else { continue }
guard let workspace = self.workspaceForDocument(uri: uri) else {
continue
}
guard self.documentsReady.contains(uri) else {
// Case 1: initial settings for a given file. Now we can process our backlog.
log("Initial build settings received for opened file \(uri)")
guard let service = workspace.documentService[uri] else {
// Unexpected: we should have an existing language service if we've registered for
// change notifications for an opened but non-ready document.
log("No language service for build settings change to non-ready file \(uri)",
level: .error)
// We're in an odd state, cancel pending requests if we have any.
self.documentToPendingQueue[uri]?.cancelAll()
self.documentToPendingQueue[uri] = nil
continue
}
// Notify the language server so it can apply the proper arguments.
service.documentUpdatedBuildSettings(uri, change: change)
// Catch up on any queued notifications and requests.
self.documentToPendingQueue[uri]?.handleAll()
self.documentToPendingQueue[uri] = nil
self.documentsReady.insert(uri)
continue
}
// Case 2: changed settings for an already open file.
log("Build settings changed for opened file \(uri)")
if let service = workspace.documentService[uri] {
service.documentUpdatedBuildSettings(uri, change: change)
}
}
}
}
/// 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>) {
queue.async {
// Split the changedFiles into the workspaces they belong to.
// Then invoke affectedOpenDocumentsForChangeSet for each workspace with its affected files.
let changedFilesAndWorkspace = changedFiles.map({
return (uri: $0, workspace: 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) {
// Make sure the document is ready - otherwise the language service won't
// know about the document yet.
guard self.documentsReady.contains(uri) else {
continue
}
log("Dependencies updated for opened file \(uri)")
if let service = workspace.documentService[uri] {
service.documentDependenciesUpdated(uri)
}
}
}
}
}
public func fileHandlingCapabilityChanged() {
queue.async {
self.uriToWorkspaceCache = [:]
}
}
}
// MARK: - Request and notification handling
extension SourceKitServer {
// MARK: - General
/// Creates a workspace at the given `uri`.
private func workspace(uri: DocumentURI) -> Workspace? {
guard let capabilityRegistry = capabilityRegistry else {
log("Cannot open workspace before server is initialized")
return nil
}
return try? Workspace(
documentManager: self.documentManager,
rootUri: uri,
capabilityRegistry: capabilityRegistry,
toolchainRegistry: self.toolchainRegistry,
buildSetup: self.options.buildSetup,
indexOptions: self.options.indexOptions,
reloadPackageStatusCallback: { status in
self.queue.async {
switch status {
case .start:
self.packageLoadingWorkDoneProgress.startProgress(server: self)
case .end:
self.packageLoadingWorkDoneProgress.endProgress(server: self)
}
}
}
)
}
func initialize(_ req: Request<InitializeRequest>) {
if case .dictionary(let options) = req.params.initializationOptions {
if case .bool(let listenToUnitEvents) = options["listenToUnitEvents"] {
self.options.indexOptions.listenToUnitEvents = listenToUnitEvents
}
if case .dictionary(let completionOptions) = options["completion"] {
if case .bool(let serverSideFiltering) = completionOptions["serverSideFiltering"] {
self.options.completionOptions.serverSideFiltering = serverSideFiltering
}
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):
log("expected null or int for 'maxResults'; got \(invalid)", level: .warning)
}
}
}
capabilityRegistry = CapabilityRegistry(clientCapabilities: req.params.capabilities)
// Any messages sent before initialize returns are expected to fail, so this will run before
// the first "supported" request. Run asynchronously to hide the latency of setting up the
// build system and index.
queue.async {
if let workspaceFolders = req.params.workspaceFolders {
self.workspaces.append(contentsOf: workspaceFolders.compactMap({ self.workspace(uri: $0.uri) }))
} else if let uri = req.params.rootURI {
if let workspace = self.workspace(uri: uri) {
self.workspaces.append(workspace)
}
} else if let path = req.params.rootPath {
if let workspace = self.workspace(uri: DocumentURI(URL(fileURLWithPath: path))) {
self.workspaces.append(workspace)
}
}
if self.workspaces.isEmpty {
log("no workspace found", level: .warning)
let workspace = Workspace(
documentManager: self.documentManager,
rootUri: req.params.rootURI,
capabilityRegistry: self.capabilityRegistry!,
toolchainRegistry: self.toolchainRegistry,
buildSetup: self.options.buildSetup,
underlyingBuildSystem: nil,
index: nil,
indexDelegate: nil)
self.workspaces.append(workspace)
}
assert(!self.workspaces.isEmpty)
for workspace in self.workspaces {
workspace.buildSystemManager.delegate = self
}
}
req.reply(InitializeResult(capabilities:
self.serverCapabilities(for: req.params.capabilities, registry: self.capabilityRegistry!)))
}
func serverCapabilities(
for client: ClientCapabilities,
registry: CapabilityRegistry
) -> ServerCapabilities {
let completionOptions: CompletionOptions?
if registry.clientHasDynamicCompletionRegistration {
// We'll initialize this dynamically instead of statically.
completionOptions = nil
} else {
completionOptions = LanguageServerProtocol.CompletionOptions(
resolveProvider: false,
triggerCharacters: ["."]
)
}
let executeCommandOptions: ExecuteCommandOptions?
if registry.clientHasDynamicExecuteCommandRegistration {
executeCommandOptions = nil
} else {
executeCommandOptions = ExecuteCommandOptions(commands: builtinSwiftCommands)
}
return ServerCapabilities(
textDocumentSync: .options(TextDocumentSyncOptions(
openClose: true,
change: .incremental
)),
hoverProvider: .bool(true),
completionProvider: completionOptions,
definitionProvider: .bool(true),
implementationProvider: .bool(true),
referencesProvider: .bool(true),
documentHighlightProvider: .bool(true),
documentSymbolProvider: .bool(true),
workspaceSymbolProvider: .bool(true),
codeActionProvider: .value(CodeActionServerCapabilities(
clientCapabilities: client.textDocument?.codeAction,
codeActionOptions: CodeActionOptions(codeActionKinds: nil),
supportsCodeActions: true
)),
colorProvider: .bool(true),
foldingRangeProvider: .bool(!registry.clientHasDynamicFoldingRangeRegistration),
declarationProvider: .bool(true),
executeCommandProvider: executeCommandOptions,
workspace: WorkspaceServerCapabilities(workspaceFolders: .init(
supported: true,
changeNotifications: .bool(true)
)),
callHierarchyProvider: .bool(true),
typeHierarchyProvider: .bool(true)
)
}
func registerCapabilities(
for server: ServerCapabilities,
languages: [Language],
registry: CapabilityRegistry
) {
if let completionOptions = server.completionProvider {
registry.registerCompletionIfNeeded(options: completionOptions, for: languages) {
self.dynamicallyRegisterCapability($0, registry)
}
}
if server.foldingRangeProvider?.isSupported == true {
registry.registerFoldingRangeIfNeeded(options: FoldingRangeOptions(), for: languages) {
self.dynamicallyRegisterCapability($0, registry)
}
}
if let semanticTokensOptions = server.semanticTokensProvider {
registry.registerSemanticTokensIfNeeded(options: semanticTokensOptions, for: languages) {
self.dynamicallyRegisterCapability($0, registry)
}
}
if let inlayHintProvider = server.inlayHintProvider,
inlayHintProvider.isSupported {
let options: InlayHintOptions
switch inlayHintProvider {
case .bool(_):
options = InlayHintOptions()
case .value(let opts):
options = opts
}
registry.registerInlayHintIfNeeded(options: options, for: languages) {
self.dynamicallyRegisterCapability($0, registry)
}
}
if let diagnosticOptions = server.diagnosticProvider {
registry.registerDiagnosticIfNeeded(options: diagnosticOptions, for: languages) {
self.dynamicallyRegisterCapability($0, registry)
}
}
if let commandOptions = server.executeCommandProvider {
registry.registerExecuteCommandIfNeeded(commands: commandOptions.commands) {
self.dynamicallyRegisterCapability($0, registry)
}
}
/// This must be a superset of the files that return true for SwiftPM's `Workspace.fileAffectsSwiftOrClangBuildSettings`.
var watchers = FileRuleDescription.builtinRules.flatMap({ $0.fileTypes }).map { fileExtension in
return FileSystemWatcher(globPattern: "**/*.\(fileExtension)", kind: [.create, .delete])
}
watchers.append(FileSystemWatcher(globPattern: "**/Package.swift", kind: [.change]))
watchers.append(FileSystemWatcher(globPattern: "**/compile_commands.json", kind: [.create, .change, .delete]))
watchers.append(FileSystemWatcher(globPattern: "**/compile_flags.txt", kind: [.create, .change, .delete]))
registry.registerDidChangeWatchedFiles(watchers: watchers) {
self.dynamicallyRegisterCapability($0, registry)
}
}
private func dynamicallyRegisterCapability(
_ registration: CapabilityRegistration,
_ registry: CapabilityRegistry
) {
let req = RegisterCapabilityRequest(registrations: [registration])
let _ = client.send(req, queue: queue) { result in
if let error = result.failure {
log("Failed to dynamically register for \(registration.method): \(error)", level: .error)
registry.remove(registration: registration)
}
}
}
func clientInitialized(_: Notification<InitializedNotification>) {
// Nothing to do.
}
func cancelRequest(_ notification: Notification<CancelRequestNotification>) {
let key = RequestCancelKey(client: notification.clientID, request: notification.params.id)
requestCancellation[key]?.cancel()
}
/// The server is about to exit, and the server should flush any buffered state.
///
/// The server shall not be used to handle more requests (other than possibly
/// `shutdown` and `exit`) and should attempt to flush any buffered state
/// immediately, such as sending index changes to disk.
public func prepareForExit() {
// Note: this method should be safe to call multiple times, since we want to
// be resilient against multiple possible shutdown sequences, including
// pipe failure.
// Close the index, which will flush to disk.
self.queue.sync {
self._prepareForExit()
}
}
func _prepareForExit() {
dispatchPrecondition(condition: .onQueue(queue))
// Note: this method should be safe to call multiple times, since we want to
// be resilient against multiple possible shutdown sequences, including
// pipe failure.
// Close the index, which will flush to disk.
for workspace in self.workspaces {
workspace.buildSystemManager.mainFilesProvider = nil
workspace.index = nil
// Break retain cycle with the BSM.
workspace.buildSystemManager.delegate = nil
}
}
func shutdown(_ request: Request<ShutdownRequest>) {
_prepareForExit()
let shutdownGroup = DispatchGroup()
for service in languageServices.values.flatMap({ $0 }) {
shutdownGroup.enter()
service.shutdown() {
shutdownGroup.leave()
}
}
languageServices = [:]
// Wait for all services to shut down before sending the shutdown response.
// Otherwise we might terminate sourcekit-lsp while it still has open
// connections to the toolchain servers, which could send messages to
// sourcekit-lsp while it is being deallocated, causing crashes.
shutdownGroup.notify(queue: self.queue) {
request.reply(VoidResponse())
}
}
func exit(_ notification: Notification<ExitNotification>) {
// Should have been called in shutdown, but allow misbehaving clients.
_prepareForExit()
// Call onExit only once, and hop off queue to allow the handler to call us back.
let onExit = self.onExit
self.onExit = {}
DispatchQueue.global().async {
onExit()
}
}
// MARK: - Text synchronization
func openDocument(_ note: Notification<DidOpenTextDocumentNotification>) {
let uri = note.params.textDocument.uri
guard let workspace = workspaceForDocument(uri: uri) else {
log("received open notification for file '\(uri)' without a corresponding workspace, ignoring...", level: .error)
return
}
openDocument(note.params, workspace: workspace)
}
private func openDocument(_ note: DidOpenTextDocumentNotification, workspace: Workspace) {
// Immediately open the document even if the build system isn't ready. This is important since
// we check that the document is open when we receive messages from the build system.
documentManager.open(note)
let textDocument = note.textDocument
let uri = textDocument.uri
let language = textDocument.language
// If we can't create a service, this document is unsupported and we can bail here.
guard let service = languageService(for: uri, language, in: workspace) else {
return
}
workspace.buildSystemManager.registerForChangeNotifications(for: uri, language: language)
// If the document is ready, we can immediately send the notification.
guard !documentsReady.contains(uri) else {
service.openDocument(note)
return
}
// Need to queue the open call so we can handle it when ready.
self.documentToPendingQueue[uri, default: DocumentNotificationRequestQueue()].add(operation: {
service.openDocument(note)
})
}
func closeDocument(_ note: Notification<DidCloseTextDocumentNotification>) {
let uri = note.params.textDocument.uri
guard let workspace = workspaceForDocument(uri: uri) else {
log("received close notification for file '\(uri)' without a corresponding workspace, ignoring...", level: .error)
return
}
self.closeDocument(note.params, workspace: workspace)
}
func closeDocument(_ note: DidCloseTextDocumentNotification, workspace: Workspace) {
// Immediately close the document. We need to be sure to clear our pending work queue in case
// the build system still isn't ready.
documentManager.close(note)
let uri = note.textDocument.uri
workspace.buildSystemManager.unregisterForChangeNotifications(for: uri)
// If the document is ready, we can close it now.
guard !documentsReady.contains(uri) else {
self.documentsReady.remove(uri)
workspace.documentService[uri]?.closeDocument(note)
return
}
// Clear any queued notifications via their cancellation handlers.
// No need to send the notification since it was never considered opened.
self.documentToPendingQueue[uri]?.cancelAll()
self.documentToPendingQueue[uri] = nil
}
func changeDocument(_ note: Notification<DidChangeTextDocumentNotification>) {
let uri = note.params.textDocument.uri
guard let workspace = workspaceForDocument(uri: uri) else {
log("received change notification for file '\(uri)' without a corresponding workspace, ignoring...", level: .error)
return
}
// If the document is ready, we can handle the change right now.
guard !documentsReady.contains(uri) else {
documentManager.edit(note.params)
workspace.documentService[uri]?.changeDocument(note.params)
return
}
// Need to queue the change call so we can handle it when ready.
self.documentToPendingQueue[uri, default: DocumentNotificationRequestQueue()].add(operation: {