File: PullDiagnosticsTests.swift

package info (click to toggle)
swiftlang 6.1.3-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 2,791,532 kB
  • sloc: cpp: 9,901,743; ansic: 2,201,431; asm: 1,091,827; python: 308,252; objc: 82,166; f90: 80,126; lisp: 38,358; pascal: 25,559; sh: 20,429; ml: 5,058; perl: 4,745; makefile: 4,484; awk: 3,535; javascript: 3,018; xml: 918; fortran: 664; cs: 573; ruby: 396
file content (408 lines) | stat: -rw-r--r-- 14,768 bytes parent folder | download
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
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2021 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 LanguageServerProtocol
import LanguageServerProtocolExtensions
import LanguageServerProtocolJSONRPC
import SKLogging
import SKTestSupport
import SemanticIndex
import SourceKitLSP
import SwiftExtensions
import XCTest

#if os(Windows)
import WinSDK
#elseif canImport(Android)
import Android
#endif

final class PullDiagnosticsTests: XCTestCase {
  func testUnknownIdentifierDiagnostic() async throws {
    let testClient = try await TestSourceKitLSPClient()
    let uri = DocumentURI(for: .swift)

    testClient.openDocument(
      """
      func foo() {
        invalid
      }
      """,
      uri: uri
    )

    let report = try await testClient.send(DocumentDiagnosticsRequest(textDocument: TextDocumentIdentifier(uri)))

    XCTAssertEqual(report.fullReport?.items.count, 1)
    let diagnostic = try XCTUnwrap(report.fullReport?.items.first)
    XCTAssertEqual(diagnostic.range, Position(line: 1, utf16index: 2)..<Position(line: 1, utf16index: 9))
  }

  func testDiagnosticsIfFileIsOpenedWithLowercaseDriveLetter() async throws {
    try SkipUnless.platformIsWindows("Drive letters only exist on Windows")

    let fileContents = """
      func foo() {
        invalid
      }
      """

    // We use `IndexedSingleSwiftFileTestProject` so that the test file exists on disk, which causes sourcekitd to
    // uppercase the drive letter.
    let project = try await IndexedSingleSwiftFileTestProject(fileContents, allowBuildFailure: true)
    project.testClient.send(DidCloseTextDocumentNotification(textDocument: TextDocumentIdentifier(project.fileURI)))

    let filePath = try XCTUnwrap(project.fileURI.fileURL?.filePath)
    XCTAssertEqual(filePath[filePath.index(filePath.startIndex, offsetBy: 1)], ":")
    let lowercaseDriveLetterPath = filePath.first!.lowercased() + filePath.dropFirst()
    let uri = DocumentURI(filePath: lowercaseDriveLetterPath, isDirectory: false)
    project.testClient.openDocument(fileContents, uri: uri)

    let report = try await project.testClient.send(
      DocumentDiagnosticsRequest(textDocument: TextDocumentIdentifier(uri))
    )

    XCTAssertEqual(report.fullReport?.items.count, 1)
    let diagnostic = try XCTUnwrap(report.fullReport?.items.first)
    XCTAssertEqual(diagnostic.range, Position(line: 1, utf16index: 2)..<Position(line: 1, utf16index: 9))
  }

  /// Test that we can get code actions for pulled diagnostics (https://github.com/swiftlang/sourcekit-lsp/issues/776)
  func testCodeActions() async throws {
    let testClient = try await TestSourceKitLSPClient(
      capabilities: ClientCapabilities(
        workspace: nil,
        textDocument: .init(
          codeAction: .init(codeActionLiteralSupport: .init(codeActionKind: .init(valueSet: [.quickFix])))
        )
      )
    )
    let uri = DocumentURI(for: .swift)

    let positions = testClient.openDocument(
      """
      protocol MyProtocol {
        func bar()
      }

      struct 1️⃣Test: 2️⃣MyProtocol {}
      """,
      uri: uri
    )
    let report = try await testClient.send(DocumentDiagnosticsRequest(textDocument: TextDocumentIdentifier(uri)))
    let diagnostics = try XCTUnwrap(report.fullReport?.items)

    let diagnostic = try XCTUnwrap(diagnostics.only)
    XCTAssert(
      diagnostic.range == Range(positions["1️⃣"]) || diagnostic.range == Range(positions["2️⃣"]),
      "Unexpected range: \(diagnostic.range)"
    )
    let note = try XCTUnwrap(diagnostic.relatedInformation?.first)
    XCTAssert(
      note.location.range == Range(positions["1️⃣"]) || note.location.range == Range(positions["2️⃣"]),
      "Unexpected range: \(note.location.range)"
    )
    XCTAssertEqual(note.codeActions?.count ?? 0, 1)

    let response = try await testClient.send(
      CodeActionRequest(
        range: note.location.range,
        context: CodeActionContext(
          diagnostics: diagnostics,
          only: [.quickFix],
          triggerKind: .invoked
        ),
        textDocument: TextDocumentIdentifier(note.location.uri)
      )
    )

    guard case .codeActions(let actions) = response else {
      XCTFail("Expected codeActions response")
      return
    }

    XCTAssertEqual(actions.count, 2)
    XCTAssert(
      actions.contains { action in
        // Allow the action message to be the one before or after
        // https://github.com/apple/swift/pull/67909, ensuring this test passes with
        // a sourcekitd that contains the change from that PR as well as older
        // toolchains that don't contain the change yet.
        [
          "Add stubs for conformance",
          "Do you want to add protocol stubs?",
        ].contains(action.title)
      }
    )
  }

  func testNotesFromIntegratedSwiftSyntaxDiagnostics() async throws {
    // Create a workspace that has compile_commands.json so that it has a build system but no compiler arguments
    // for test.swift so that we fall back to producing diagnostics from the built-in swift-syntax.
    let project = try await MultiFileTestProject(files: [
      "test.swift": "func foo() 1️⃣{2️⃣",
      "compile_commands.json": "[]",
    ])

    let (uri, positions) = try project.openDocument("test.swift")

    let report = try await project.testClient.send(
      DocumentDiagnosticsRequest(textDocument: TextDocumentIdentifier(uri))
    )
    let diagnostic = try XCTUnwrap(report.fullReport?.items.only)
    XCTAssertEqual(diagnostic.message, "expected '}' to end function")
    XCTAssertEqual(diagnostic.range, Range(positions["2️⃣"]))

    let note = try XCTUnwrap(diagnostic.relatedInformation?.only)
    XCTAssertEqual(note.message, "to match this opening '{'")
    XCTAssertEqual(note.location.range, positions["1️⃣"]..<positions["2️⃣"])
  }

  func testDiagnosticUpdatedAfterFilesInSameModuleAreUpdated() async throws {
    try SkipUnless.longTestsEnabled()

    let project = try await SwiftPMTestProject(
      files: [
        "FileA.swift": "",
        "FileB.swift": """
        func test() {
          sayHello()
        }
        """,
      ]
    )

    let (bUri, _) = try project.openDocument("FileB.swift")
    let beforeChangingFileA = try await project.testClient.send(
      DocumentDiagnosticsRequest(textDocument: TextDocumentIdentifier(bUri))
    )
    XCTAssert(
      (beforeChangingFileA.fullReport?.items ?? []).contains(where: { $0.message == "Cannot find 'sayHello' in scope" })
    )

    let diagnosticsRefreshRequestReceived = self.expectation(description: "DiagnosticsRefreshRequest received")
    project.testClient.handleSingleRequest { (request: DiagnosticsRefreshRequest) in
      diagnosticsRefreshRequestReceived.fulfill()
      return VoidResponse()
    }

    let updatedACode = "func sayHello() {}"
    let aUri = try project.uri(for: "FileA.swift")
    try updatedACode.write(to: try XCTUnwrap(aUri.fileURL), atomically: true, encoding: .utf8)
    project.testClient.send(
      DidChangeWatchedFilesNotification(changes: [FileEvent(uri: aUri, type: .changed)])
    )

    try await fulfillmentOfOrThrow([diagnosticsRefreshRequestReceived])

    let afterChangingFileA = try await project.testClient.send(
      DocumentDiagnosticsRequest(textDocument: TextDocumentIdentifier(bUri))
    )
    XCTAssertEqual(afterChangingFileA.fullReport?.items, [])
  }

  func testDiagnosticUpdatedAfterDependentModuleIsBuilt() async throws {
    try SkipUnless.longTestsEnabled()

    let project = try await SwiftPMTestProject(
      files: [
        "LibA/LibA.swift": """
        public func 1️⃣sayHello() {}
        """,
        "LibB/LibB.swift": """
        import LibA

        func test() {
          2️⃣sayHello()
        }
        """,
      ],
      manifest: """
        let package = Package(
          name: "MyLibrary",
          targets: [
            .target(name: "LibA"),
            .target(name: "LibB", dependencies: ["LibA"]),
          ]
        )
        """
    )

    let (bUri, _) = try project.openDocument("LibB.swift")

    // We might receive empty syntactic diagnostics before getting build settings. Wait until we get the diagnostic
    // about the missing module.
    try await repeatUntilExpectedResult {
      let beforeBuilding = try? await project.testClient.send(
        DocumentDiagnosticsRequest(textDocument: TextDocumentIdentifier(bUri))
      )
      #if compiler(>=6.1)
      #warning("When we drop support for Swift 5.10 we no longer need to check for the Objective-C error message")
      #endif
      if (beforeBuilding?.fullReport?.items ?? []).contains(where: {
        return $0.message == "No such module 'LibA'" || $0.message == "Could not build Objective-C module 'LibA'"
      }) {
        return true
      }
      logger.debug("Received unexpected diagnostics: \(beforeBuilding?.forLogging)")
      return false
    }

    let diagnosticsRefreshRequestReceived = self.expectation(description: "DiagnosticsRefreshRequest received")
    project.testClient.handleSingleRequest { (request: DiagnosticsRefreshRequest) in
      diagnosticsRefreshRequestReceived.fulfill()
      return VoidResponse()
    }

    try await SwiftPMTestProject.build(at: project.scratchDirectory)

    project.testClient.send(
      DidChangeWatchedFilesNotification(
        changes:
          FileManager.default.findFiles(withExtension: "swiftmodule", in: project.scratchDirectory).map {
            FileEvent(uri: DocumentURI($0), type: .created)
          }
      )
    )

    try await fulfillmentOfOrThrow([diagnosticsRefreshRequestReceived])

    let afterChangingFileA = try await project.testClient.send(
      DocumentDiagnosticsRequest(textDocument: TextDocumentIdentifier(bUri))
    )
    XCTAssertEqual(afterChangingFileA.fullReport?.items, [])
  }

  func testDiagnosticsWaitForDocumentToBePrepared() async throws {
    let diagnosticRequestSent = AtomicBool(initialValue: false)
    var testHooks = Hooks()
    testHooks.indexTestHooks.preparationTaskDidStart = { @Sendable taskDescription in
      // Only start preparation after we sent the diagnostic request. In almost all cases, this should not give
      // preparation enough time to finish before the diagnostic request is handled unless we wait for preparation in
      // the diagnostic request.
      while diagnosticRequestSent.value == false {
        do {
          try await Task.sleep(for: .seconds(0.01))
        } catch {
          XCTFail("Did not expect sleep to fail")
          break
        }
      }
    }

    let project = try await SwiftPMTestProject(
      files: [
        "LibA/LibA.swift": """
        public func sayHello() {}
        """,
        "LibB/LibB.swift": """
        import LibA

        func test() {
          sayHello()
        }
        """,
      ],
      manifest: """
        let package = Package(
          name: "MyLibrary",
          targets: [
            .target(name: "LibA"),
            .target(name: "LibB", dependencies: ["LibA"]),
          ]
        )
        """,
      hooks: testHooks,
      enableBackgroundIndexing: true,
      pollIndex: false
    )

    let (uri, _) = try project.openDocument("LibB.swift")

    // Use completion handler based method to send request so we can fulfill `diagnosticRequestSent` after sending it
    // but before receiving a reply. The async variant doesn't allow this distinction.
    let receivedDiagnostics = self.expectation(description: "Received diagnostics")
    project.testClient.send(DocumentDiagnosticsRequest(textDocument: TextDocumentIdentifier(uri))) { diagnostics in
      XCTAssertEqual(diagnostics.success?.fullReport?.items, [])
      receivedDiagnostics.fulfill()
    }
    diagnosticRequestSent.value = true
    try await fulfillmentOfOrThrow([receivedDiagnostics])
  }

  func testDontReturnEmptyDiagnosticsIfDiagnosticRequestIsCancelled() async throws {
    let diagnosticRequestCancelled = self.expectation(description: "diagnostic request cancelled")
    let packageLoadingDidFinish = self.expectation(description: "Package loading did finish")
    var testHooks = Hooks()
    testHooks.buildSystemHooks.swiftPMTestHooks.reloadPackageDidFinish = {
      packageLoadingDidFinish.fulfill()
    }
    testHooks.indexTestHooks.preparationTaskDidStart = { _ in
      _ = await XCTWaiter.fulfillment(of: [diagnosticRequestCancelled], timeout: defaultTimeout)
      // Poll until the `CancelRequestNotification` has been propagated to the request handling.
      for _ in 0..<Int(defaultTimeout * 100) {
        if Task.isCancelled {
          break
        }
        #if os(Windows)
        Sleep(10 /*ms*/)
        #else
        usleep(10_000 /*µs*/)
        #endif
      }
    }
    let project = try await SwiftPMTestProject(
      files: [
        "Lib.swift": "let x: String = 1"
      ],
      hooks: testHooks,
      enableBackgroundIndexing: true,
      pollIndex: false
    )
    try await fulfillmentOfOrThrow([packageLoadingDidFinish])
    let (uri, _) = try project.openDocument("Lib.swift")

    let diagnosticResponseReceived = self.expectation(description: "Received diagnostic response")
    let requestID = project.testClient.send(
      DocumentDiagnosticsRequest(textDocument: TextDocumentIdentifier(uri))
    ) { result in
      XCTAssertEqual(result, .failure(ResponseError.cancelled))
      diagnosticResponseReceived.fulfill()
    }
    project.testClient.send(CancelRequestNotification(id: requestID))
    diagnosticRequestCancelled.fulfill()
    try await fulfillmentOfOrThrow([diagnosticResponseReceived])
  }

  func testNoteInSecondaryFile() async throws {
    let project = try await SwiftPMTestProject(files: [
      "FileA.swift": """
      @available(*, unavailable)
      struct 1️⃣Test {}
      """,
      "FileB.swift": """
      func test() {
          _ = Test()
      }
      """,
    ])

    let (uri, _) = try project.openDocument("FileB.swift")
    let diagnostics = try await project.testClient.send(
      DocumentDiagnosticsRequest(textDocument: TextDocumentIdentifier(uri))
    )
    let diagnostic = try XCTUnwrap(diagnostics.fullReport?.items.only)
    let note = try XCTUnwrap(diagnostic.relatedInformation?.only)
    XCTAssertEqual(note.location, try project.location(from: "1️⃣", to: "1️⃣", in: "FileA.swift"))
  }
}