File: Job.swift

package info (click to toggle)
swiftlang 6.0.3-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, 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 (387 lines) | stat: -rw-r--r-- 14,283 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
//===--------------- Job.swift - Swift Job Abstraction --------------------===//
//
// 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 protocol TSCBasic.DiagnosticData
import protocol TSCBasic.FileSystem

/// A job represents an individual subprocess that should be invoked during compilation.
public struct Job: Codable, Equatable, Hashable {
  public enum Kind: String, Codable {
    case compile
    case backend
    case mergeModule = "merge-module"
    case link
    case generateDSYM = "generate-dSYM"
    case autolinkExtract = "autolink-extract"
    case emitModule = "emit-module"
    case generatePCH = "generate-pch"
    case moduleWrap = "module-wrap"

    /// Generate a compiled Clang module.
    case generatePCM = "generate-pcm"
    case compileModuleFromInterface = "compile-module-from-interface"
    case dumpPCM = "dump-pcm"
    case interpret
    case repl
    case verifyDebugInfo = "verify-debug-info"
    case printTargetInfo = "print-target-info"
    case emitSupportedFeatures = "emit-supported-features"
    case versionRequest = "version-request"
    case scanDependencies = "scan-dependencies"
    case verifyModuleInterface = "verify-emitted-module-interface"
    case help
    case generateAPIBaseline = "generate-api-baseline"
    case generateABIBaseline = "generate-abi-baseline"
    case compareAPIBaseline = "compare-api-baseline"
    case compareABIBaseline = "Check ABI stability"
  }

  public enum ArgTemplate: Equatable, Hashable {
    /// Represents a command-line flag that is substituted as-is.
    case flag(String)

    /// Represents a virtual path on disk.
    case path(VirtualPath)

    /// Represents a response file path prefixed by '@'.
    case responseFilePath(VirtualPath)

    /// Represents a joined option+path combo.
    case joinedOptionAndPath(String, VirtualPath)

    /// Represents a list of arguments squashed together and passed as a single argument.
    case squashedArgumentList(option: String, args: [ArgTemplate])
  }

  /// The Swift module this job involves.
  public var moduleName: String

  /// The tool to invoke.
  public var tool: VirtualPath

  /// The command-line arguments of the job.
  public var commandLine: [ArgTemplate]

  /// Whether or not the job supports using response files to pass command line arguments.
  public var supportsResponseFiles: Bool

  /// The list of inputs for this job. These are all files that must be provided in order for this job to execute,
  /// and this list, along with the corresponding `outputs` is used to establish producer-consumer dependency
  /// relationship among jobs.
  public var inputs: [TypedVirtualPath]

  /// The list of inputs to use for displaying purposes. These files are the ones the driver will communicate
  /// to the user/client as being objects of the selected compilation action.
  /// For example, a frontend job to compile a `.swift` source file may require multiple binary `inputs`,
  /// such as a pre-compiled bridging header and binary Swift module dependencies, but only the input `.swift`
  /// source file is meant to be the displayed object of compilation - a display input.
  public var displayInputs: [TypedVirtualPath]

  /// The primary inputs for compile jobs
  public var primaryInputs: [TypedVirtualPath]

  /// The outputs produced by the job.
  public var outputs: [TypedVirtualPath]

  /// Any extra environment variables which should be set while running the job.
  public var extraEnvironment: [String: String]

  /// Whether or not the job must be executed in place, replacing the current driver process.
  public var requiresInPlaceExecution: Bool

  /// The kind of job.
  public var kind: Kind

  /// The Cache Key for the compilation. It is a dictionary from input file to its output cache key.
  public var outputCacheKeys: [TypedVirtualPath: String]

  /// A map from a primary input to all of its corresponding outputs
  private var compileInputOutputMap: [TypedVirtualPath : [TypedVirtualPath]]

  public init(
    moduleName: String,
    kind: Kind,
    tool: ResolvedTool,
    commandLine: [ArgTemplate],
    displayInputs: [TypedVirtualPath]? = nil,
    inputs: [TypedVirtualPath],
    primaryInputs: [TypedVirtualPath],
    outputs: [TypedVirtualPath],
    outputCacheKeys: [TypedVirtualPath: String] = [:],
    inputOutputMap: [TypedVirtualPath : [TypedVirtualPath]] = [:],
    extraEnvironment: [String: String] = [:],
    requiresInPlaceExecution: Bool = false
  ) {
    self.moduleName = moduleName
    self.kind = kind
    self.tool = .absolute(tool.path)
    self.commandLine = commandLine
    self.displayInputs = displayInputs ?? []
    self.inputs = inputs
    self.primaryInputs = primaryInputs
    self.outputs = outputs
    self.outputCacheKeys = outputCacheKeys
    self.compileInputOutputMap = inputOutputMap
    self.extraEnvironment = extraEnvironment
    self.requiresInPlaceExecution = requiresInPlaceExecution
    self.supportsResponseFiles = tool.supportsResponseFiles
  }

  public var primarySwiftSourceFiles: [SwiftSourceFile] { primaryInputs.swiftSourceFiles }
}

extension Job {
  public enum InputError: Error, Equatable, DiagnosticData {
    case inputUnexpectedlyModified(TypedVirtualPath)

    public var description: String {
      switch self {
      case .inputUnexpectedlyModified(let input):
        return "input file '\(input.file.name)' was modified during the build"
      }
    }
  }

  public func verifyInputsNotModified(since recordedInputModificationDates: [TypedVirtualPath: TimePoint], fileSystem: FileSystem) throws {
    for input in inputs {
      if let recordedModificationTime = recordedInputModificationDates[input],
         try fileSystem.lastModificationTime(for: input.file) != recordedModificationTime {
        throw InputError.inputUnexpectedlyModified(input)
      }
    }
  }
}

extension Job {
  // If the job's kind is `.compile`, serve a collection of Outputs corresponding
  // to a given primary input.
  public func getCompileInputOutputs(for input: TypedVirtualPath) -> [TypedVirtualPath]? {
    assert(self.kind == .compile)
    return compileInputOutputMap[input]
  }
}

extension Job : CustomStringConvertible {
  public var description: String {
    func join(_ parts: String?...) -> String {
      return parts.compactMap { $0 }.joined(separator: " ")
    }

    switch kind {
    case .compile:
        return join("Compiling \(moduleName)", displayInputs.first?.file.basename)

    case .mergeModule:
        return "Merging module \(moduleName)"

    case .link:
        return "Linking \(moduleName)"

    case .generateDSYM:
        return "Generating dSYM for module \(moduleName)"

    case .autolinkExtract:
        return "Extracting autolink information for module \(moduleName)"

    case .emitModule:
        return "Emitting module for \(moduleName)"

    case .compileModuleFromInterface:
        return "Compiling Swift module \(moduleName)"

    case .generatePCH:
        return join("Compiling bridging header", displayInputs.first?.file.basename)

    case .moduleWrap:
      return "Wrapping Swift module \(moduleName)"

    case .generatePCM:
        return "Compiling Clang module \(moduleName)"

    case .dumpPCM:
        return join("Dump information about Clang module", displayInputs.first?.file.name)

    case .interpret:
        return join("Interpreting", displayInputs.first?.file.name)

    case .repl:
        return "Executing Swift REPL"

    case .verifyDebugInfo:
        return "Verifying debug information for module \(moduleName)"

    case .printTargetInfo:
        return "Gathering target information for module \(moduleName)"

    case .versionRequest:
        return "Getting Swift version information"

    case .help:
        return "Swift help"

    case .backend:
      return join("Embedding bitcode for \(moduleName)", displayInputs.first?.file.basename)

    case .emitSupportedFeatures:
      return "Emitting supported Swift compiler features"

    case .scanDependencies:
      return "Scanning dependencies for module \(moduleName)"

    case .verifyModuleInterface:
      return join("Verifying emitted module interface", displayInputs.first?.file.basename)

    case .generateAPIBaseline:
      return "Generating API baseline file for module \(moduleName)"

    case .generateABIBaseline:
      return "Generating ABI baseline file for module \(moduleName)"

    case .compareAPIBaseline:
      return "Comparing API of \(moduleName) to baseline"

    case .compareABIBaseline:
      return "Comparing ABI of \(moduleName) to baseline"
    }
  }

  public var descriptionForLifecycle: String {
    switch kind {
    case .compile:
      return "Compiling \(inputsGeneratingCode.map {$0.file.basename}.joined(separator: ", "))"
    default:
      return description
    }
  }
}

extension Job.Kind {
  /// Whether this job kind uses the Swift frontend.
  public var isSwiftFrontend: Bool {
    switch self {
    case .backend, .compile, .mergeModule, .emitModule, .compileModuleFromInterface, .generatePCH,
        .generatePCM, .dumpPCM, .interpret, .repl, .printTargetInfo,
        .versionRequest, .emitSupportedFeatures, .scanDependencies, .verifyModuleInterface:
        return true

    case .autolinkExtract, .generateDSYM, .help, .link, .verifyDebugInfo, .moduleWrap,
        .generateAPIBaseline, .generateABIBaseline, .compareAPIBaseline, .compareABIBaseline:
        return false
    }
  }

  /// Whether this job kind is a compile job.
  public var isCompile: Bool {
    switch self {
    case .compile:
      return true
    case .backend, .mergeModule, .emitModule, .generatePCH, .compileModuleFromInterface,
         .generatePCM, .dumpPCM, .interpret, .repl, .printTargetInfo,
         .versionRequest, .autolinkExtract, .generateDSYM,
         .help, .link, .verifyDebugInfo, .scanDependencies,
         .emitSupportedFeatures, .moduleWrap, .verifyModuleInterface,
         .generateAPIBaseline, .generateABIBaseline, .compareAPIBaseline,
         .compareABIBaseline:
      return false
    }
  }

  /// Whether this job supports caching.
  public var supportCaching: Bool {
    switch self {
    case .compile, .emitModule, .generatePCH, .compileModuleFromInterface,
         .generatePCM, .verifyModuleInterface:
      return true
    case .backend, .mergeModule, .dumpPCM, .interpret, .repl, .printTargetInfo,
         .versionRequest, .autolinkExtract, .generateDSYM, .help, .link,
         .verifyDebugInfo, .scanDependencies, .emitSupportedFeatures, .moduleWrap,
         .generateAPIBaseline, .generateABIBaseline, .compareAPIBaseline,
         .compareABIBaseline:
      return false
    }
  }
}
// MARK: - Job.ArgTemplate + Codable

extension Job.ArgTemplate: Codable {
  private enum CodingKeys: String, CodingKey {
    case flag, path, responseFilePath, joinedOptionAndPath, squashedArgumentList

    enum JoinedOptionAndPathCodingKeys: String, CodingKey {
      case option, path
    }

    enum SquashedArgumentListCodingKeys: String, CodingKey {
      case option, args
    }
  }

  public func encode(to encoder: Encoder) throws {
    var container = encoder.container(keyedBy: CodingKeys.self)
    switch self {
    case let .flag(a1):
      var unkeyedContainer = container.nestedUnkeyedContainer(forKey: .flag)
      try unkeyedContainer.encode(a1)
    case let .path(a1):
      var unkeyedContainer = container.nestedUnkeyedContainer(forKey: .path)
      try unkeyedContainer.encode(a1)
    case let .responseFilePath(a1):
      var unkeyedContainer = container.nestedUnkeyedContainer(forKey: .responseFilePath)
      try unkeyedContainer.encode(a1)
    case let .joinedOptionAndPath(option, path):
      var keyedContainer = container.nestedContainer(
        keyedBy: CodingKeys.JoinedOptionAndPathCodingKeys.self,
        forKey: .joinedOptionAndPath)
      try keyedContainer.encode(option, forKey: .option)
      try keyedContainer.encode(path, forKey: .path)
    case .squashedArgumentList(option: let option, args: let args):
      var keyedContainer = container.nestedContainer(
        keyedBy: CodingKeys.SquashedArgumentListCodingKeys.self,
        forKey: .squashedArgumentList)
      try keyedContainer.encode(option, forKey: .option)
      try keyedContainer.encode(args, forKey: .args)
    }
  }

  public init(from decoder: Decoder) throws {
    let values = try decoder.container(keyedBy: CodingKeys.self)
    guard let key = values.allKeys.first(where: values.contains) else {
      throw DecodingError.dataCorrupted(.init(codingPath: decoder.codingPath, debugDescription: "Did not find a matching key"))
    }
    switch key {
    case .flag:
      var unkeyedValues = try values.nestedUnkeyedContainer(forKey: key)
      let a1 = try unkeyedValues.decode(String.self)
      self = .flag(a1)
    case .path:
      var unkeyedValues = try values.nestedUnkeyedContainer(forKey: key)
      let a1 = try unkeyedValues.decode(VirtualPath.self)
      self = .path(a1)
    case .responseFilePath:
      var unkeyedValues = try values.nestedUnkeyedContainer(forKey: key)
      let a1 = try unkeyedValues.decode(VirtualPath.self)
      self = .responseFilePath(a1)
    case .joinedOptionAndPath:
      let keyedValues = try values.nestedContainer(
        keyedBy: CodingKeys.JoinedOptionAndPathCodingKeys.self,
        forKey: .joinedOptionAndPath)
      self = .joinedOptionAndPath(try keyedValues.decode(String.self, forKey: .option),
                                  try keyedValues.decode(VirtualPath.self, forKey: .path))
    case .squashedArgumentList:
      let keyedValues = try values.nestedContainer(
        keyedBy: CodingKeys.SquashedArgumentListCodingKeys.self,
        forKey: .squashedArgumentList)
      self = .squashedArgumentList(option: try keyedValues.decode(String.self, forKey: .option),
                                   args: try keyedValues.decode([Job.ArgTemplate].self, forKey: .args))
    }
  }
}