File: CompilationDatabaseTests.swift

package info (click to toggle)
swiftlang 6.2.3-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 2,856,264 kB
  • sloc: cpp: 9,995,718; ansic: 2,234,019; asm: 1,092,167; python: 313,940; objc: 82,726; f90: 80,126; lisp: 38,373; pascal: 25,580; sh: 20,378; ml: 5,058; perl: 4,751; makefile: 4,725; awk: 3,535; javascript: 3,018; xml: 918; fortran: 664; cs: 573; ruby: 396
file content (367 lines) | stat: -rw-r--r-- 14,172 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
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2022 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 SKTestSupport
import SwiftExtensions
import TSCBasic
import TSCExtensions
import ToolchainRegistry
import XCTest

final class CompilationDatabaseTests: XCTestCase {
  func testModifyCompilationDatabase() async throws {
    let project = try await MultiFileTestProject(files: [
      "main.cpp": """
      #if FOO
      void 1️⃣foo2️⃣() {}
      #else
      void 3️⃣foo4️⃣() {}
      #endif

      int main() {
        5️⃣foo6️⃣();
      }
      """,
      "compile_flags.txt": """
      -DFOO
      """,
    ])

    let (mainUri, positions) = try project.openDocument("main.cpp")

    // Verify that we get the expected result from a hover response before modifying the compile commands.

    let highlightRequest = DocumentHighlightRequest(
      textDocument: TextDocumentIdentifier(mainUri),
      position: positions["5️⃣"]
    )
    let preChangeHighlightResponse = try await project.testClient.send(highlightRequest)
    XCTAssertEqual(
      preChangeHighlightResponse,
      [
        DocumentHighlight(range: positions["1️⃣"]..<positions["2️⃣"], kind: .text),
        DocumentHighlight(range: positions["5️⃣"]..<positions["6️⃣"], kind: .text),
      ]
    )

    // Remove -DFOO from the compile commands.

    try await project.changeFileOnDisk(FixedCompilationDatabaseBuildSystem.dbName, newMarkedContents: "")

    // DocumentHighlight should now point to the definition in the `#else` block.

    let expectedPostEditHighlight = [
      DocumentHighlight(range: positions["3️⃣"]..<positions["4️⃣"], kind: .text),
      DocumentHighlight(range: positions["5️⃣"]..<positions["6️⃣"], kind: .text),
    ]

    // Updating the build settings takes a few seconds.
    // Send highlight requests every second until we receive correct results.
    try await repeatUntilExpectedResult {
      let postChangeHighlightResponse = try await project.testClient.send(highlightRequest)
      return postChangeHighlightResponse == expectedPostEditHighlight
    }
  }

  func testJSONCompilationDatabaseWithDifferentToolchainsForSwift() async throws {
    let dummyToolchain = Toolchain(
      identifier: "dummy",
      displayName: "dummy",
      path: URL(fileURLWithPath: "/dummy"),
      clang: nil,
      swift: URL(fileURLWithPath: "/dummy/usr/bin/swift"),
      swiftc: URL(fileURLWithPath: "/dummy/usr/bin/swiftc"),
      swiftFormat: nil,
      clangd: nil,
      sourcekitd: URL(fileURLWithPath: "/dummy/usr/lib/sourcekitd.framework/sourcekitd"),
      libIndexStore: nil
    )
    let toolchainRegistry = ToolchainRegistry(toolchains: [
      try await unwrap(ToolchainRegistry.forTesting.default), dummyToolchain,
    ])

    let project = try await MultiFileTestProject(
      files: [
        "testFromDefaultToolchain.swift": """
        #warning("Test warning")
        """,
        "testFromDummyToolchain.swift": """
        #warning("Test warning")
        """,
        "compile_commands.json": """
        [
          {
            "directory": "$TEST_DIR_BACKSLASH_ESCAPED",
            "arguments": [
              "swiftc",
              "$TEST_DIR_BACKSLASH_ESCAPED/testFromDefaultToolchain.swift",
              \(defaultSDKArgs)
            ],
            "file": "testFromDefaultToolchain.swift",
            "output": "$TEST_DIR_BACKSLASH_ESCAPED/testFromDefaultToolchain.swift.o"
          },
          {
            "directory": "$TEST_DIR_BACKSLASH_ESCAPED",
            "arguments": [
              "/dummy/usr/bin/swiftc",
              "$TEST_DIR_BACKSLASH_ESCAPED/testFromDummyToolchain.swift",
              \(defaultSDKArgs)
            ],
            "file": "testFromDummyToolchain.swift",
            "output": "$TEST_DIR_BACKSLASH_ESCAPED/testFromDummyToolchain.swift.o"
          }
        ]
        """,
      ],
      toolchainRegistry: toolchainRegistry
    )

    // We should be able to provide semantic functionality for `testFromDefaultToolchain` because we open it using the
    // default toolchain.

    let (forDefaultToolchainUri, _) = try project.openDocument("testFromDefaultToolchain.swift")
    let diagnostics = try await project.testClient.send(
      DocumentDiagnosticsRequest(textDocument: TextDocumentIdentifier(forDefaultToolchainUri))
    )
    XCTAssertEqual(
      diagnostics.fullReport?.items.map(\.message),
      ["Test warning"]
    )

    // But for `testFromDummyToolchain.swift`, we can't launch sourcekitd (because it doesn't exist, we just provided a
    // dummy), so we should receive an error. The exact error here is not super relevant, the important part is that we
    // apparently tried to launch a different sourcekitd.
    let (forDummyToolchainUri, _) = try project.openDocument("testFromDummyToolchain.swift")
    await assertThrowsError(
      try await project.testClient.send(
        DocumentDiagnosticsRequest(textDocument: TextDocumentIdentifier(forDummyToolchainUri))
      )
    ) { error in
      guard let error = error as? ResponseError else {
        XCTFail("Expected ResponseError, got \(error)")
        return
      }
      assertContains(error.message, "No language service")
    }
  }

  func testJSONCompilationDatabaseWithDifferentToolchainsForClang() async throws {
    let dummyToolchain = Toolchain(
      identifier: "dummy",
      displayName: "dummy",
      path: URL(fileURLWithPath: "/dummy"),
      clang: URL(fileURLWithPath: "/dummy/usr/bin/clang"),
      swift: nil,
      swiftc: nil,
      swiftFormat: nil,
      clangd: URL(fileURLWithPath: "/dummy/usr/bin/clangd"),
      sourcekitd: nil,
      libIndexStore: nil
    )
    let toolchainRegistry = ToolchainRegistry(toolchains: [
      try await unwrap(ToolchainRegistry.forTesting.default), dummyToolchain,
    ])

    let project = try await MultiFileTestProject(
      files: [
        "testFromDefaultToolchain.c": """
        void 1️⃣main() {}
        """,
        "testFromDummyToolchain.c": """
        void 2️⃣main() {}
        """,
        "compile_commands.json": """
        [
          {
            "directory": "$TEST_DIR_BACKSLASH_ESCAPED",
            "arguments": [
              "clang",
              "$TEST_DIR_BACKSLASH_ESCAPED/testFromDefaultToolchain.c"
            ],
            "file": "testFromDefaultToolchain.c",
            "output": "$TEST_DIR_BACKSLASH_ESCAPED/testFromDefaultToolchain.o"
          },
          {
            "directory": "$TEST_DIR_BACKSLASH_ESCAPED",
            "arguments": [
              "/dummy/usr/bin/clang",
              "$TEST_DIR_BACKSLASH_ESCAPED/testFromDummyToolchain.c"
            ],
            "file": "testFromDummyToolchain.c",
            "output": "$TEST_DIR_BACKSLASH_ESCAPED/testFromDummyToolchain.o"
          }
        ]
        """,
      ],
      toolchainRegistry: toolchainRegistry
    )

    // We should be able to provide semantic functionality for `testFromDefaultToolchain` because we open it using the
    // default toolchain.

    let (forDefaultToolchainUri, forDefaultToolchainPositions) = try project.openDocument("testFromDefaultToolchain.c")
    let hover = try await project.testClient.send(
      HoverRequest(
        textDocument: TextDocumentIdentifier(forDefaultToolchainUri),
        position: forDefaultToolchainPositions["1️⃣"]
      )
    )
    let hoverContent = try XCTUnwrap(hover?.contents.markupContent?.value)
    assertContains(hoverContent, "void main()")

    // But for `testFromDummyToolchain.swift`, we can't launch sourcekitd (because it doesn't exist, we just provided a
    // dummy), so we should receive an error. The exact error here is not super relevant, the important part is that we
    // apparently tried to launch a different sourcekitd.
    let (forDummyToolchainUri, forDummyToolchainPositions) = try project.openDocument("testFromDummyToolchain.c")
    await assertThrowsError(
      try await project.testClient.send(
        HoverRequest(
          textDocument: TextDocumentIdentifier(forDummyToolchainUri),
          position: forDummyToolchainPositions["2️⃣"]
        )
      )
    ) { error in
      guard let error = error as? ResponseError else {
        XCTFail("Expected ResponseError, got \(error)")
        return
      }
      assertContains(error.message, "No language service")
    }
  }

  func testLookThroughSwiftly() async throws {
    try await withTestScratchDir { scratchDirectory in
      let defaultToolchain = try await unwrap(ToolchainRegistry.forTesting.default)

      // We create a toolchain registry with the default toolchain, which is able to provide semantic functionality and
      // a dummy toolchain that can't provide semantic functionality.
      let fakeToolchainURL = scratchDirectory.appending(components: "fakeToolchain")
      let fakeToolchain = Toolchain(
        identifier: "fake",
        displayName: "fake",
        path: fakeToolchainURL,
        clang: nil,
        swift: fakeToolchainURL.appending(components: "usr", "bin", "swift"),
        swiftc: fakeToolchainURL.appending(components: "usr", "bin", "swiftc"),
        swiftFormat: nil,
        clangd: nil,
        sourcekitd: fakeToolchainURL.appending(components: "usr", "lib", "sourcekitd.framework", "sourcekitd"),
        libIndexStore: nil
      )
      let toolchainRegistry = ToolchainRegistry(toolchains: [
        try await unwrap(ToolchainRegistry.forTesting.default), fakeToolchain,
      ])

      // We need to create a file for the swift executable because `SwiftlyResolver` checks for its presence.
      try FileManager.default.createDirectory(
        at: XCTUnwrap(fakeToolchain.swift).deletingLastPathComponent(),
        withIntermediateDirectories: true
      )
      try await "".writeWithRetry(to: XCTUnwrap(fakeToolchain.swift))

      // Create a dummy swiftly executable that picks the default toolchain for all file unless `fakeToolchain` is in
      // the source file's path.
      let dummySwiftlyExecutableUrl = scratchDirectory.appendingPathComponent("swiftly")
      let dummySwiftExecutableUrl = scratchDirectory.appendingPathComponent("swift")
      try FileManager.default.createSymbolicLink(
        at: dummySwiftExecutableUrl,
        withDestinationURL: dummySwiftlyExecutableUrl
      )
      try await createBinary(
        """
        import Foundation

        if FileManager.default.currentDirectoryPath.contains("fakeToolchain") {
          print(#"\(fakeToolchain.path.filePath)"#)
        } else {
          print(#"\(defaultToolchain.path.filePath)"#)
        }
        """,
        at: dummySwiftlyExecutableUrl
      )

      // Now create a project in which we have one file in a `realToolchain` directory for which our fake swiftly will
      // pick the default toolchain and one in `fakeToolchain` for which swiftly will pick the fake toolchain. We should
      // be able to get semantic functionality for the file in `realToolchain` but not for `fakeToolchain` because
      // sourcekitd can't be launched for that toolchain (since it doesn't exist).
      let dummySwiftExecutablePathForJSON = try dummySwiftExecutableUrl.filePath.replacing(#"\"#, with: #"\\"#)

      let project = try await MultiFileTestProject(
        files: [
          "realToolchain/realToolchain.swift": """
          #warning("Test warning")
          """,
          "fakeToolchain/fakeToolchain.swift": """
          #warning("Test warning")
          """,
          "compile_commands.json": """
          [
            {
              "directory": "$TEST_DIR_BACKSLASH_ESCAPED/realToolchain",
              "arguments": [
                "\(dummySwiftExecutablePathForJSON)",
                "$TEST_DIR_BACKSLASH_ESCAPED/realToolchain/realToolchain.swift",
                \(defaultSDKArgs)
              ],
              "file": "realToolchain.swift",
              "output": "$TEST_DIR_BACKSLASH_ESCAPED/realToolchain/test.swift.o"
            },
            {
              "directory": "$TEST_DIR_BACKSLASH_ESCAPED/fakeToolchain",
              "arguments": [
                "\(dummySwiftExecutablePathForJSON)",
                "$TEST_DIR_BACKSLASH_ESCAPED/fakeToolchain/fakeToolchain.swift",
                \(defaultSDKArgs)
              ],
              "file": "fakeToolchain.swift",
              "output": "$TEST_DIR_BACKSLASH_ESCAPED/fakeToolchain/test.swift.o"
            }
          ]
          """,
        ],
        toolchainRegistry: toolchainRegistry
      )

      let (forRealToolchainUri, _) = try project.openDocument("realToolchain.swift")
      let diagnostics = try await project.testClient.send(
        DocumentDiagnosticsRequest(textDocument: TextDocumentIdentifier(forRealToolchainUri))
      )
      XCTAssertEqual(diagnostics.fullReport?.items.map(\.message), ["Test warning"])

      let (forDummyToolchainUri, _) = try project.openDocument("fakeToolchain.swift")
      await assertThrowsError(
        try await project.testClient.send(
          DocumentDiagnosticsRequest(textDocument: TextDocumentIdentifier(forDummyToolchainUri))
        )
      ) { error in
        guard let error = error as? ResponseError else {
          XCTFail("Expected ResponseError, got \(error)")
          return
        }
        // The actual error message here doesn't matter too much, we just need to check that we don't get diagnostics.
        assertContains(error.message, "No language service")
      }
    }
  }
}

fileprivate let defaultSDKArgs: String = {
  if let defaultSDKPath {
    let escapedPath = defaultSDKPath.replacing(#"\"#, with: #"\\"#)
    return """
      "-sdk", "\(escapedPath)"
      """
  }
  return ""
}()