File: SwiftCWrapper.swift

package info (click to toggle)
swiftlang 6.0.3-2
  • links: PTS, VCS
  • area: main
  • in suites: trixie
  • size: 2,519,992 kB
  • sloc: cpp: 9,107,863; ansic: 2,040,022; asm: 1,135,751; python: 296,500; objc: 82,456; f90: 60,502; lisp: 34,951; pascal: 19,946; sh: 18,133; perl: 7,482; ml: 4,937; javascript: 4,117; makefile: 3,840; awk: 3,535; xml: 914; fortran: 619; cs: 573; ruby: 573
file content (326 lines) | stat: -rw-r--r-- 12,730 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
//===----------------------------------------------------------------------===//
//
// 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 Common
import Foundation
import class TSCUtility.PercentProgressAnimation
import protocol TSCUtility.ProgressAnimationProtocol
import TSCBasic

public struct SwiftCWrapper {
  let arguments: [String]
  let swiftcPath: String
  let extraCodeCompleteOptions: [String]
  let stressTesterPath: String
  let astBuildLimit: Int?
  let requestDurationsOutputFile: URL?
  let rewriteModes: [RewriteMode]
  let requestKinds: Set<RequestKind>
  let conformingMethodTypes: [String]?
  let ignoreIssues: Bool
  let issueManager: IssueManager?
  let maxJobs: Int?
  let dumpResponsesPath: String?
  let failFast: Bool
  let suppressOutput: Bool

  public init(swiftcArgs: [String], swiftcPath: String,
              stressTesterPath: String, astBuildLimit: Int?,
              requestDurationsOutputFile: URL?,
              rewriteModes: [RewriteMode], requestKinds: Set<RequestKind>,
              conformingMethodTypes: [String]?,
              extraCodeCompleteOptions: [String], ignoreIssues: Bool,
              issueManager: IssueManager?, maxJobs: Int?,
              dumpResponsesPath: String?, failFast: Bool,
              suppressOutput: Bool) {
    self.arguments = swiftcArgs
    self.swiftcPath = swiftcPath
    self.stressTesterPath = stressTesterPath
    self.astBuildLimit = astBuildLimit
    self.extraCodeCompleteOptions = extraCodeCompleteOptions
    self.ignoreIssues = ignoreIssues
    self.issueManager = issueManager
    self.failFast = failFast
    self.suppressOutput = suppressOutput
    self.requestDurationsOutputFile = requestDurationsOutputFile
    self.rewriteModes = rewriteModes
    self.requestKinds = requestKinds
    self.conformingMethodTypes = conformingMethodTypes
    self.maxJobs = maxJobs
    self.dumpResponsesPath = dumpResponsesPath
  }

  public var swiftFiles: [(String, size: Int)] {
    let dependencyPaths = ["/.build/checkouts/", "/Pods/", "/Carthage/Checkouts", "/SourcePackages/checkouts/"]
    return arguments
      .flatMap { DriverFileList(at: $0)?.paths ?? [$0] }
      .filter { argument in
        // Check it looks like a Swift file path and is in the main project
        guard argument.hasSuffix(".swift") &&
            dependencyPaths.allSatisfy({ !argument.contains($0) }) else { return false }
        var isDirectory: ObjCBool = false
        let exists = FileManager.default.fileExists(atPath: argument, isDirectory: &isDirectory)
        return exists && !isDirectory.boolValue
      }
      .sorted()
      .compactMap { file in
        guard let size = try? FileManager.default.attributesOfItem(atPath: file)[.size] else {
            // ignore files that couldn't be read
            return nil
        }
        return (file, size: Int(size as! UInt64))
      }
  }

  func run() throws -> Int32 {
    // Execute the compiler
    let swiftcResult = ProcessRunner(launchPath: swiftcPath, arguments: arguments)
      .run(captureStdout: false, captureStderr: false)
    guard swiftcResult.status == EXIT_SUCCESS else { return swiftcResult.status }

    let startTime = Date()

    // Determine the list of stress testing operations to perform
    let operations = swiftFiles.flatMap { (file, sizeInBytes) -> [StressTestOperation] in
      if let fileFilter = ProcessInfo.processInfo.environment["SK_STRESS_FILE_FILTER"] {
        if !fileFilter.split(separator: ",").contains(where: { file.contains($0) }) {
          return []
        }
      }
      // Split large files into multiple parts to improve load balancing
      let partCount = max(Int(sizeInBytes / 1000), 1)
      return rewriteModes.flatMap { (mode) -> [StressTestOperation] in
        // CodePointWidth.swift in swift-power-assert produces a lot of
        // expressions that are bogus and take very long to type check, causing
        // the stress tester to time out. Skip it for now until the underlying
        // issue is fixed.
        // https://github.com/apple/swift/issues/66785
        if file.contains("CodePointWidth.swift") && (mode == .insideOut || mode == .concurrent) {
          return []
        }
        return (1...partCount).map { part in
          StressTestOperation(file: file, rewriteMode: mode,
                              requests: requestKinds,
                              conformingMethodTypes: conformingMethodTypes,
                              limit: astBuildLimit,
                              part: (part, of: partCount),
                              offsetFilter: ProcessInfo.processInfo.environment["SK_OFFSET_FILTER"].flatMap { Int($0) },
                              reportResponses: dumpResponsesPath != nil,
                              compilerArgs: arguments,
                              executable: stressTesterPath,
                              swiftc: swiftcPath,
                              extraCodeCompleteOptions: extraCodeCompleteOptions,
                              requestDurationsOutputFile: requestDurationsOutputFile)
        }
      }
    }

    guard !operations.isEmpty else { return swiftcResult.status }

    // Run the operations, reporting progress
    let progress: ProgressAnimationProtocol?
    if !suppressOutput {
      progress = PercentProgressAnimation(stream: stderrStream, header: "Stress testing SourceKit...")
      progress?.update(step: 0, total: operations.count, text: "Scheduling \(operations.count) operations")
    } else {
      progress = nil
    }

    // Write out response data once it's received and all preceding operations are complete
    var orderingHandler: OrderingBuffer<[SourceKitResponseData]>? = nil
    var seenResponses = Set<UInt64>()
    if let dumpResponsesPath = dumpResponsesPath {
      orderingHandler = OrderingBuffer(itemCount: operations.count) { responses in
        self.writeResponseData(responses, to: dumpResponsesPath, seenResponses: &seenResponses)
      }
    }

    let queue = StressTesterOperationQueue(operations: operations, maxWorkers: maxJobs) { index, operation, completed, total -> Bool in
      let message = "\(operation.file) (\(operation.summary)): \(operation.status.name)"
      progress?.update(step: completed, total: total, text: message)
      orderingHandler?.complete(operation.responses, at: index, setLast: !operation.status.isPassed)
      operation.responses.removeAll()
      // We can control whether to stop scheduling new operations here. As long
      // as we return `true`, the stress tester continues to schedule new
      // test operations. To stop at the first failure, return
      // `operation.status.isPassed`.
      return true
    }
    queue.waitUntilFinished()

    if !suppressOutput {
      progress?.complete(success: operations.allSatisfy {$0.status.isPassed})
      stderrStream <<< "\n"
      stderrStream.flush()

      // Report the overall runtime
      let elapsedSeconds = -startTime.timeIntervalSinceNow
      stderrStream <<< "Runtime: \(elapsedSeconds.formatted() ?? String(elapsedSeconds))\n\n"
      stderrStream.flush()
    }

    // Determine the set of processed files and the first failure (if any)
    var processedFiles = Set<String>()
    var detectedIssues: [StressTesterIssue] = []
    for operation in operations {
      switch operation.status {
      case .cancelled:
        fatalError("cancelled operation before failed operation")
      case .unexecuted:
        fatalError("unterminated operation")
      case .errored(let status):
        detectedIssues.append(.errored(status: status, file: operation.file,
                                 arguments: escapeArgs(operation.args)))
      case .failed(let sourceKitErrors):
        for sourceKitError in sourceKitErrors {
          detectedIssues.append(.failed(sourceKitError: sourceKitError,
                                  arguments: escapeArgs(operation.args)))
        }
        fallthrough
      case .passed:
        processedFiles.insert(operation.file)
      }
    }

    var hasUnexpectedIssue = false
    for detectedIssue in detectedIssues {
      let matchingSpec = try issueManager?.update(for: processedFiles, issue: detectedIssue)
      if issueManager == nil || matchingSpec != nil {
        hasUnexpectedIssue = true
      }
      try report(detectedIssue, matching: matchingSpec)
    }

    if hasUnexpectedIssue {
      return ignoreIssues ? swiftcResult.status : EXIT_FAILURE
    } else {
      return EXIT_SUCCESS
    }
  }

  private func writeResponseData(_ responses: [SourceKitResponseData], to path: String, seenResponses: inout Set<UInt64>) {
    // Only write the first of identical responses
    let data = responses
      .map { response -> String in
        let results = response.results.map { result in
          let hash = result.stableHash
          if !seenResponses.insert(hash).inserted {
            return "See <\(hash)>.\n"
          }
          return "<\(hash)> \(result)\n"
        }.joined()
        return """
          \(response.request)"
          \(results)

          """
      }
      .joined()
      .data(using: .utf8)!

    if let fileHandle = FileHandle(forWritingAtPath: path) {
      defer { fileHandle.closeFile() }
      fileHandle.seekToEndOfFile()
      fileHandle.write(data)
    } else {
      FileManager.default.createFile(atPath: path, contents: data)
    }
  }

  private func report(_ issue: StressTesterIssue?, matching xIssue: ExpectedIssue? = nil) throws {
    guard !suppressOutput else { return }
    defer { stderrStream.flush() }

    guard let issue = issue else {
      stderrStream <<< "No failures detected.\n"
      return
    }

    if let xIssue = xIssue {
      stderrStream <<< "Detected expected failure [\(xIssue.issueUrl)]: \(issue)\n\n"
    } else {
      stderrStream <<< "Detected unexpected failure: \(issue)\n\n"
      if let issueManager = issueManager {
        let xfail = ExpectedIssue(matching: issue, issueUrl: "<issue url>",
                                    config: issueManager.activeConfig)
        let json = try issueManager.encoder.encode(xfail)
        stderrStream <<< "Add the following entry to the expected failures JSON file to mark it as expected:\n"
        stderrStream <<< String(data: json, encoding: .utf8)! <<< "\n\n"
      }
    }
  }
}

private struct OrderingBuffer<T> {
  private var items: [T?]
  private var nextItemIndex: Int
  private var endIndex: Int? = nil
  private let completionHandler: (T) -> ()

  init(itemCount: Int, completionHandler: @escaping (T) -> ()) {
    items = Array.init(repeating: nil, count: itemCount)
    nextItemIndex = items.startIndex
    self.completionHandler = completionHandler
  }

  mutating func complete(_ item: T, at index: Int, setLast: Bool) {
    precondition(index < items.endIndex && items[index] == nil && nextItemIndex < items.endIndex)
    items[index] = item
    if setLast && (endIndex == nil || (index + 1) < endIndex!) {
      endIndex = index + 1
    }
    while nextItemIndex < (endIndex ?? items.endIndex), let nextItem = items[nextItemIndex] {
      completionHandler(nextItem)
      nextItemIndex += 1
    }
  }
}

fileprivate extension TimeInterval {
  func formatted() -> String? {
    let formatter = DateComponentsFormatter()
    formatter.allowedUnits = [.hour, .minute, .second]
    formatter.allowsFractionalUnits = true
    formatter.maximumUnitCount = 3
    formatter.unitsStyle = .abbreviated

    return formatter.string(from: self)
  }
}

public enum StressTesterIssue: CustomStringConvertible {
  case failed(sourceKitError: SourceKitError, arguments: String)
  case errored(status: Int32, file: String, arguments: String)

  public var description: String {
    switch self {
    case .failed(let sourceKitError, let arguments):
      return String(describing: sourceKitError) +
        "\n\nReproduce with:\nsk-stress-test \(arguments)\n"
    case .errored(let status, _, let arguments):
      return """
        sk-stress-test errored with exit code \(status). Reproduce with:
        sk-stress-test \(arguments)\n
        """
    }
  }

  /// Returns `true`if this issue represents a soft `SourceKitError`.
  public var isSoftError: Bool {
    switch self {
    case .failed(sourceKitError: let sourceKitError, arguments: _):
      return sourceKitError.isSoft
    case .errored:
      return false
    }
  }
}