File: BuildRecord.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 (303 lines) | stat: -rw-r--r-- 10,519 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
//===--------------- BuildRecord.swift - Swift Input File Info Map -------===//
//
// 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 class TSCBasic.DiagnosticsEngine
import struct TSCBasic.AbsolutePath
import struct TSCBasic.Diagnostic

@_implementationOnly import Yams

/// Holds the info about inputs needed to plan incremenal compilation
/// A.k.a. BuildRecord was the legacy name
public struct BuildRecord {
  public let swiftVersion: String
  /// When testing, the argsHash may be missing from the build record
  public let argsHash: String
  /// Next compile, will compare an input mod time against the start time of the previous build
  public let buildStartTime: TimePoint
  /// Next compile, will compare an output mod time against the end time of the previous build
  public let buildEndTime: TimePoint
  /// The date is the modification time of the main input file the last time the driver ran
  public let inputInfos: [VirtualPath: InputInfo]

  public init(argsHash: String,
              swiftVersion: String,
              buildStartTime: TimePoint,
              buildEndTime: TimePoint,
              inputInfos: [VirtualPath: InputInfo]) {
    self.argsHash = argsHash
    self.swiftVersion = swiftVersion
    self.buildStartTime = buildStartTime
    self.buildEndTime = buildEndTime
    self.inputInfos = inputInfos
  }

  public enum SectionName: String, CaseIterable {
    case swiftVersion = "version"
    case argsHash = "options"
    // Implement this for a smoother transition
    case legacyBuildStartTime = "build_time"
    case buildStartTime = "build_start_time"
    case buildEndTime = "build_end_time"
    case inputInfos = "inputs"

    var serializedName: String { rawValue }
  }

  var allInputs: Set<VirtualPath> {
    Set(inputInfos.map { $0.key })
  }
}

// MARK: - Reading the old map and deciding whether to use it
public extension BuildRecord {
  enum Error: Swift.Error {
    case malformedYAML
    case invalidKey
    case missingTimeStamp
    case missingInputSequenceNode
    case missingInputEntryNode
    case missingPriorBuildState
    case unexpectedKey(String)
    case malformed(SectionName)

    var reason: String {
      switch self {
      case .malformedYAML:
        return ""
      case .invalidKey:
        return ""
      case .missingTimeStamp:
        return "could not read time value in build record"
      case .missingInputSequenceNode:
        return "no sequence node for input entry in build record"
      case .missingInputEntryNode:
        return "no input entry in build record"
      case .missingPriorBuildState:
        return "no previous build state in build record"
      case .unexpectedKey(let key):
        return "Unexpected key '\(key)'"
      case .malformed(let section):
        return "Malformed value for key '\(section.serializedName)'"
      }
    }
  }
  init(contents: String) throws {
    guard let sections = try? Parser(yaml: contents, resolver: .basic, encoding: .utf8)
            .singleRoot()?.mapping
    else {
      throw Error.malformedYAML
    }
    var argsHash: String?
    var swiftVersion: String?
    // Legacy driver does not disable incremental if no buildTime field.
    var buildStartTime: TimePoint = .distantPast
    var buildEndTime: TimePoint = .distantFuture
    var inputInfos: [VirtualPath: InputInfo]?
    for (key, value) in sections {
      guard let k = key.string else {
        throw Error.invalidKey
      }
      switch k {
      case SectionName.swiftVersion.serializedName:
        // There's a test that uses "" for an illegal value
        guard let s = value.string, s != "" else {
          break
        }
        swiftVersion = s
      case SectionName.argsHash.serializedName:
        guard let s = value.string, s != "" else {
          break
        }
        argsHash = s
      case SectionName.buildStartTime.serializedName,
           SectionName.legacyBuildStartTime.serializedName:
        buildStartTime = try Self.decodeDate(value, forInputInfo: false)
      case SectionName.buildEndTime.serializedName:
        buildEndTime = try Self.decodeDate(value, forInputInfo: false)
      case SectionName.inputInfos.serializedName:
        inputInfos = try Self.decodeInputInfos(value)
      default:
        throw Error.unexpectedKey(k)
      }
    }
    // The legacy driver allows argHash to be absent to ease testing.
    // Mimic the legacy driver for testing ease: If no `argsHash` section,
    // record still matches.
    guard let sv = swiftVersion else {
      throw Error.malformed(.swiftVersion)
    }
    guard let iis = inputInfos else {
      throw Error.malformed(.inputInfos)
    }
    guard let argsHash = argsHash else {
      throw Error.malformed(.argsHash)
    }
    self.init(argsHash: argsHash,
              swiftVersion: sv,
              buildStartTime: buildStartTime,
              buildEndTime: buildEndTime,
              inputInfos: iis)
  }

  private static func decodeDate(
    _ node: Yams.Node,
    forInputInfo: Bool
  ) throws -> TimePoint {
    guard let vals = node.sequence else {
      if forInputInfo {
        throw Error.missingInputSequenceNode
      } else {
        throw Error.missingTimeStamp
      }
    }
    guard vals.count == 2,
          let secs = vals[0].int,
          let ns = vals[1].int
    else {
      throw Error.missingTimeStamp
    }
    return TimePoint(seconds: UInt64(secs), nanoseconds: UInt32(ns))
  }

  private static func decodeInputInfos(
    _ node: Yams.Node
  ) throws -> [VirtualPath: InputInfo] {
    guard let map = node.mapping else {
      throw BuildRecord.Error.malformed(.inputInfos)
    }
    var infos = [VirtualPath: InputInfo]()
    for (keyNode, valueNode) in map {
      guard let pathString = keyNode.string,
            let path = try? VirtualPath(path: pathString)
      else {
        throw BuildRecord.Error.missingInputEntryNode
      }
      let previousModTime = try decodeDate(valueNode, forInputInfo: true)
      let inputInfo = try InputInfo(
        tag: valueNode.tag.description, previousModTime: previousModTime)
      infos[path] = inputInfo
    }
    return infos
   }
}

// MARK: - Creating and writing a new map
extension BuildRecord {
  /// Create a new buildRecord for writing
  init(jobs: [Job],
       finishedJobResults: [BuildRecordInfo.JobResult],
       skippedInputs: Set<TypedVirtualPath>?,
       compilationInputModificationDates: [TypedVirtualPath: TimePoint],
       actualSwiftVersion: String,
       argsHash: String,
       timeBeforeFirstJob: TimePoint,
       timeAfterLastJob: TimePoint
  ) {
    let jobResultsByInput = Dictionary(uniqueKeysWithValues:
      finishedJobResults.flatMap { entry in
        entry.job.inputsGeneratingCode.map { ($0, entry.result) }
    })
    let inputInfosArray = compilationInputModificationDates
      .map { input, modDate -> (VirtualPath, InputInfo) in
        let status = InputInfo.Status(  wasSkipped: skippedInputs?.contains(input),
                                        jobResult: jobResultsByInput[input])
        return (input.file, InputInfo(status: status, previousModTime: modDate))
      }

    self.init(
      argsHash: argsHash,
      swiftVersion: actualSwiftVersion,
      buildStartTime: timeBeforeFirstJob,
      buildEndTime: timeAfterLastJob,
      inputInfos: Dictionary(uniqueKeysWithValues: inputInfosArray)
    )
  }

  /// Pass in `currentArgsHash` to ensure it is non-nil
  public func encode(diagnosticEngine: DiagnosticsEngine) -> String? {
      let pathsAndInfos = inputInfos.map {
        input, inputInfo -> (String, InputInfo) in
        return (input.name, inputInfo)
      }
      let inputInfosNode = Yams.Node(
        pathsAndInfos
          .sorted {$0.0 < $1.0}
          .map {(Yams.Node($0.0, .implicit, .doubleQuoted), Self.encode($0.1))}
      )
    let fieldNodes = [
      (SectionName.swiftVersion,    Yams.Node(swiftVersion,    .implicit, .doubleQuoted)),
      (SectionName.argsHash,        Yams.Node(argsHash, .implicit, .doubleQuoted)),
      (SectionName.buildStartTime,  Self.encode(buildStartTime)),
      (SectionName.buildEndTime,    Self.encode(buildEndTime)),
      (SectionName.inputInfos,      inputInfosNode )
      ] .map { (Yams.Node($0.0.serializedName), $0.1) }

    let buildRecordNode = Yams.Node(fieldNodes, .implicit, .block)
   // let options = Yams.Emitter.Options(canonical: true)
    do {
      return try Yams.serialize(node: buildRecordNode,
                                width: -1,
                                sortKeys: false)
    } catch {
      diagnosticEngine.emit(.warning_could_not_serialize_build_record(error))
      return nil
    }
  }

  private static func encode(_ date: TimePoint, tag tagString: String? = nil) -> Yams.Node {
    return Yams.Node(
      [ Yams.Node(String(date.seconds)), Yams.Node(String(date.nanoseconds)) ],
      tagString.map {Yams.Tag(Yams.Tag.Name(rawValue: $0))} ?? .implicit,
      .flow)
  }

  private static func encode(_ inputInfo: InputInfo) -> Yams.Node {
    encode(inputInfo.previousModTime, tag: inputInfo.tag)
  }

}

extension Diagnostic.Message {
  static func warning_could_not_serialize_build_record(_ err: Error
  ) -> Diagnostic.Message {
    .warning("next compile won't be incremental; Could not serialize build record: \(err.localizedDescription)")
  }
  static func warning_could_not_write_build_record_not_absolutePath(
    _ path: VirtualPath
  ) -> Diagnostic.Message {
    .warning("next compile won't be incremental; build record path was not absolute: \(path)")
  }
  static func warning_could_not_write_build_record(_ path: AbsolutePath
  ) -> Diagnostic.Message {
    .warning("next compile won't be incremental; could not write build record to \(path)")
  }
}


// MARK: - reading
extension InputInfo {
  fileprivate init(
    tag: String,
    previousModTime: TimePoint
  ) throws {
    guard let status = Status(identifier: tag) else {
      throw BuildRecord.Error.missingPriorBuildState
    }
    self.init(status: status, previousModTime: previousModTime)
  }
}

// MARK: - writing
extension InputInfo {
  fileprivate var tag: String { status.identifier }
}