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
|
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2023 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
//
//===----------------------------------------------------------------------===//
@_spi(Testing) import Diagnose
import Foundation
import LSPLogging
import LSPTestSupport
@_spi(Testing) import SKCore
import SKTestSupport
import SourceKitD
import XCTest
import struct TSCBasic.AbsolutePath
/// If a default SDK is present on the test machine, return the `-sdk` argument that can be placed in the request
/// YAML. Otherwise, return an empty string.
private let sdkArg: String = {
if let sdk = defaultSDKPath {
return """
"-sdk", "\(sdk)",
"""
} else {
return ""
}
}()
/// If a default SDK is present on the test machine, return the `-sdk` argument that can be placed in the request
/// YAML. Otherwise, return an empty string.
private let sdkArgs: [String] = {
if let sdk = defaultSDKPath {
return ["-sdk", "\(sdk)"]
} else {
return []
}
}()
final class DiagnoseTests: XCTestCase {
func testRemoveCodeItemsAndMembers() async throws {
// We consider the test case reproducing if cursor info returns the two ambiguous results including their doc
// comments.
// We should strip away unrelated declarations and statements.
try await assertReduceSourceKitD(
"""
func test() {
let foo = Foo()
print("test")
foo.1️⃣ambiguous()
}
struct Foo {
/// Returns an integer
func ambiguous() -> Int {
return 1 + 2
}
/// Returns a string
func ambiguous() -> String {
// a unrelated comment
return "abc"
}
func unrelated() {}
}
struct UnrelatedStruct {}
""",
request: """
{
key.request: source.request.cursorinfo,
key.compilerargs: [
"$FILE",
\(sdkArg)
],
key.offset: $OFFSET,
key.sourcefile: "$FILE"
}
""",
reproducerPredicate: { $0.contains("Returns an integer") && $0.contains("Returns a string") },
expectedReducedFileContents: """
func test() {
let foo = Foo()
foo.ambiguous()
}
struct Foo {
/// Returns an integer
func ambiguous() -> Int {
}
/// Returns a string
func ambiguous() -> String {
}
}
"""
)
}
func testRemoveComments() async throws {
try await assertReduceSourceKitD(
"""
/// Doc comment
func test() {
// Comment
let foo = 1️⃣Foo()
}
/*
Block comment
With another line
*/
struct Foo {
}
""",
request: """
{
key.request: source.request.cursorinfo,
key.compilerargs: [
"$FILE",
\(sdkArg)
],
key.offset: $OFFSET,
key.sourcefile: "$FILE"
}
""",
reproducerPredicate: { $0.contains("Foo") },
expectedReducedFileContents: """
func test() {
let foo = Foo()
}
struct Foo {
}
"""
)
}
@MainActor
func testReduceFrontend() async throws {
try await withTestScratchDir { scratchDir in
let fileAContents = """
func makeThing() -> Int { 1 }
func test() { let b = makeThing() }
func unrelatedA() {}
"""
let fileBContents = """
func makeThing() -> String { "" }
func unrelatedB() {}
"""
let fileAPath = scratchDir.appending(component: "a.swift").pathString
let fileBPath = scratchDir.appending(component: "b.swift").pathString
try fileAContents.write(toFile: fileAPath, atomically: true, encoding: .utf8)
try fileBContents.write(toFile: fileBPath, atomically: true, encoding: .utf8)
let toolchain = try await unwrap(ToolchainRegistry.forTesting.default)
let requestExecutor = try InProcessSourceKitRequestExecutor(
toolchain: toolchain,
reproducerPredicate: NSPredicate(block: { (result, _) -> Bool in
guard let dict = (result as? [String: Any]) else {
return false
}
guard let stderr = dict["stderr"] as? String else {
return false
}
return stderr.contains("ambiguous use of 'makeThing()'")
})
)
var lastProgress = 0.0
// '-swift-version 5' is irrelevant and should get removed by the reducer.
let frontendArgs = ["-typecheck", fileAPath, fileBPath, "-swift-version", "5"] + sdkArgs
let reduced = try await reduceFrontendIssue(
frontendArgs: frontendArgs,
using: requestExecutor,
progressUpdate: { progress, _ in
XCTAssertLessThanOrEqual(lastProgress, progress)
lastProgress = progress
}
)
XCTAssertEqual(
reduced.fileContents,
"""
func makeThing() -> Int { }
func test() { let b = makeThing() }
func makeThing() -> String { }
"""
)
// When running swift-frontend from an Xcode toolchain, the -sdk argument is required to find the stdlib.
// When running using an open source toolchain snapshot or on Linux, the SDK is found next to the compiler and the
// -sdk argument is not required.
XCTAssert(
reduced.compilerArgs == ["-typecheck", "$FILE"] || reduced.compilerArgs == ["-typecheck"] + sdkArgs + ["$FILE"]
)
}
}
}
/// Check that reducing `request` with the given file contents results in `expectedReducedFileContents`.
///
/// - Parameters:
/// - markedFileContents: The contents of the files that should be reduced. Must contain a 1️⃣ location marker, which
/// will be used to substitute `$OFFSET` in `request`.
/// - request: The YAML sourcekitd request that should be reduced. May contain the following placeholders:
/// - `$FILE`: The path of the input file
/// - `$OFFSET`: The UTF-8 offset of the 1️⃣ location marker in `markedFileContents`
/// - reproducerPredicate: A predicate that indicates whether a run request reproduces the issue.
/// - expectedReducedFileContents: The contents of the file that the reducer is expected to produce.
@MainActor
private func assertReduceSourceKitD(
_ markedFileContents: String,
request: String,
reproducerPredicate: @Sendable @escaping (String) -> Bool,
expectedReducedFileContents: String,
file: StaticString = #filePath,
line: UInt = #line
) async throws {
let (markers, fileContents) = extractMarkers(markedFileContents)
let toolchain = try await unwrap(ToolchainRegistry.forTesting.default)
logger.debug("Using \(toolchain.path?.pathString ?? "<nil>") to reduce source file")
let markerOffset = try XCTUnwrap(markers["1️⃣"], "Failed to find position marker 1️⃣ in file contents")
try await withTestScratchDir { scratchDir in
let requestExecutor = try InProcessSourceKitRequestExecutor(
toolchain: toolchain,
reproducerPredicate: NSPredicate(block: { (requestResponse, _) -> Bool in
reproducerPredicate(requestResponse as! String)
})
)
let testFilePath = scratchDir.appending(component: "test.swift").pathString
try fileContents.write(toFile: testFilePath, atomically: false, encoding: .utf8)
let request =
request
.replacingOccurrences(of: "$FILE", with: testFilePath)
.replacingOccurrences(of: "$OFFSET", with: String(markerOffset))
let requestInfo = try RequestInfo(request: request)
var lastProgress = 0.0
let reduced = try await requestInfo.reduceInputFile(
using: requestExecutor,
progressUpdate: { progress, _ in
XCTAssertLessThanOrEqual(lastProgress, progress, file: file, line: line)
lastProgress = progress
}
)
XCTAssertEqual(reduced.fileContents, expectedReducedFileContents, file: file, line: line)
}
}
/// We can't run the `OutOfProcessSourceKitRequestExecutor` in tests because that runs the sourcekit-lsp executable,
/// which isn't built when running tests.
private class InProcessSourceKitRequestExecutor: SourceKitRequestExecutor {
/// The path to `sourcekitd.framework/sourcekitd`.
private let sourcekitd: URL
/// The path to `swift-frontend`.
private let swiftFrontend: URL
/// The file to which we write the reduce source file.
private let temporarySourceFile: URL
/// The file to which we write the AYML request that we want to run.
private let temporaryRequestFile: URL
/// If this predicate evaluates to true on the sourcekitd response, the request is
/// considered to reproduce the issue.
private let reproducerPredicate: NSPredicate
init(toolchain: Toolchain, reproducerPredicate: NSPredicate) throws {
self.sourcekitd = try XCTUnwrap(toolchain.sourcekitd?.asURL)
self.swiftFrontend = try XCTUnwrap(toolchain.swiftFrontend)
self.reproducerPredicate = reproducerPredicate
temporaryRequestFile = FileManager.default.temporaryDirectory.appendingPathComponent("request-\(UUID()).yml")
temporarySourceFile = FileManager.default.temporaryDirectory.appendingPathComponent("reduce-\(UUID()).swift")
}
deinit {
try? FileManager.default.removeItem(at: temporaryRequestFile)
try? FileManager.default.removeItem(at: temporarySourceFile)
}
func runSwiftFrontend(request: RequestInfo) async throws -> SourceKitDRequestResult {
return try await OutOfProcessSourceKitRequestExecutor(
sourcekitd: sourcekitd,
swiftFrontend: swiftFrontend,
reproducerPredicate: reproducerPredicate
).runSwiftFrontend(request: request)
}
func runSourceKitD(request: RequestInfo) async throws -> SourceKitDRequestResult {
try request.fileContents.write(to: temporarySourceFile, atomically: true, encoding: .utf8)
let requestString = try request.request(for: temporarySourceFile)
logger.info("Sending request: \(requestString)")
let sourcekitd = try await DynamicallyLoadedSourceKitD.getOrCreate(
dylibPath: try! AbsolutePath(validating: sourcekitd.path)
)
let response = try await sourcekitd.run(requestYaml: requestString)
logger.info("Received response: \(response.description)")
switch response.error {
case .requestFailed, .requestInvalid, .requestCancelled, .timedOut, .missingRequiredSymbol, .connectionInterrupted:
return .error
case nil:
if reproducerPredicate.evaluate(with: response.description) {
return .reproducesIssue
}
return .success(response: response.description)
}
}
}
|