File: SourceFileDependencyGraph.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 (385 lines) | stat: -rw-r--r-- 13,973 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
//===---SourceFileDependencyGraph.swift - Read swiftdeps or swiftmodule files ---===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2020 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.FileSystem
import struct TSCBasic.ByteString

/*@_spi(Testing)*/ public struct SourceFileDependencyGraph {
  public static let sourceFileProvidesInterfaceSequenceNumber: Int = 0
  public static let sourceFileProvidesImplementationSequenceNumber: Int = 1

  public var majorVersion: UInt64
  public var minorVersion: UInt64
  public var compilerVersionString: String
  private var allNodes: [Node]
  let internedStringTable: InternedStringTable

  public var sourceFileNodePair: (interface: Node, implementation: Node) {
    (interface: allNodes[SourceFileDependencyGraph.sourceFileProvidesInterfaceSequenceNumber],
     implementation: allNodes[SourceFileDependencyGraph.sourceFileProvidesImplementationSequenceNumber])
  }

  public func forEachNode(_ visit: (Node) -> Void) {
    allNodes.forEach(visit)
  }

  public func forEachDefDependedUpon(by node: Node, _ doIt: (Node) -> Void) {
    for sequenceNumber in node.defsIDependUpon {
      doIt(allNodes[sequenceNumber])
    }
  }

  public func forEachArc(_ doIt: (Node, Node) -> Void) {
    forEachNode { useNode in
      forEachDefDependedUpon(by: useNode) { defNode in
        doIt(defNode, useNode)
      }
    }
  }

  @discardableResult public func verify() -> Bool {
    assert(Array(allNodes.indices) == allNodes.map { $0.sequenceNumber })
    forEachNode {
      $0.verify()
    }
    return true
  }
}

extension SourceFileDependencyGraph {
  public struct Node: Equatable, Hashable {
    public let keyAndFingerprint: KeyAndFingerprintHolder
    public var key: DependencyKey { keyAndFingerprint.key }
    public var fingerprint: InternedString? { keyAndFingerprint.fingerprint }

    public let sequenceNumber: Int
    public let defsIDependUpon: [Int]
    public let definitionVsUse: DefinitionVsUse

    /*@_spi(Testing)*/ public init(
      key: DependencyKey,
      fingerprint: InternedString?,
      sequenceNumber: Int,
      defsIDependUpon: [Int],
      definitionVsUse: DefinitionVsUse
    ) throws {
      self.keyAndFingerprint = try KeyAndFingerprintHolder(key, fingerprint)
      self.sequenceNumber = sequenceNumber
      self.defsIDependUpon = defsIDependUpon
      self.definitionVsUse = definitionVsUse
    }

    public func verify() {
      key.verify()

      if case .sourceFileProvide = key.designator {
        switch key.aspect {
        case .interface:
          assert(sequenceNumber == SourceFileDependencyGraph.sourceFileProvidesInterfaceSequenceNumber)
        case .implementation:
          assert(sequenceNumber == SourceFileDependencyGraph.sourceFileProvidesImplementationSequenceNumber)
        }
      }
    }

    public func description(in holder: InternedStringTableHolder) -> String {
      let providesString = definitionVsUse == .definition ? "provides" : "depends"
      return [
        key.description(in: holder),
        fingerprint.map {"fingerprint: \($0.description(in: holder))"},
        providesString,
        defsIDependUpon.isEmpty ? nil : "depends on \(defsIDependUpon.count)"
      ]
        .compactMap{$0}
        .joined(separator: ", ")
    }
  }
}

extension SourceFileDependencyGraph {
  private enum RecordKind: UInt64 {
    case metadata = 1
    case sourceFileDepGraphNode
    case fingerprintNode
    case dependsOnDefinitionNode
    case identifierNode
  }

  fileprivate enum ReadError: Error {
    case badMagic
    case swiftModuleHasNoDependencies
    case noRecordBlock
    case malformedMetadataRecord
    case unexpectedMetadataRecord
    case malformedFingerprintRecord
    case malformedDependsOnDefinitionRecord
    case malformedIdentifierRecord
    case malformedSourceFileDepGraphNodeRecord
    case unknownRecord
    case unexpectedSubblock
    case bogusNameOrContext
    case unknownKind
  }

  /// Returns nil if there was no dependency info
  ///
  /// Warning: if the serialization format changes, it will be necessary to regenerate the `swiftdeps`
  /// files in `TestInputs/SampleSwiftDeps`.
  /// See ``CleanBuildPerformanceTests/testCleanBuildSwiftDepsPerformance``.
  static func read(
    from typedFile: TypedVirtualPath,
    on fileSystem: FileSystem,
    internedStringTable: InternedStringTable
  ) throws -> Self? {
    try self.init(contentsOf: typedFile, on: fileSystem, internedStringTable: internedStringTable)
  }

  /*@_spi(Testing)*/ public init(nodesForTesting: [Node],
                                 internedStringTable: InternedStringTable) {
    majorVersion = 0
    minorVersion = 0
    compilerVersionString = ""
    allNodes = nodesForTesting
    self.internedStringTable = internedStringTable
  }

  /*@_spi(Testing)*/ public init?(
    contentsOf typedFile: TypedVirtualPath,
    on fileSystem: FileSystem,
    internedStringTable: InternedStringTable
  ) throws {
    assert(typedFile.type == .swiftDeps || typedFile.type == .swiftModule)
    let data = try fileSystem.readFileContents(typedFile.file)
    try self.init(internedStringTable: internedStringTable,
                  data: data,
                  fromSwiftModule: typedFile.type == .swiftModule)
  }

  /// Returns nil for a swiftmodule with no dependencies
  /*@_spi(Testing)*/ public init?(
    internedStringTable: InternedStringTable,
    data: ByteString,
    fromSwiftModule extractFromSwiftModule: Bool = false
  ) throws {
    struct Visitor: BitstreamVisitor, InternedStringTableHolder {
      let extractFromSwiftModule: Bool
      let internedStringTable: InternedStringTable

      init(extractFromSwiftModule: Bool,
           internedStringTable: InternedStringTable) {
        self.extractFromSwiftModule = extractFromSwiftModule
        self.internedStringTable = internedStringTable
        self.identifiers = ["".intern(in: internedStringTable)]
      }

      var nodes: [Node] = []
      var majorVersion: UInt64?
      var minorVersion: UInt64?
      var compilerVersionString: String?

      // Node ingredients
      private var key: DependencyKey?
      private var fingerprint: String?
      private var nodeSequenceNumber = 0
      private var defsNodeDependUpon: [Int] = []
      private var definitionVsUse: DefinitionVsUse = .use

      private var nextSequenceNumber = 0
      private var identifiers: [InternedString] // The empty string is hardcoded as identifiers[0]

      func validate(signature: Bitcode.Signature) throws {
        if extractFromSwiftModule {
          guard signature == .init(value: 0x0EA89CE2) else { throw ReadError.swiftModuleHasNoDependencies }
        } else {
          guard signature == .init(string: "DEPS") else { throw ReadError.badMagic }
        }
      }

      mutating func shouldEnterBlock(id: UInt64) throws -> Bool {
        if extractFromSwiftModule {
          // Enter the top-level module block, and the incremental info
          // subblock, ignoring the rest of the file.
          return id == /*Module block*/ 8 || id == /*Incremental record block*/ 196
        } else {
          guard id == /*Incremental record block*/ 8 else {
            throw ReadError.unexpectedSubblock
          }
          return true
        }
      }

      mutating func didExitBlock() throws {
        try finalizeNode()
      }
      private mutating func finalizeNode() throws {
        guard let key = key else {return}

          let defsIDependUpon: [Int] = Array(unsafeUninitializedCapacity: defsNodeDependUpon.count) { destinationBuffer, initializedCount in
            _ = destinationBuffer.initialize(from: defsNodeDependUpon)
            initializedCount = defsNodeDependUpon.count
        }
        let node = try Node(key: key,
                            fingerprint: fingerprint?.intern(in: internedStringTable),
                            sequenceNumber: nodeSequenceNumber,
                            defsIDependUpon: defsIDependUpon,
                            definitionVsUse: definitionVsUse)
        self.key = nil
        self.defsNodeDependUpon.removeAll(keepingCapacity: true)
        self.nodes.append(node)
      }
      mutating func visit(record: BitcodeElement.Record) throws {
        guard let kind = RecordKind(rawValue: record.id) else { throw ReadError.unknownRecord }
        switch kind {
        case .metadata:
          // If we've already read metadata, this is an unexpected duplicate.
          guard majorVersion == nil, minorVersion == nil, compilerVersionString == nil else {
            throw ReadError.unexpectedMetadataRecord
          }
          guard record.fields.count == 2,
                case .blob(let compilerVersionBlob) = record.payload
          else { throw ReadError.malformedMetadataRecord }

          self.majorVersion = record.fields[0]
          self.minorVersion = record.fields[1]
          self.compilerVersionString = String(decoding: compilerVersionBlob, as: UTF8.self)
        case .sourceFileDepGraphNode:
          try finalizeNode()
          let kindCode = record.fields[0]
          guard record.fields.count == 5,
                let declAspect = DependencyKey.DeclAspect(record.fields[1]),
                record.fields[2] < identifiers.count,
                record.fields[3] < identifiers.count else {
            throw ReadError.malformedSourceFileDepGraphNodeRecord
          }
          let context = identifiers[Int(record.fields[2])]
          let identifier = identifiers[Int(record.fields[3])]
            self.definitionVsUse = .deserializing(record.fields[4])
          let designator = try DependencyKey.Designator(
            kindCode: kindCode, context: context, name: identifier,
            internedStringTable: internedStringTable)
          self.key = DependencyKey(aspect: declAspect, designator: designator)
          self.fingerprint = nil
          self.nodeSequenceNumber = nextSequenceNumber
          self.defsNodeDependUpon.removeAll(keepingCapacity: true)

          nextSequenceNumber += 1
        case .fingerprintNode:
          guard key != nil,
                record.fields.count == 0,
                case .blob(let fingerprintBlob) = record.payload
          else {
            throw ReadError.malformedFingerprintRecord
          }
          self.fingerprint = String(decoding: fingerprintBlob, as: UTF8.self)
        case .dependsOnDefinitionNode:
          guard key != nil,
                record.fields.count == 1 else { throw ReadError.malformedDependsOnDefinitionRecord }
          self.defsNodeDependUpon.append(Int(record.fields[0]))
        case .identifierNode:
          guard record.fields.count == 0,
                case .blob(let identifierBlob) = record.payload
          else {
            throw ReadError.malformedIdentifierRecord
          }
          identifiers.append(String(decoding: identifierBlob, as: UTF8.self).intern(in: internedStringTable))
        }
      }
    }

    var visitor = Visitor(
      extractFromSwiftModule: extractFromSwiftModule,
      internedStringTable: internedStringTable)
    do {
      try Bitcode.read(bytes: data, using: &visitor)
    } catch ReadError.swiftModuleHasNoDependencies {
      return nil
    }
    guard let major = visitor.majorVersion,
          let minor = visitor.minorVersion,
          let versionString = visitor.compilerVersionString else {
      throw ReadError.malformedMetadataRecord
    }
    self.majorVersion = major
    self.minorVersion = minor
    self.compilerVersionString = versionString
    self.allNodes = visitor.nodes
    self.internedStringTable = internedStringTable
  }
}

// MARK: - Creating DependencyKeys
fileprivate extension DependencyKey.DeclAspect {
  init?(_ c: UInt64) {
    switch c {
    case 0: self = .interface
    case 1: self = .implementation
    default: return nil
    }
  }
}

fileprivate extension DependencyKey.Designator {
  init(kindCode: UInt64,
       context: String,
       name: String,
       internedStringTable: InternedStringTable
  ) throws {
    try self.init(kindCode: kindCode,
                  context: context.intern(in: internedStringTable),
                  name: name.intern(in: internedStringTable),
                  internedStringTable: internedStringTable)
  }

  init(kindCode: UInt64,
       context: InternedString,
       name: InternedString,
       internedStringTable: InternedStringTable) throws {
    func mustBeEmpty(_ s: InternedString) throws {
      guard s.isEmpty else { throw SourceFileDependencyGraph.ReadError.bogusNameOrContext }
    }
    switch kindCode {
    case 0:
      try mustBeEmpty(context)
      self = .topLevel(name: name)
    case 1:
      try mustBeEmpty(name)
      self = .nominal(context: context)
    case 2:
      try mustBeEmpty(name)
      self = .potentialMember(context: context)
    case 3:
      self = .member(context: context, name: name)
    case 4:
      try mustBeEmpty(context)
      self = .dynamicLookup(name: name)
    case 5:
      try mustBeEmpty(context)
      self = .externalDepend(ExternalDependency(fileName: name, internedStringTable))
    case 6:
      try mustBeEmpty(context)
      self = .sourceFileProvide(name: name)
    default: throw SourceFileDependencyGraph.ReadError.unknownKind
    }
  }
}

// MARK: - Provides or Depends

/// The frontend reports Swift dependency information about `Decl`s (declarations).
/// The reports are either for definitions or uses. The old terminology (pre-fine-grained) was `provides` vs `depends`.
public enum DefinitionVsUse {
  case definition, use

  static func deserializing(_ field: UInt64) -> Self {
    field != 0 ? .definition : .use
  }
}