forked from swiftlang/sourcekit-lsp
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathBackgroundIndexingTests.swift
2645 lines (2396 loc) · 92.4 KB
/
BackgroundIndexingTests.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 - 2024 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 LanguageServerProtocol
import LanguageServerProtocolExtensions
import SKLogging
import SKOptions
import SKTestSupport
import SemanticIndex
import SourceKitLSP
import SwiftExtensions
import TSCExtensions
import ToolchainRegistry
import XCTest
import class TSCBasic.Process
final class BackgroundIndexingTests: XCTestCase {
func testBackgroundIndexingOfSingleFile() async throws {
let project = try await SwiftPMTestProject(
files: [
"MyFile.swift": """
func 1️⃣foo() {}
func 2️⃣bar() {
3️⃣foo()
}
"""
],
enableBackgroundIndexing: true
)
let (uri, positions) = try project.openDocument("MyFile.swift")
let prepare = try await project.testClient.send(
CallHierarchyPrepareRequest(textDocument: TextDocumentIdentifier(uri), position: positions["1️⃣"])
)
let initialItem = try XCTUnwrap(prepare?.only)
let calls = try await project.testClient.send(CallHierarchyIncomingCallsRequest(item: initialItem))
XCTAssertEqual(
calls,
[
CallHierarchyIncomingCall(
from: CallHierarchyItem(
name: "bar()",
kind: .function,
tags: nil,
uri: uri,
range: Range(positions["2️⃣"]),
selectionRange: Range(positions["2️⃣"]),
data: .dictionary([
"usr": .string("s:9MyLibrary3baryyF"),
"uri": .string(uri.stringValue),
])
),
fromRanges: [Range(positions["3️⃣"])]
)
]
)
}
func testBackgroundIndexingOfMultiFileModule() async throws {
let project = try await SwiftPMTestProject(
files: [
"MyFile.swift": """
func 1️⃣foo() {}
""",
"MyOtherFile.swift": """
func 2️⃣bar() {
3️⃣foo()
}
""",
],
enableBackgroundIndexing: true
)
let (uri, positions) = try project.openDocument("MyFile.swift")
let prepare = try await project.testClient.send(
CallHierarchyPrepareRequest(textDocument: TextDocumentIdentifier(uri), position: positions["1️⃣"])
)
let initialItem = try XCTUnwrap(prepare?.only)
let calls = try await project.testClient.send(CallHierarchyIncomingCallsRequest(item: initialItem))
XCTAssertEqual(
calls,
[
CallHierarchyIncomingCall(
from: CallHierarchyItem(
name: "bar()",
kind: .function,
tags: nil,
uri: try project.uri(for: "MyOtherFile.swift"),
range: Range(try project.position(of: "2️⃣", in: "MyOtherFile.swift")),
selectionRange: Range(try project.position(of: "2️⃣", in: "MyOtherFile.swift")),
data: .dictionary([
"usr": .string("s:9MyLibrary3baryyF"),
"uri": .string(try project.uri(for: "MyOtherFile.swift").stringValue),
])
),
fromRanges: [Range(try project.position(of: "3️⃣", in: "MyOtherFile.swift"))]
)
]
)
}
func testBackgroundIndexingOfMultiModuleProject() async throws {
let project = try await SwiftPMTestProject(
files: [
"LibA/MyFile.swift": """
public func 1️⃣foo() {}
""",
"LibB/MyOtherFile.swift": """
import LibA
func 2️⃣bar() {
3️⃣foo()
}
""",
],
manifest: """
let package = Package(
name: "MyLibrary",
targets: [
.target(name: "LibA"),
.target(name: "LibB", dependencies: ["LibA"]),
]
)
""",
enableBackgroundIndexing: true
)
let (uri, positions) = try project.openDocument("MyFile.swift")
let prepare = try await project.testClient.send(
CallHierarchyPrepareRequest(textDocument: TextDocumentIdentifier(uri), position: positions["1️⃣"])
)
let initialItem = try XCTUnwrap(prepare?.only)
let calls = try await project.testClient.send(CallHierarchyIncomingCallsRequest(item: initialItem))
XCTAssertEqual(
calls,
[
CallHierarchyIncomingCall(
from: CallHierarchyItem(
name: "bar()",
kind: .function,
tags: nil,
uri: try project.uri(for: "MyOtherFile.swift"),
range: Range(try project.position(of: "2️⃣", in: "MyOtherFile.swift")),
selectionRange: Range(try project.position(of: "2️⃣", in: "MyOtherFile.swift")),
data: .dictionary([
"usr": .string("s:4LibB3baryyF"),
"uri": .string(try project.uri(for: "MyOtherFile.swift").stringValue),
])
),
fromRanges: [Range(try project.position(of: "3️⃣", in: "MyOtherFile.swift"))]
)
]
)
}
func testBackgroundIndexingHappensWithLowPriority() async throws {
var testHooks = Hooks()
testHooks.indexHooks.preparationTaskDidFinish = { taskDescription in
XCTAssert(Task.currentPriority == .low, "\(taskDescription) ran with priority \(Task.currentPriority)")
}
testHooks.indexHooks.updateIndexStoreTaskDidFinish = { taskDescription in
XCTAssert(Task.currentPriority == .low, "\(taskDescription) ran with priority \(Task.currentPriority)")
}
let project = try await SwiftPMTestProject(
files: [
"LibA/MyFile.swift": """
public func 1️⃣foo() {}
""",
"LibB/MyOtherFile.swift": """
import LibA
func 2️⃣bar() {
3️⃣foo()
}
""",
],
manifest: """
let package = Package(
name: "MyLibrary",
targets: [
.target(name: "LibA"),
.target(name: "LibB", dependencies: ["LibA"]),
]
)
""",
hooks: testHooks,
enableBackgroundIndexing: true,
pollIndex: false
)
// Wait for indexing to finish without elevating the priority
let semaphore = WrappedSemaphore(name: "Indexing finished")
let testClient = project.testClient
Task(priority: .low) {
await assertNoThrow {
try await testClient.send(SynchronizeRequest(index: true))
}
semaphore.signal()
}
try semaphore.waitOrThrow()
}
func testBackgroundIndexingOfPackageDependency() async throws {
let dependencyContents = """
public func 1️⃣doSomething() {}
"""
let dependencyProject = try await SwiftPMDependencyProject(files: [
"Sources/MyDependency/MyDependency.swift": dependencyContents
])
defer { dependencyProject.keepAlive() }
let project = try await SwiftPMTestProject(
files: [
"Test.swift": """
import MyDependency
func 2️⃣test() {
3️⃣doSomething()
}
"""
],
manifest: """
let package = Package(
name: "MyLibrary",
dependencies: [.package(url: "\(dependencyProject.packageDirectory)", from: "1.0.0")],
targets: [
.target(
name: "MyLibrary",
dependencies: [.product(name: "MyDependency", package: "MyDependency")]
)
]
)
""",
enableBackgroundIndexing: true
)
let dependencyUrl = try XCTUnwrap(
FileManager.default.findFiles(
named: "MyDependency.swift",
in: project.scratchDirectory.appendingPathComponent(".build").appendingPathComponent("index-build")
.appendingPathComponent("checkouts")
).only
)
let dependencyUri = DocumentURI(dependencyUrl)
let testFileUri = try project.uri(for: "Test.swift")
let positions = project.testClient.openDocument(dependencyContents, uri: dependencyUri)
let prepare = try await project.testClient.send(
CallHierarchyPrepareRequest(textDocument: TextDocumentIdentifier(dependencyUri), position: positions["1️⃣"])
)
let calls = try await project.testClient.send(
CallHierarchyIncomingCallsRequest(item: try XCTUnwrap(prepare?.only))
)
XCTAssertEqual(
calls,
[
CallHierarchyIncomingCall(
from: CallHierarchyItem(
name: "test()",
kind: .function,
tags: nil,
uri: testFileUri,
range: try project.range(from: "2️⃣", to: "2️⃣", in: "Test.swift"),
selectionRange: try project.range(from: "2️⃣", to: "2️⃣", in: "Test.swift"),
data: .dictionary([
"usr": .string("s:9MyLibrary4testyyF"),
"uri": .string(testFileUri.stringValue),
])
),
fromRanges: [try project.range(from: "3️⃣", to: "3️⃣", in: "Test.swift")]
)
]
)
}
func testIndexCFile() async throws {
let project = try await SwiftPMTestProject(
files: [
"MyLibrary/include/destination.h": "",
"MyFile.c": """
void 1️⃣someFunc() {}
void 2️⃣test() {
3️⃣someFunc();
}
""",
],
enableBackgroundIndexing: true
)
let (uri, positions) = try project.openDocument("MyFile.c")
let prepare = try await project.testClient.send(
CallHierarchyPrepareRequest(textDocument: TextDocumentIdentifier(uri), position: positions["1️⃣"])
)
let calls = try await project.testClient.send(
CallHierarchyIncomingCallsRequest(item: try XCTUnwrap(prepare?.only))
)
XCTAssertEqual(
calls,
[
CallHierarchyIncomingCall(
from: CallHierarchyItem(
name: "test",
kind: .function,
tags: nil,
uri: uri,
range: Range(positions["2️⃣"]),
selectionRange: Range(positions["2️⃣"]),
data: .dictionary([
"usr": .string("c:@F@test"),
"uri": .string(uri.stringValue),
])
),
fromRanges: [Range(positions["3️⃣"])]
)
]
)
}
func testBackgroundIndexingStatusWorkDoneProgress() async throws {
let receivedBeginProgressNotification = WrappedSemaphore(
name: "Received work done progress saying build graph generation"
)
let receivedReportProgressNotification = WrappedSemaphore(
name: "Received work done progress saying indexing"
)
var testHooks = Hooks()
testHooks.indexHooks = IndexHooks(
buildGraphGenerationDidFinish: {
receivedBeginProgressNotification.waitOrXCTFail()
},
updateIndexStoreTaskDidFinish: { _ in
receivedReportProgressNotification.waitOrXCTFail()
}
)
let project = try await SwiftPMTestProject(
files: [
"MyFile.swift": """
func foo() {}
func bar() {
foo()
}
"""
],
capabilities: ClientCapabilities(window: WindowClientCapabilities(workDoneProgress: true)),
hooks: testHooks,
enableBackgroundIndexing: true,
pollIndex: false,
preInitialization: { testClient in
testClient.handleMultipleRequests { (request: CreateWorkDoneProgressRequest) in
return VoidResponse()
}
}
)
let beginNotification = try await project.testClient.nextNotification(
ofType: WorkDoneProgress.self,
satisfying: { notification in
guard case .begin(let data) = notification.value else {
return false
}
return data.title == "Indexing"
}
)
receivedBeginProgressNotification.signal()
guard case .begin(let beginData) = beginNotification.value else {
XCTFail("Expected begin notification")
return
}
XCTAssertEqual(beginData.message, "Scheduling tasks")
let indexingWorkDoneProgressToken = beginNotification.token
_ = try await project.testClient.nextNotification(
ofType: WorkDoneProgress.self,
satisfying: { notification in
guard notification.token == indexingWorkDoneProgressToken,
case .report(let reportData) = notification.value,
reportData.message == "0 / 1"
else {
return false
}
return true
}
)
receivedReportProgressNotification.signal()
_ = try await project.testClient.nextNotification(
ofType: WorkDoneProgress.self,
satisfying: { notification in
guard notification.token == indexingWorkDoneProgressToken, case .end = notification.value else {
return false
}
return true
}
)
withExtendedLifetime(project) {}
}
func testBackgroundIndexingReindexesWhenSwiftFileIsModified() async throws {
let project = try await SwiftPMTestProject(
files: [
"MyFile.swift": """
func 1️⃣foo() {}
""",
"MyOtherFile.swift": "",
],
enableBackgroundIndexing: true
)
let (uri, positions) = try project.openDocument("MyFile.swift")
let prepare = try await project.testClient.send(
CallHierarchyPrepareRequest(textDocument: TextDocumentIdentifier(uri), position: positions["1️⃣"])
)
let callsBeforeEdit = try await project.testClient.send(
CallHierarchyIncomingCallsRequest(item: try XCTUnwrap(prepare?.only))
)
XCTAssertEqual(callsBeforeEdit, [])
let (otherFileUri, otherFilePositions) = try await project.changeFileOnDisk(
"MyOtherFile.swift",
newMarkedContents: """
func 2️⃣bar() {
3️⃣foo()
}
"""
)
try await project.testClient.send(SynchronizeRequest(index: true))
let callsAfterEdit = try await project.testClient.send(
CallHierarchyIncomingCallsRequest(item: try XCTUnwrap(prepare?.only))
)
XCTAssertEqual(
callsAfterEdit,
[
CallHierarchyIncomingCall(
from: CallHierarchyItem(
name: "bar()",
kind: .function,
tags: nil,
uri: otherFileUri,
range: Range(otherFilePositions["2️⃣"]),
selectionRange: Range(otherFilePositions["2️⃣"]),
data: .dictionary([
"usr": .string("s:9MyLibrary3baryyF"),
"uri": .string(otherFileUri.stringValue),
])
),
fromRanges: [Range(otherFilePositions["3️⃣"])]
)
]
)
}
func testBackgroundIndexingReindexesHeader() async throws {
let project = try await SwiftPMTestProject(
files: [
"MyLibrary/include/Header.h": """
void 1️⃣someFunc();
""",
"MyFile.c": """
#include "Header.h"
""",
],
enableBackgroundIndexing: true
)
let (uri, positions) = try project.openDocument("Header.h", language: .c)
let prepare = try await project.testClient.send(
CallHierarchyPrepareRequest(textDocument: TextDocumentIdentifier(uri), position: positions["1️⃣"])
)
let callsBeforeEdit = try await project.testClient.send(
CallHierarchyIncomingCallsRequest(item: try XCTUnwrap(prepare?.only))
)
XCTAssertEqual(callsBeforeEdit, [])
let (_, newPositions) = try await project.changeFileOnDisk(
"Header.h",
newMarkedContents: """
void someFunc();
void 2️⃣test() {
3️⃣someFunc();
};
"""
)
try await project.testClient.send(SynchronizeRequest(index: true))
let callsAfterEdit = try await project.testClient.send(
CallHierarchyIncomingCallsRequest(item: try XCTUnwrap(prepare?.only))
)
XCTAssertEqual(
callsAfterEdit,
[
CallHierarchyIncomingCall(
from: CallHierarchyItem(
name: "test",
kind: .function,
tags: nil,
uri: uri,
range: Range(newPositions["2️⃣"]),
selectionRange: Range(newPositions["2️⃣"]),
data: .dictionary([
"usr": .string("c:@F@test"),
"uri": .string(uri.stringValue),
])
),
fromRanges: [Range(newPositions["3️⃣"])]
)
]
)
}
func testPrepareTargetAfterEditToDependency() async throws {
var testHooks = Hooks()
let expectedPreparationTracker = ExpectedIndexTaskTracker(expectedPreparations: [
[
try ExpectedPreparation(target: "LibA", destination: .target),
try ExpectedPreparation(target: "LibB", destination: .target),
],
[
try ExpectedPreparation(target: "LibB", destination: .target)
],
])
testHooks.indexHooks = expectedPreparationTracker.testHooks
let project = try await SwiftPMTestProject(
files: [
"LibA/MyFile.swift": "",
"LibB/MyOtherFile.swift": """
import LibA
func bar() {
1️⃣foo2️⃣()
}
""",
],
manifest: """
let package = Package(
name: "MyLibrary",
targets: [
.target(name: "LibA"),
.target(name: "LibB", dependencies: ["LibA"]),
]
)
""",
capabilities: ClientCapabilities(
workspace: WorkspaceClientCapabilities(diagnostics: RefreshRegistrationCapability(refreshSupport: true)),
window: WindowClientCapabilities(workDoneProgress: true)
),
hooks: testHooks,
enableBackgroundIndexing: true,
cleanUp: { expectedPreparationTracker.keepAlive() }
)
let (uri, _) = try project.openDocument("MyOtherFile.swift")
let initialDiagnostics = try await project.testClient.send(
DocumentDiagnosticsRequest(textDocument: TextDocumentIdentifier(uri))
)
XCTAssertNotEqual(initialDiagnostics.fullReport?.items, [])
try await project.changeFileOnDisk("MyFile.swift", newMarkedContents: "public func foo() {}")
let receivedEmptyDiagnostics = self.expectation(description: "Received diagnostic refresh request")
receivedEmptyDiagnostics.assertForOverFulfill = false
project.testClient.handleMultipleRequests { (_: CreateWorkDoneProgressRequest) in
return VoidResponse()
}
let testClient = project.testClient
project.testClient.handleMultipleRequests { [weak testClient] (_: DiagnosticsRefreshRequest) in
Task { [weak testClient] in
let updatedDiagnostics = try await testClient?.send(
DocumentDiagnosticsRequest(textDocument: TextDocumentIdentifier(uri))
)
guard case .full(let updatedDiagnostics) = updatedDiagnostics else {
XCTFail("Expected full diagnostics")
return
}
if updatedDiagnostics.items.isEmpty {
receivedEmptyDiagnostics.fulfill()
}
}
return VoidResponse()
}
// Send a document request for `uri` to trigger re-preparation of its target. We don't actually care about the
// response for this request. Instead, we wait until SourceKit-LSP sends us a `DiagnosticsRefreshRequest`,
// indicating that the target of `uri` has been prepared.
_ = try await project.testClient.send(
DocumentDiagnosticsRequest(textDocument: TextDocumentIdentifier(uri))
)
try await fulfillmentOfOrThrow(receivedEmptyDiagnostics)
// Check that we received a work done progress for the re-preparation of the target
_ = try await project.testClient.nextNotification(
ofType: WorkDoneProgress.self,
satisfying: { notification in
switch notification.value {
case .begin(let value): return value.message == "Preparing current file"
case .report(let value): return value.message == "Preparing current file"
case .end: return false
}
}
)
}
func testDontStackTargetPreparationForEditorFunctionality() async throws {
let allDocumentsOpened = WrappedSemaphore(name: "All documents opened")
let libBStartedPreparation = WrappedSemaphore(name: "LibB started preparing")
let libDPreparedForEditing = WrappedSemaphore(name: "LibD prepared for editing")
var testHooks = Hooks()
let expectedPreparationTracker = ExpectedIndexTaskTracker(expectedPreparations: [
// Preparation of targets during the initial of the target
[
try ExpectedPreparation(target: "LibA", destination: .target),
try ExpectedPreparation(target: "LibB", destination: .target),
try ExpectedPreparation(target: "LibC", destination: .target),
try ExpectedPreparation(target: "LibD", destination: .target),
],
// LibB's preparation has already started by the time we browse through the other files, so we finish its preparation
[
try ExpectedPreparation(
target: "LibB",
destination: .target,
didStart: { libBStartedPreparation.signal() },
didFinish: { allDocumentsOpened.waitOrXCTFail() }
)
],
// And now we just want to prepare LibD, and not LibC
[
try ExpectedPreparation(
target: "LibD",
destination: .target,
didFinish: { libDPreparedForEditing.signal() }
)
],
])
testHooks.indexHooks = expectedPreparationTracker.testHooks
let project = try await SwiftPMTestProject(
files: [
"LibA/LibA.swift": "",
"LibB/LibB.swift": "",
"LibC/LibC.swift": "",
"LibD/LibD.swift": "",
],
manifest: """
let package = Package(
name: "MyLibrary",
targets: [
.target(name: "LibA"),
.target(name: "LibB", dependencies: ["LibA"]),
.target(name: "LibC", dependencies: ["LibA"]),
.target(name: "LibD", dependencies: ["LibA"]),
]
)
""",
hooks: testHooks,
enableBackgroundIndexing: true,
cleanUp: { expectedPreparationTracker.keepAlive() }
)
// Clean the preparation status of all libraries
project.testClient.send(
DidChangeWatchedFilesNotification(changes: [FileEvent(uri: try project.uri(for: "LibA.swift"), type: .changed)])
)
// Ensure that we handle the `DidChangeWatchedFilesNotification`.
try await project.testClient.send(SynchronizeRequest())
// Quickly flip through all files. The way the test is designed to work is as follows:
// - LibB.swift gets opened and prepared. Preparation is simulated to take a long time until both LibC.swift and
// LibD.swift have been opened.
// - LibC.swift gets opened. This queues preparation of LibC but doesn't cancel preparation of LibB because we
// don't cancel in-progress preparation tasks to guarantee forward progress (see comment at the end of
// `SemanticIndexManager.prepare`).
// - Now LibD.swift gets opened. This cancels preparation of LibC which actually cancels LibC's preparation for
// real because LibC's preparation hasn't started yet (it's only queued).
// Thus, the only targets that are being prepared are LibB and LibD, which is checked by the
// `ExpectedIndexTaskTracker`.
_ = try project.openDocument("LibB.swift")
try libBStartedPreparation.waitOrThrow()
_ = try project.openDocument("LibC.swift")
// Ensure that LibC gets opened before LibD, so that LibD is the latest document. Two open requests don't have
// dependencies between each other, so SourceKit-LSP is free to execute them in parallel or re-order them without
// the barrier.
try await project.testClient.send(SynchronizeRequest())
_ = try project.openDocument("LibD.swift")
// Send a barrier request to ensure we have finished opening LibD before allowing the preparation of LibB to finish.
try await project.testClient.send(SynchronizeRequest())
allDocumentsOpened.signal()
try libDPreparedForEditing.waitOrThrow()
}
func testProduceIndexLog() async throws {
let didReceivePreparationIndexLogMessage = WrappedSemaphore(name: "Did receive preparation log message")
let didReceiveIndexingLogMessage = WrappedSemaphore(name: "Did receive indexing log message")
let updateIndexStoreTaskDidFinish = WrappedSemaphore(name: "Update index store task did finish")
// Block the index tasks until we have received a log notification to make sure we stream out results as they come
// in and not only when the indexing task has finished
var testHooks = Hooks()
testHooks.indexHooks.preparationTaskDidFinish = { _ in
didReceivePreparationIndexLogMessage.waitOrXCTFail()
}
testHooks.indexHooks.updateIndexStoreTaskDidFinish = { _ in
didReceiveIndexingLogMessage.waitOrXCTFail()
updateIndexStoreTaskDidFinish.signal()
}
let project = try await SwiftPMTestProject(
files: [
"MyFile.swift": ""
],
hooks: testHooks,
enableBackgroundIndexing: true,
pollIndex: false
)
_ = try await project.testClient.nextNotification(
ofType: LogMessageNotification.self,
satisfying: { notification in
return notification.message.contains("Preparing MyLibrary")
}
)
didReceivePreparationIndexLogMessage.signal()
_ = try await project.testClient.nextNotification(
ofType: LogMessageNotification.self,
satisfying: { notification in
notification.message.contains("Indexing \(try project.uri(for: "MyFile.swift").pseudoPath)")
}
)
didReceiveIndexingLogMessage.signal()
try updateIndexStoreTaskDidFinish.waitOrThrow()
}
func testProduceIndexLogWithTaskID() async throws {
let project = try await SwiftPMTestProject(
files: ["MyFile.swift": ""],
options: .testDefault(experimentalFeatures: [.structuredLogs]),
enableBackgroundIndexing: true,
pollIndex: false
)
var inProgressMessagesByTaskID: [String: String] = [:]
var finishedMessagesByTaskID: [String: String] = [:]
while true {
let notification = try await project.testClient.nextNotification(
ofType: LogMessageNotification.self,
satisfying: { $0.logName == "SourceKit-LSP: Indexing" }
)
switch notification.structure {
case .begin(let begin):
XCTAssertNil(inProgressMessagesByTaskID[begin.taskID])
inProgressMessagesByTaskID[begin.taskID] = begin.title + "\n" + notification.message + "\n"
case .report(let report):
XCTAssertNotNil(inProgressMessagesByTaskID[report.taskID])
inProgressMessagesByTaskID[report.taskID]?.append(notification.message + "\n")
case .end(let end):
finishedMessagesByTaskID[end.taskID] =
try XCTUnwrap(inProgressMessagesByTaskID[end.taskID]) + notification.message
inProgressMessagesByTaskID[end.taskID] = nil
case nil:
break
}
if let indexingTask = finishedMessagesByTaskID.values.first(where: { $0.contains("Indexing ") }),
let prepareTask = finishedMessagesByTaskID.values.first(where: { $0.contains("Preparing ") }),
indexingTask.contains("Finished"),
prepareTask.contains("Finished")
{
// We have two finished tasks, one for preparation, one for indexing, which is what we expect.
break
}
}
}
func testIndexingHappensInParallel() async throws {
let fileAIndexingStarted = WrappedSemaphore(name: "FileA indexing started")
let fileBIndexingStarted = WrappedSemaphore(name: "FileB indexing started")
var testHooks = Hooks()
let expectedIndexTaskTracker = ExpectedIndexTaskTracker(
expectedIndexStoreUpdates: [
[
ExpectedIndexStoreUpdate(
sourceFileName: "FileA.swift",
didStart: {
fileAIndexingStarted.signal()
},
didFinish: {
fileBIndexingStarted.waitOrXCTFail()
}
),
ExpectedIndexStoreUpdate(
sourceFileName: "FileB.swift",
didStart: {
fileBIndexingStarted.signal()
},
didFinish: {
fileAIndexingStarted.waitOrXCTFail()
}
),
]
]
)
testHooks.indexHooks = expectedIndexTaskTracker.testHooks
_ = try await SwiftPMTestProject(
files: [
"FileA.swift": "",
"FileB.swift": "",
],
hooks: testHooks,
enableBackgroundIndexing: true,
cleanUp: { expectedIndexTaskTracker.keepAlive() }
)
}
func testNoIndexingHappensWhenPackageIsReopened() async throws {
let project = try await SwiftPMTestProject(
files: [
"SwiftLib/NonEmptySwiftFile.swift": """
func test() {}
""",
"CLib/include/EmptyHeader.h": "",
"CLib/Assembly.S": "",
"CLib/EmptyC.c": "",
"CLib/NonEmptyC.c": """
void test() {}
""",
],
manifest: """
let package = Package(
name: "MyLibrary",
targets: [
.target(name: "SwiftLib"),
.target(name: "CLib"),
]
)
""",
enableBackgroundIndexing: true
)
var otherClientOptions = Hooks()
otherClientOptions.indexHooks = IndexHooks(
preparationTaskDidStart: { taskDescription in
XCTFail("Did not expect any target preparation, got \(taskDescription.targetsToPrepare)")
},
updateIndexStoreTaskDidStart: { taskDescription in
XCTFail("Did not expect any indexing tasks, got \(taskDescription.filesToIndex)")
}
)
let otherClient = try await TestSourceKitLSPClient(
hooks: otherClientOptions,
enableBackgroundIndexing: true,
workspaceFolders: [
WorkspaceFolder(uri: DocumentURI(project.scratchDirectory))
]
)
try await otherClient.send(SynchronizeRequest(index: true))
}
func testOpeningFileThatIsNotPartOfThePackageDoesntGenerateABuildFolderThere() async throws {
let project = try await SwiftPMTestProject(
files: [
"Lib.swift": "",
"OtherLib/OtherLib.swift": "",
],
enableBackgroundIndexing: true
)
_ = try project.openDocument("OtherLib.swift")
// Wait for 1 second to increase the likelihood of this test failing in case we would start scheduling some
// background task that causes a build in the `OtherLib` directory.
try await Task.sleep(for: .seconds(1))
let nestedIndexBuildURL = try XCTUnwrap(
project.uri(for: "OtherLib.swift").fileURL?
.deletingLastPathComponent()
.appendingPathComponent(".build")
.appendingPathComponent("index-build")
)
XCTAssertFalse(
FileManager.default.fileExists(at: nestedIndexBuildURL),
"No file should exist at \(nestedIndexBuildURL)"
)
}
func testNoPreparationStatusIfTargetIsUpToDate() async throws {
let project = try await SwiftPMTestProject(
files: [
"Lib.swift": ""
],
capabilities: ClientCapabilities(window: WindowClientCapabilities(workDoneProgress: true)),
enableBackgroundIndexing: true
)
// Opening the document prepares it for editor functionality. Its target is already prepared, so we shouldn't show
// a work done progress for it.
project.testClient.handleSingleRequest { (request: CreateWorkDoneProgressRequest) in
XCTFail("Received unexpected create work done progress: \(request)")
return VoidResponse()
}
_ = try project.openDocument("Lib.swift")
try await project.testClient.send(SynchronizeRequest())
}
func testImportPreparedModuleWithFunctionBodiesSkipped() async throws {
// This test case was crashing the indexing compiler invocation for Client if Lib was built for index preparation
// (using `-enable-library-evolution -experimental-skip-all-function-bodies -experimental-lazy-typecheck`) but the
// Client was not indexed with `-experimental-allow-module-with-compiler-errors`. rdar://129071600
let project = try await SwiftPMTestProject(
files: [
"Lib/Lib.swift": """
public class TerminalController {
public var 1️⃣width: Int { 1 }
}
""",
"Client/Client.swift": """
import Lib
func test(terminal: TerminalController) {
let width = terminal.width
}
""",
],
manifest: """
let package = Package(
name: "MyLibrary",
targets: [
.target(name: "Lib"),
.target(name: "Client", dependencies: ["Lib"]),
]
)
""",
enableBackgroundIndexing: true
)
let (uri, positions) = try project.openDocument("Lib.swift")
// Check that we indexed `Client.swift` by checking that we return a rename location within it.
let result = try await project.testClient.send(
RenameRequest(textDocument: TextDocumentIdentifier(uri), position: positions["1️⃣"], newName: "height")
)
XCTAssertEqual((result?.changes?.keys).map(Set.init), [uri, try project.uri(for: "Client.swift")])
}
func testDontPreparePackageManifest() async throws {
let project = try await SwiftPMTestProject(
files: [
"Lib.swift": ""
],
enableBackgroundIndexing: true
)
_ = try await project.testClient.nextNotification(
ofType: LogMessageNotification.self,
satisfying: { $0.message.contains("Preparing MyLibrary") }
)
// Opening the package manifest shouldn't cause any `swift build` calls to prepare them because they are not part of
// a target that can be prepared.
let (uri, _) = try project.openDocument("Package.swift")
_ = try await project.testClient.send(DocumentDiagnosticsRequest(textDocument: TextDocumentIdentifier(uri)))
try await project.testClient.assertDoesNotReceiveNotification(
ofType: LogMessageNotification.self,
satisfying: { $0.message.contains("Preparing") }
)
}
func testUseBuildFlagsDuringPreparation() async throws {
var options = try await SourceKitLSPOptions.testDefault()
options.swiftPMOrDefault.swiftCompilerFlags = ["-D", "MY_FLAG"]
let project = try await SwiftPMTestProject(
files: [
"Lib/Lib.swift": """
#if MY_FLAG
public func foo() -> Int { 1 }
#endif
""",
"Client/Client.swift": """
import Lib
func test() -> String {