-
Notifications
You must be signed in to change notification settings - Fork 302
/
Copy pathSwiftPMIntegrationTests.swift
564 lines (514 loc) · 19.2 KB
/
SwiftPMIntegrationTests.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
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2019 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 BuildSystemIntegration
import Foundation
import LanguageServerProtocol
import SKTestSupport
import SourceKitLSP
import SwiftExtensions
import XCTest
final class SwiftPMIntegrationTests: XCTestCase {
func testSwiftPMIntegration() async throws {
try await SkipUnless.sourcekitdSupportsPlugin()
let project = try await SwiftPMTestProject(
files: [
"Lib.swift": """
struct Lib {
func 1️⃣foo() {}
}
""",
"Other.swift": """
func test() {
Lib().2️⃣foo()
}
""",
],
enableBackgroundIndexing: true
)
let (otherUri, otherPositions) = try project.openDocument("Other.swift")
let callPosition = otherPositions["2️⃣"]
let refs = try await project.testClient.send(
ReferencesRequest(
textDocument: TextDocumentIdentifier(otherUri),
position: callPosition,
context: ReferencesContext(includeDeclaration: true)
)
)
XCTAssertEqual(
Set(refs),
[
Location(uri: otherUri, range: Range(callPosition)),
Location(uri: try project.uri(for: "Lib.swift"), range: Range(try project.position(of: "1️⃣", in: "Lib.swift"))),
]
)
let completions = try await project.testClient.send(
CompletionRequest(textDocument: TextDocumentIdentifier(otherUri), position: callPosition)
)
XCTAssertEqual(
completions.items.clearingUnstableValues,
[
CompletionItem(
label: "foo()",
kind: .method,
detail: "Void",
deprecated: false,
sortText: nil,
filterText: "foo()",
insertText: "foo()",
insertTextFormat: .plain,
textEdit: .textEdit(
TextEdit(range: Range(callPosition), newText: "foo()")
)
),
CompletionItem(
label: "self",
kind: .keyword,
detail: "Lib",
deprecated: false,
sortText: nil,
filterText: "self",
insertText: "self",
insertTextFormat: .plain,
textEdit: .textEdit(
TextEdit(range: Range(callPosition), newText: "self")
)
),
]
)
}
func testAddFile() async throws {
try await SkipUnless.sourcekitdSupportsPlugin()
let project = try await SwiftPMTestProject(
files: [
"Lib.swift": """
struct Lib {
func foo() {
1️⃣
}
}
"""
],
enableBackgroundIndexing: true
)
let newFileUrl = project.scratchDirectory
.appendingPathComponent("Sources")
.appendingPathComponent("MyLibrary")
.appendingPathComponent("Other.swift")
let newFileUri = DocumentURI(newFileUrl)
let newFileContents = """
func baz(l: Lib) {
l.2️⃣foo()
}
"""
try await extractMarkers(newFileContents).textWithoutMarkers.writeWithRetry(to: newFileUrl)
// Check that we don't get cross-file code completion before we send a `DidChangeWatchedFilesNotification` to make
// sure we didn't include the file in the initial retrieval of build settings.
let (oldFileUri, oldFilePositions) = try project.openDocument("Lib.swift")
let newFilePositions = project.testClient.openDocument(newFileContents, uri: newFileUri)
let completionsBeforeDidChangeNotification = try await project.testClient.send(
CompletionRequest(textDocument: TextDocumentIdentifier(newFileUri), position: newFilePositions["2️⃣"])
)
XCTAssertEqual(completionsBeforeDidChangeNotification.items, [])
// Send a `DidChangeWatchedFilesNotification` and verify that we now get cross-file code completion.
project.testClient.send(
DidChangeWatchedFilesNotification(changes: [
FileEvent(uri: newFileUri, type: .created)
])
)
// Ensure that the DidChangeWatchedFilesNotification is handled before we continue.
try await project.testClient.send(SynchronizeRequest(index: true))
let completions = try await project.testClient.send(
CompletionRequest(textDocument: TextDocumentIdentifier(newFileUri), position: newFilePositions["2️⃣"])
)
XCTAssertEqual(
completions.items.clearingUnstableValues,
[
CompletionItem(
label: "foo()",
kind: .method,
detail: "Void",
deprecated: false,
sortText: nil,
filterText: "foo()",
insertText: "foo()",
insertTextFormat: .plain,
textEdit: .textEdit(
TextEdit(range: Range(newFilePositions["2️⃣"]), newText: "foo()")
)
),
CompletionItem(
label: "self",
kind: .keyword,
detail: "Lib",
deprecated: false,
sortText: nil,
filterText: "self",
insertText: "self",
insertTextFormat: .plain,
textEdit: .textEdit(
TextEdit(range: Range(newFilePositions["2️⃣"]), newText: "self")
)
),
]
)
// Check that we get code completion for `baz` (defined in the new file) in the old file.
// I.e. check that the existing file's build settings have been updated to include the new file.
let oldFileCompletions = try await project.testClient.send(
CompletionRequest(textDocument: TextDocumentIdentifier(oldFileUri), position: oldFilePositions["1️⃣"])
)
XCTAssert(oldFileCompletions.items.contains(where: { $0.label == "baz(l: Lib)" }))
}
func testNestedPackage() async throws {
try await SkipUnless.sourcekitdSupportsPlugin()
let project = try await MultiFileTestProject(files: [
"pkg/Sources/lib/lib.swift": "",
"pkg/Package.swift": """
// swift-tools-version:4.2
import PackageDescription
let package = Package(name: "a", products: [], dependencies: [],
targets: [.target(name: "lib", dependencies: [])])
""",
"nested/pkg/Sources/lib/a.swift.swift": """
struct Foo {
func bar() {}
}
""",
"nested/pkg/Sources/lib/b.swift": """
func test(foo: Foo) {
foo.1️⃣
}
""",
"nested/pkg/Package.swift": """
// swift-tools-version:4.2
import PackageDescription
let package = Package(name: "a", products: [], dependencies: [],
targets: [.target(name: "lib", dependencies: [])])
""",
])
let (uri, positions) = try project.openDocument("b.swift")
try await project.testClient.send(SynchronizeRequest(index: true))
let result = try await project.testClient.send(
CompletionRequest(textDocument: TextDocumentIdentifier(uri), position: positions["1️⃣"])
)
XCTAssertEqual(
result.items.clearingUnstableValues,
[
CompletionItem(
label: "bar()",
kind: .method,
detail: "Void",
deprecated: false,
filterText: "bar()",
insertText: "bar()",
insertTextFormat: .plain,
textEdit: .textEdit(TextEdit(range: positions["1️⃣"]..<positions["1️⃣"], newText: "bar()"))
),
CompletionItem(
label: "self",
kind: .keyword,
detail: "Foo",
deprecated: false,
filterText: "self",
insertText: "self",
insertTextFormat: .plain,
textEdit: .textEdit(TextEdit(range: positions["1️⃣"]..<positions["1️⃣"], newText: "self"))
),
]
)
}
func testWasm() async throws {
try await SkipUnless.canCompileForWasm()
let project = try await SwiftPMTestProject(
files: [
"/.sourcekit-lsp/config.json": """
{
"swiftPM": {
"triple": "wasm32-unknown-none-wasm"
}
}
""",
"Test.swift": """
#if arch(wasm32)
let _: UnsafeRawPointer = 1
#endif
""",
],
manifest: """
let package = Package(
name: "WasmTest",
targets: [
.executableTarget(
name: "wasmTest",
cSettings: [.unsafeFlags(["-fdeclspec"])],
swiftSettings: [
.enableExperimentalFeature("Embedded"),
.interoperabilityMode(.Cxx),
.unsafeFlags(["-wmo", "-disable-cmo", "-Xfrontend", "-gnone"]),
],
linkerSettings: [.unsafeFlags(["-Xclang-linker", "-nostdlib", "-Xlinker", "--no-entry"])]
)
]
)
"""
)
let (uri, _) = try project.openDocument("Test.swift")
let diagnostics = try await project.testClient.send(
DocumentDiagnosticsRequest(textDocument: TextDocumentIdentifier(uri))
)
XCTAssertEqual(
diagnostics.fullReport?.items.map(\.message),
["Cannot convert value of type 'Int' to specified type 'UnsafeRawPointer'"]
)
}
func testProvideSyntacticFunctionalityWhilePackageIsLoading() async throws {
let receivedDocumentSymbolsReply = WrappedSemaphore(name: "Received document symbols reply")
let project = try await SwiftPMTestProject(
files: [
"Test.swift": ""
],
hooks: Hooks(
buildSystemHooks: BuildSystemHooks(
swiftPMTestHooks: SwiftPMTestHooks(reloadPackageDidStart: {
receivedDocumentSymbolsReply.waitOrXCTFail()
})
)
),
pollIndex: false
)
let (uri, _) = try project.openDocument("Test.swift")
_ = try await project.testClient.send(DocumentSymbolRequest(textDocument: TextDocumentIdentifier(uri)))
receivedDocumentSymbolsReply.signal()
}
func testDiagnosticsGetRefreshedAfterPackageLoadingFinishes() async throws {
let receivedInitialDiagnosticsReply = WrappedSemaphore(name: "Received initial diagnostics reply")
let project = try await SwiftPMTestProject(
files: [
"Test.swift": """
let x: String = 1
"""
],
capabilities: ClientCapabilities(
workspace: WorkspaceClientCapabilities(diagnostics: RefreshRegistrationCapability(refreshSupport: true))
),
hooks: Hooks(
buildSystemHooks: BuildSystemHooks(
swiftPMTestHooks: SwiftPMTestHooks(reloadPackageDidStart: {
receivedInitialDiagnosticsReply.waitOrXCTFail()
})
)
),
pollIndex: false
)
let diagnosticRefreshRequestReceived = self.expectation(description: "DiagnosticsRefreshRequest received")
project.testClient.handleSingleRequest { (request: DiagnosticsRefreshRequest) in
diagnosticRefreshRequestReceived.fulfill()
return VoidResponse()
}
let (uri, _) = try project.openDocument("Test.swift")
let diagnosticsBeforePackageLoading = try await project.testClient.send(
DocumentDiagnosticsRequest(textDocument: TextDocumentIdentifier(uri))
)
XCTAssertEqual(diagnosticsBeforePackageLoading.fullReport?.items, [])
receivedInitialDiagnosticsReply.signal()
try await Task.sleep(for: .seconds(1))
try await fulfillmentOfOrThrow(diagnosticRefreshRequestReceived)
let diagnosticsAfterPackageLoading = try await project.testClient.send(
DocumentDiagnosticsRequest(textDocument: TextDocumentIdentifier(uri))
)
XCTAssertEqual(
diagnosticsAfterPackageLoading.fullReport?.items.map(\.message),
["Cannot convert value of type 'Int' to specified type 'String'"]
)
}
func testToolPluginWithBuild() async throws {
let project = try await SwiftPMTestProject(
files: [
"Plugins/plugin.swift": #"""
import PackagePlugin
@main struct CodeGeneratorPlugin: BuildToolPlugin {
func createBuildCommands(context: PluginContext, target: Target) throws -> [Command] {
let genSourcesDir = context.pluginWorkDirectoryURL.appending(path: "GeneratedSources")
guard let target = target as? SourceModuleTarget else { return [] }
let codeGenerator = try context.tool(named: "CodeGenerator").url
let generatedFile = genSourcesDir.appending(path: "\(target.name)-generated.swift")
return [.buildCommand(
displayName: "Generating code for \(target.name)",
executable: codeGenerator,
arguments: [
generatedFile.path
],
inputFiles: [],
outputFiles: [generatedFile]
)]
}
}
"""#,
"Sources/CodeGenerator/CodeGenerator.swift": #"""
import Foundation
try "let generated = 1".write(to: URL(fileURLWithPath: CommandLine.arguments[1]), atomically: true, encoding: String.Encoding.utf8)
"""#,
"Sources/TestLib/TestLib.swift": #"""
func useGenerated() {
_ = 1️⃣generated
}
"""#,
],
manifest: """
// swift-tools-version: 6.0
import PackageDescription
let package = Package(
name: "PluginTest",
targets: [
.executableTarget(name: "CodeGenerator"),
.target(
name: "TestLib",
plugins: [.plugin(name: "CodeGeneratorPlugin")]
),
.plugin(
name: "CodeGeneratorPlugin",
capability: .buildTool(),
dependencies: ["CodeGenerator"]
),
]
)
""",
enableBackgroundIndexing: false
)
let (uri, positions) = try project.openDocument("TestLib.swift")
let result = try await project.testClient.send(
DefinitionRequest(textDocument: TextDocumentIdentifier(uri), position: positions["1️⃣"])
)
// We cannot run plugins when not using background indexing, so we expect no result here.
XCTAssertNil(result)
}
func testToolPluginWithBackgroundIndexing() async throws {
try await SkipUnless.canLoadPluginsBuiltByToolchain()
let project = try await SwiftPMTestProject(
files: [
"Plugins/plugin.swift": #"""
import Foundation
import PackagePlugin
@main struct CodeGeneratorPlugin: BuildToolPlugin {
func createBuildCommands(context: PluginContext, target: Target) throws -> [Command] {
let genSourcesDir = context.pluginWorkDirectoryURL.appending(path: "GeneratedSources")
guard let target = target as? SourceModuleTarget else { return [] }
let codeGenerator = try context.tool(named: "CodeGenerator").url
let generatedFile = genSourcesDir.appending(path: "\(target.name)-generated.swift")
return [.buildCommand(
displayName: "Generating code for \(target.name)",
executable: codeGenerator,
arguments: [
generatedFile.path
],
inputFiles: [
URL(fileURLWithPath: "$TEST_DIR_BACKSLASH_ESCAPED/topDep.txt"),
URL(fileURLWithPath: "$TEST_DIR_BACKSLASH_ESCAPED/Sources/TestLib/targetDep.txt")
],
outputFiles: [generatedFile]
)]
}
}
"""#,
"Sources/CodeGenerator/CodeGenerator.swift": #"""
import Foundation
let topGenerated = try String(contentsOf: URL(fileURLWithPath: "$TEST_DIR_BACKSLASH_ESCAPED/topDep.txt"))
let targetGenerated = try String(contentsOf: URL(fileURLWithPath: "$TEST_DIR_BACKSLASH_ESCAPED/Sources/TestLib/targetDep.txt"))
try "\(topGenerated)\n\(targetGenerated)".write(
to: URL(fileURLWithPath: CommandLine.arguments[1]),
atomically: true,
encoding: String.Encoding.utf8
)
"""#,
"Sources/TestLib/TestLib.swift": #"""
func useGenerated() {
_ = 1️⃣topGenerated
_ = 2️⃣targetGenerated
}
"""#,
"/topDep.txt": "let topGenerated = 1",
"Sources/TestLib/targetDep.txt": "let targetGenerated = 1",
],
manifest: """
// swift-tools-version: 6.0
import PackageDescription
let package = Package(
name: "PluginTest",
targets: [
.executableTarget(name: "CodeGenerator"),
.target(
name: "TestLib",
plugins: [.plugin(name: "CodeGeneratorPlugin")]
),
.plugin(
name: "CodeGeneratorPlugin",
capability: .buildTool(),
dependencies: ["CodeGenerator"]
),
]
)
""",
enableBackgroundIndexing: true
)
let (uri, positions) = try project.openDocument("TestLib.swift")
// We should have run plugins and thus created generated.swift
do {
let topResult = try await project.testClient.send(
DefinitionRequest(textDocument: TextDocumentIdentifier(uri), position: positions["1️⃣"])
)
let topLocation = try XCTUnwrap(topResult?.locations?.only)
XCTAssertTrue(topLocation.uri.pseudoPath.hasSuffix("generated.swift"))
XCTAssertEqual(topLocation.range.lowerBound, Position(line: 0, utf16index: 4))
XCTAssertEqual(topLocation.range.upperBound, Position(line: 0, utf16index: 4))
let targetResult = try await project.testClient.send(
DefinitionRequest(textDocument: TextDocumentIdentifier(uri), position: positions["2️⃣"])
)
let targetLocation = try XCTUnwrap(targetResult?.locations?.only)
XCTAssertTrue(targetLocation.uri.pseudoPath.hasSuffix("generated.swift"))
XCTAssertEqual(targetLocation.range.lowerBound, Position(line: 1, utf16index: 4))
XCTAssertEqual(targetLocation.range.upperBound, Position(line: 1, utf16index: 4))
}
// Make a change to the top level input file of the plugin command
try await project.changeFileOnDisk(
"topDep.txt",
newMarkedContents: """
// some change
let topGenerated = 2
"""
)
try await project.testClient.send(SynchronizeRequest(index: true))
// Expect that the position has been updated in the dependency
try await repeatUntilExpectedResult {
let result = try await project.testClient.send(
DefinitionRequest(textDocument: TextDocumentIdentifier(uri), position: positions["1️⃣"])
)
let location = try XCTUnwrap(result?.locations?.only)
return location.range.lowerBound == Position(line: 1, utf16index: 4)
}
// Make a change to the target level input file of the plugin command
try await project.changeFileOnDisk(
"targetDep.txt",
newMarkedContents: """
// some change
let targetGenerated = 2
"""
)
try await project.testClient.send(SynchronizeRequest(index: true))
// Expect that the position has been updated in the dependency
try await repeatUntilExpectedResult {
let result = try await project.testClient.send(
DefinitionRequest(textDocument: TextDocumentIdentifier(uri), position: positions["2️⃣"])
)
let location = try XCTUnwrap(result?.locations?.only)
return location.range.lowerBound == Position(line: 3, utf16index: 4)
}
}
}