forked from swiftlang/swift-driver
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathExplicitDependencyBuildPlanner.swift
590 lines (533 loc) · 27.9 KB
/
ExplicitDependencyBuildPlanner.swift
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
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
//===--------------- ExplicitDependencyBuildPlanner.swift ---------------------===//
//
// 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 struct TSCBasic.SHA256
import struct TSCBasic.AbsolutePath
import struct Foundation.Data
import class Foundation.JSONEncoder
/// Details about an external target, including the path to its .swiftmodule file
/// and whether it is a framework.
public struct ExternalTargetModuleDetails {
public init(path: AbsolutePath, isFramework: Bool) {
self.path = path
self.isFramework = isFramework
}
let path: AbsolutePath
let isFramework: Bool
}
public typealias ExternalTargetModuleDetailsMap = [ModuleDependencyId: ExternalTargetModuleDetails]
/// In Explicit Module Build mode, this planner is responsible for generating and providing
/// build jobs for all module dependencies and providing compile command options
/// that specify said explicit module dependencies.
@_spi(Testing) public struct ExplicitDependencyBuildPlanner {
/// The module dependency graph.
private let dependencyGraph: InterModuleDependencyGraph
/// A set of direct and transitive dependencies for every module in the dependency graph
private let reachabilityMap: [ModuleDependencyId : Set<ModuleDependencyId>]
/// The toolchain to be used for frontend job generation.
private let toolchain: Toolchain
/// Whether we are using the integrated driver via libSwiftDriver shared lib
private let integratedDriver: Bool
private let mainModuleName: String?
private let cas: SwiftScanCAS?
private let swiftScanOracle: InterModuleDependencyOracle
/// Clang PCM names contain a hash of the command-line arguments that were used to build them.
/// We avoid re-running the hash computation with the use of this cache
private var hashedModuleNameCache: [String: String] = [:]
/// Does this compile support `.explicitInterfaceModuleBuild`
private var supportsExplicitInterfaceBuild: Bool
/// Cached command-line additions for all main module compile jobs
private struct ResolvedModuleDependenciesCommandLineComponents {
let inputs: [TypedVirtualPath]
let commandLine: [Job.ArgTemplate]
}
private var resolvedMainModuleDependenciesArgs: ResolvedModuleDependenciesCommandLineComponents? = nil
public init(dependencyGraph: InterModuleDependencyGraph,
toolchain: Toolchain,
dependencyOracle: InterModuleDependencyOracle,
integratedDriver: Bool = true,
supportsExplicitInterfaceBuild: Bool = false,
cas: SwiftScanCAS? = nil) throws {
self.dependencyGraph = dependencyGraph
self.toolchain = toolchain
self.swiftScanOracle = dependencyOracle
self.integratedDriver = integratedDriver
self.mainModuleName = dependencyGraph.mainModuleName
self.reachabilityMap = try dependencyGraph.computeTransitiveClosure()
self.supportsExplicitInterfaceBuild = supportsExplicitInterfaceBuild
self.cas = cas
}
/// Supports resolving bridging header pch command from swiftScan.
public func supportsBridgingHeaderPCHCommand() throws -> Bool {
return try swiftScanOracle.supportsBridgingHeaderPCHCommand()
}
/// Generate build jobs for all dependencies of the main module.
/// The main module itself is handled elsewhere in the driver.
///
/// The main source of complexity in this procedure is versioning of Clang dependency PCMs.
/// There exists a strict limitation that a compatible PCM must have the exact same target version
/// with the loading module (either a Swift module or another PCM). This means that each PCM may
/// have to be built multiple times, once for each unique (SDK, architecture, toolchain) tuple
/// of some loading module.
///
/// For example:
/// Main (target: 10.13) depends on ClangA, SwiftB, SwiftC, SwiftD, ClangD
/// SwiftB (target: 10.12) depends on ClangB, SwiftC
/// SwiftC (target: 10.11) depends on ClangC
/// SwiftD (target: 10.10) depends on ClangD
/// (Clang{A,B,C,D} are leaf modules)
/// If the task is to build `main`, the Clang modules in this example have the following "uses":
/// ClangA is used directly by Main.
/// ClangB is used directly by SwiftB and transitively by Main.
/// ClangC is used directly by SwiftC and transitively by Main and SwiftB.
/// ClangD is used directly by SwiftD and Main.
/// Given the individual targets of the uses, the following versions of the Clang modules must
/// be built:
/// ClangA: (10.13)
/// ClangB: (10.12, 10.13)
/// ClangC: (10.11, 10.12, 10.13)
/// ClangD: (10.10, 10.13)
///
/// Due to this requirement, we generate jobs for main main module dependencies in two stages:
/// 1. Generate jobs for all Swift modules, accumulating, for each Clang dependency, the depending Swift
/// module's target version (PCM Args).
/// 2. Generate jobs for all Clang modules, now that we have each module's set of PCM versions it must be
/// built against.
public mutating func generateExplicitModuleDependenciesBuildJobs() throws -> [Job] {
let mainModuleId: ModuleDependencyId = .swift(dependencyGraph.mainModuleName)
guard let mainModuleDependencies = reachabilityMap[mainModuleId] else {
fatalError("Expected reachability information for the main module.")
}
let swiftDependenciesJobs =
try generateSwiftDependenciesBuildJobs(for: mainModuleDependencies)
// Generate build jobs for all Clang modules
let clangDependenciesJobs =
try generateClangDependenciesBuildJobs(for: mainModuleDependencies)
return swiftDependenciesJobs + clangDependenciesJobs
}
/// Generate a build job for each Swift module in the set of supplied `dependencies`
private mutating func generateSwiftDependenciesBuildJobs(for dependencies: Set<ModuleDependencyId>)
throws -> [Job] {
var jobs: [Job] = []
let swiftDependencies = dependencies.filter {
if case .swift(_) = $0 {
return true
}
return false
}
for moduleId in swiftDependencies {
let moduleInfo = try dependencyGraph.moduleInfo(of: moduleId)
var inputs: [TypedVirtualPath] = []
var commandLine: [Job.ArgTemplate] = []
// First, take the command line options provided in the dependency information
let moduleDetails = try dependencyGraph.swiftModuleDetails(of: moduleId)
moduleDetails.commandLine?.forEach { commandLine.appendFlags($0) }
// Resolve all dependency module inputs for this Swift module
try resolveExplicitModuleDependencies(moduleId: moduleId,
inputs: &inputs,
commandLine: &commandLine)
// Build the .swiftinterfaces file using a list of command line options specified in the
// `details` field.
guard let moduleInterfacePath = moduleDetails.moduleInterfacePath else {
throw Driver.Error.malformedModuleDependency(moduleId.moduleName,
"no `moduleInterfacePath` object")
}
let inputInterfacePath = TypedVirtualPath(file: moduleInterfacePath.path, type: .swiftInterface)
inputs.append(inputInterfacePath)
let outputModulePath = TypedVirtualPath(file: moduleInfo.modulePath.path, type: .swiftModule)
let outputs = [outputModulePath]
let cacheKeys : [TypedVirtualPath : String]
if let key = moduleDetails.moduleCacheKey {
cacheKeys = [inputInterfacePath: key]
} else {
cacheKeys = [:]
}
// Add precompiled module candidates, if present
if let compiledCandidateList = moduleDetails.compiledModuleCandidates {
for compiledCandidate in compiledCandidateList {
inputs.append(TypedVirtualPath(file: compiledCandidate.path,
type: .swiftModule))
}
}
jobs.append(Job(
moduleName: moduleId.moduleName,
kind: .compileModuleFromInterface,
tool: try toolchain.resolvedTool(.swiftCompiler),
commandLine: commandLine,
inputs: inputs,
primaryInputs: [],
outputs: outputs,
outputCacheKeys: cacheKeys
))
}
return jobs
}
/// Generate a build job for each Clang module in the set of supplied `dependencies`. Once per each required
/// PCMArgSet as queried from the supplied `clangPCMSetMap`
private mutating func generateClangDependenciesBuildJobs(for dependencies: Set<ModuleDependencyId>)
throws -> [Job] {
var jobs: [Job] = []
let clangDependencies = dependencies.filter {
if case .clang(_) = $0 {
return true
}
return false
}
for moduleId in clangDependencies {
let moduleInfo = try dependencyGraph.moduleInfo(of: moduleId)
// Generate a distinct job for each required set of PCM Arguments for this module
var inputs: [TypedVirtualPath] = []
var outputs: [TypedVirtualPath] = []
var commandLine: [Job.ArgTemplate] = []
// First, take the command line options provided in the dependency information
let moduleDetails = try dependencyGraph.clangModuleDetails(of: moduleId)
moduleDetails.commandLine.forEach { commandLine.appendFlags($0) }
// Resolve all dependency module inputs for this Clang module
try resolveExplicitModuleDependencies(moduleId: moduleId, inputs: &inputs,
commandLine: &commandLine)
let moduleMapPath = TypedVirtualPath(file: moduleDetails.moduleMapPath.path, type: .clangModuleMap)
let modulePCMPath = TypedVirtualPath(file: moduleInfo.modulePath.path, type: .pcm)
outputs.append(modulePCMPath)
// The only required input is the .modulemap for this module.
// Command line options in the dependency scanner output will include the
// required modulemap, so here we must only add it to the list of inputs.
let cacheKeys : [TypedVirtualPath : String]
if let key = moduleDetails.moduleCacheKey {
cacheKeys = [moduleMapPath: key]
} else {
cacheKeys = [:]
}
jobs.append(Job(
moduleName: moduleId.moduleName,
kind: .generatePCM,
tool: try toolchain.resolvedTool(.swiftCompiler),
commandLine: commandLine,
inputs: inputs,
primaryInputs: [],
outputs: outputs,
outputCacheKeys: cacheKeys
))
}
return jobs
}
/// For the specified module, update the given command line flags and inputs
/// to use explicitly-built module dependencies.
private mutating func resolveExplicitModuleDependencies(moduleId: ModuleDependencyId,
inputs: inout [TypedVirtualPath],
commandLine: inout [Job.ArgTemplate]) throws {
// Prohibit the frontend from implicitly building textual modules into binary modules.
var swiftDependencyArtifacts: [SwiftModuleArtifactInfo] = []
var clangDependencyArtifacts: [ClangModuleArtifactInfo] = []
try addModuleDependencies(of: moduleId,
clangDependencyArtifacts: &clangDependencyArtifacts,
swiftDependencyArtifacts: &swiftDependencyArtifacts)
// Each individual module binary is still an "input" to ensure the build system gets the
// order correctly.
for dependencyModule in swiftDependencyArtifacts {
inputs.append(TypedVirtualPath(file: dependencyModule.modulePath.path,
type: .swiftModule))
let prebuiltHeaderDependencyPaths = dependencyModule.prebuiltHeaderDependencyPaths ?? []
if cas != nil && !prebuiltHeaderDependencyPaths.isEmpty {
throw DependencyScanningError.unsupportedConfigurationForCaching("module \(dependencyModule.moduleName) has bridging header dependency")
}
for headerDep in prebuiltHeaderDependencyPaths {
commandLine.appendFlags(["-Xcc", "-include-pch", "-Xcc"])
commandLine.appendPath(VirtualPath.lookup(headerDep.path))
inputs.append(TypedVirtualPath(file: headerDep.path, type: .pch))
}
}
// Clang module dependencies are specified on the command line explicitly
for moduleArtifactInfo in clangDependencyArtifacts {
let clangModulePath =
TypedVirtualPath(file: moduleArtifactInfo.clangModulePath.path,
type: .pcm)
inputs.append(clangModulePath)
}
// Swift Main Module dependencies are passed encoded in a JSON file as described by
// SwiftModuleArtifactInfo
guard moduleId == .swift(dependencyGraph.mainModuleName) else { return }
let dependencyFileContent =
try serializeModuleDependencies(for: moduleId,
swiftDependencyArtifacts: swiftDependencyArtifacts,
clangDependencyArtifacts: clangDependencyArtifacts)
if let cas = self.cas {
// When using a CAS, write JSON into CAS and pass the ID on command-line.
let casID = try cas.store(data: dependencyFileContent)
commandLine.appendFlag("-explicit-swift-module-map-file")
commandLine.appendFlag(casID)
} else {
// Write JSON to a file and add the JSON artifacts to command-line and inputs.
let dependencyFile =
try VirtualPath.createUniqueTemporaryFileWithKnownContents(.init(validating: "\(moduleId.moduleName)-dependencies.json"),
dependencyFileContent)
commandLine.appendFlag("-explicit-swift-module-map-file")
commandLine.appendPath(dependencyFile)
inputs.append(TypedVirtualPath(file: dependencyFile.intern(),
type: .jsonSwiftArtifacts))
}
}
private mutating func addModuleDependency(of moduleId: ModuleDependencyId,
dependencyId: ModuleDependencyId,
clangDependencyArtifacts: inout [ClangModuleArtifactInfo],
swiftDependencyArtifacts: inout [SwiftModuleArtifactInfo]
) throws {
switch dependencyId {
case .swift:
let dependencyInfo = try dependencyGraph.moduleInfo(of: dependencyId)
let swiftModulePath: TypedVirtualPath
let isFramework: Bool
swiftModulePath = .init(file: dependencyInfo.modulePath.path,
type: .swiftModule)
let swiftModuleDetails = try dependencyGraph.swiftModuleDetails(of: dependencyId)
isFramework = swiftModuleDetails.isFramework ?? false
// Accumulate the required information about this dependency
// TODO: add .swiftdoc and .swiftsourceinfo for this module.
swiftDependencyArtifacts.append(
SwiftModuleArtifactInfo(name: dependencyId.moduleName,
modulePath: TextualVirtualPath(path: swiftModulePath.fileHandle),
isFramework: isFramework,
moduleCacheKey: swiftModuleDetails.moduleCacheKey))
case .clang:
let dependencyInfo = try dependencyGraph.moduleInfo(of: dependencyId)
let dependencyClangModuleDetails =
try dependencyGraph.clangModuleDetails(of: dependencyId)
// Accumulate the required information about this dependency
clangDependencyArtifacts.append(
ClangModuleArtifactInfo(name: dependencyId.moduleName,
modulePath: TextualVirtualPath(path: dependencyInfo.modulePath.path),
moduleMapPath: dependencyClangModuleDetails.moduleMapPath,
moduleCacheKey: dependencyClangModuleDetails.moduleCacheKey))
case .swiftPrebuiltExternal:
let prebuiltModuleDetails = try dependencyGraph.swiftPrebuiltDetails(of: dependencyId)
let compiledModulePath = prebuiltModuleDetails.compiledModulePath
let isFramework = prebuiltModuleDetails.isFramework ?? false
let swiftModulePath: TypedVirtualPath =
.init(file: compiledModulePath.path, type: .swiftModule)
// Accumulate the required information about this dependency
// TODO: add .swiftdoc and .swiftsourceinfo for this module.
swiftDependencyArtifacts.append(
SwiftModuleArtifactInfo(name: dependencyId.moduleName,
modulePath: TextualVirtualPath(path: swiftModulePath.fileHandle),
headerDependencies: prebuiltModuleDetails.headerDependencyPaths,
isFramework: isFramework,
moduleCacheKey: prebuiltModuleDetails.moduleCacheKey))
case .swiftPlaceholder:
fatalError("Unresolved placeholder dependencies at planning stage: \(dependencyId) of \(moduleId)")
}
}
/// Add a specific module dependency as an input and a corresponding command
/// line flag.
private mutating func addModuleDependencies(of moduleId: ModuleDependencyId,
clangDependencyArtifacts: inout [ClangModuleArtifactInfo],
swiftDependencyArtifacts: inout [SwiftModuleArtifactInfo]
) throws {
guard let moduleDependencies = reachabilityMap[moduleId] else {
fatalError("Expected reachability information for the module: \(moduleId.moduleName).")
}
for dependencyId in moduleDependencies {
try addModuleDependency(of: moduleId, dependencyId: dependencyId,
clangDependencyArtifacts: &clangDependencyArtifacts,
swiftDependencyArtifacts: &swiftDependencyArtifacts)
}
}
private func updateClangPCMArgSetMap(for moduleId: ModuleDependencyId,
clangPCMSetMap: inout [ModuleDependencyId : Set<[String]>])
throws {
guard let moduleDependencies = reachabilityMap[moduleId] else {
fatalError("Expected reachability information for the module: \(moduleId.moduleName).")
}
let pcmArgs = try dependencyGraph.swiftModulePCMArgs(of: moduleId)
for dependencyId in moduleDependencies {
guard case .clang(_) = dependencyId else {
continue
}
if clangPCMSetMap[dependencyId] != nil {
clangPCMSetMap[dependencyId]!.insert(pcmArgs)
} else {
clangPCMSetMap[dependencyId] = [pcmArgs]
}
}
}
/// Resolve all module dependencies of the main module and add them to the lists of
/// inputs and command line flags.
public mutating func resolveMainModuleDependencies(inputs: inout [TypedVirtualPath],
commandLine: inout [Job.ArgTemplate]) throws {
// If not previously computed, gather all dependency input files and command-line arguments
if resolvedMainModuleDependenciesArgs == nil {
var inputAdditions: [TypedVirtualPath] = []
var commandLineAdditions: [Job.ArgTemplate] = []
let mainModuleId: ModuleDependencyId = .swift(dependencyGraph.mainModuleName)
let mainModuleDetails = try dependencyGraph.swiftModuleDetails(of: mainModuleId)
if let additionalArgs = mainModuleDetails.commandLine {
additionalArgs.forEach { commandLineAdditions.appendFlag($0) }
}
commandLineAdditions.appendFlags("-disable-implicit-swift-modules",
"-Xcc", "-fno-implicit-modules",
"-Xcc", "-fno-implicit-module-maps")
try resolveExplicitModuleDependencies(moduleId: mainModuleId,
inputs: &inputAdditions,
commandLine: &commandLineAdditions)
resolvedMainModuleDependenciesArgs = ResolvedModuleDependenciesCommandLineComponents(
inputs: inputAdditions,
commandLine: commandLineAdditions
)
}
guard let mainModuleDependenciesArgs = resolvedMainModuleDependenciesArgs else {
fatalError("Failed to compute resolved explicit dependency arguments.")
}
inputs.append(contentsOf: mainModuleDependenciesArgs.inputs)
commandLine.append(contentsOf: mainModuleDependenciesArgs.commandLine)
}
/// Get the context hash for the main module.
public func getMainModuleContextHash() throws -> String? {
let mainModuleId: ModuleDependencyId = .swift(dependencyGraph.mainModuleName)
let mainModuleDetails = try dependencyGraph.swiftModuleDetails(of: mainModuleId)
return mainModuleDetails.contextHash
}
/// Resolve all module dependencies of the main module and add them to the lists of
/// inputs and command line flags.
public mutating func resolveBridgingHeaderDependencies(inputs: inout [TypedVirtualPath],
commandLine: inout [Job.ArgTemplate]) throws {
let mainModuleId: ModuleDependencyId = .swift(dependencyGraph.mainModuleName)
var swiftDependencyArtifacts: [SwiftModuleArtifactInfo] = []
var clangDependencyArtifacts: [ClangModuleArtifactInfo] = []
let mainModuleDetails = try dependencyGraph.swiftModuleDetails(of: mainModuleId)
var addedDependencies: Set<ModuleDependencyId> = []
var dependenciesWorklist = mainModuleDetails.bridgingHeaderDependencies ?? []
while !dependenciesWorklist.isEmpty {
guard let bridgingHeaderDepID = dependenciesWorklist.popLast() else {
break
}
guard !addedDependencies.contains(bridgingHeaderDepID) else {
continue
}
addedDependencies.insert(bridgingHeaderDepID)
try addModuleDependency(of: mainModuleId, dependencyId: bridgingHeaderDepID,
clangDependencyArtifacts: &clangDependencyArtifacts,
swiftDependencyArtifacts: &swiftDependencyArtifacts)
try addModuleDependencies(of: bridgingHeaderDepID,
clangDependencyArtifacts: &clangDependencyArtifacts,
swiftDependencyArtifacts: &swiftDependencyArtifacts)
let depInfo = try dependencyGraph.moduleInfo(of: bridgingHeaderDepID)
dependenciesWorklist.append(contentsOf: depInfo.directDependencies ?? [])
}
// Clang module dependencies are specified on the command line explicitly
for moduleArtifactInfo in clangDependencyArtifacts {
let clangModulePath =
TypedVirtualPath(file: moduleArtifactInfo.clangModulePath.path,
type: .pcm)
inputs.append(clangModulePath)
}
// Return if depscanner provided build commands.
if let scannerPCHArgs = mainModuleDetails.bridgingPchCommandLine {
scannerPCHArgs.forEach { commandLine.appendFlag($0) }
return
}
assert(cas == nil, "Caching build should always return command-line from scanner")
// Prohibit the frontend from implicitly building textual modules into binary modules.
commandLine.appendFlags("-disable-implicit-swift-modules",
"-Xcc", "-fno-implicit-modules",
"-Xcc", "-fno-implicit-module-maps")
let dependencyFileContent =
try serializeModuleDependencies(for: mainModuleId,
swiftDependencyArtifacts: swiftDependencyArtifacts,
clangDependencyArtifacts: clangDependencyArtifacts)
let dependencyFile =
try VirtualPath.createUniqueTemporaryFileWithKnownContents(.init(validating: "\(mainModuleId.moduleName)-dependencies.json"),
dependencyFileContent)
commandLine.appendFlag("-explicit-swift-module-map-file")
commandLine.appendPath(dependencyFile)
inputs.append(TypedVirtualPath(file: dependencyFile.intern(),
type: .jsonSwiftArtifacts))
}
/// Serialize the output file artifacts for a given module in JSON format.
private func serializeModuleDependencies(for moduleId: ModuleDependencyId,
swiftDependencyArtifacts: [SwiftModuleArtifactInfo],
clangDependencyArtifacts: [ClangModuleArtifactInfo]
) throws -> Data {
// The module dependency map in CAS needs to be stable.
// Sort the dependencies by name.
let allDependencyArtifacts: [ModuleDependencyArtifactInfo] =
swiftDependencyArtifacts.sorted().map {ModuleDependencyArtifactInfo.swift($0)} +
clangDependencyArtifacts.sorted().map {ModuleDependencyArtifactInfo.clang($0)}
let encoder = JSONEncoder()
// Use sorted key to ensure the order of the keys is stable.
encoder.outputFormatting = [.prettyPrinted, .sortedKeys]
return try encoder.encode(allDependencyArtifacts)
}
private func getPCMHashParts(pcmArgs: [String], contextHash: String) -> [String] {
var results: [String] = []
results.append(contextHash)
results.append(contentsOf: pcmArgs)
if integratedDriver {
return results
}
// We need this to enable explicit modules in the driver-as-executable mode. For instance,
// we have two Swift targets A and B, where A depends on X.pcm which in turn depends on Y.pcm,
// and B only depends on Y.pcm. In the driver-as-executable mode, the build system isn't aware
// of the shared dependency of Y.pcm so it will be generated multiple times. If all these Y.pcm
// share the same name, X.pcm may fail to be loaded because its dependency Y.pcm may have a
// changed mod time.
// We only differentiate these PCM names in the non-integrated mode due to the lacking of
// inter-module planning.
results.append(mainModuleName!)
return results
}
}
/// Encapsulates some of the common queries of the ExplicitDependencyBuildPlanner with error-checking
/// on the dependency graph's structure.
@_spi(Testing) public extension InterModuleDependencyGraph {
func moduleInfo(of moduleId: ModuleDependencyId) throws -> ModuleInfo {
guard let moduleInfo = modules[moduleId] else {
throw Driver.Error.missingModuleDependency(moduleId.moduleName)
}
return moduleInfo
}
func swiftModuleDetails(of moduleId: ModuleDependencyId) throws -> SwiftModuleDetails {
guard case .swift(let swiftModuleDetails) = try moduleInfo(of: moduleId).details else {
throw Driver.Error.malformedModuleDependency(moduleId.moduleName, "no Swift `details` object")
}
return swiftModuleDetails
}
func swiftPrebuiltDetails(of moduleId: ModuleDependencyId)
throws -> SwiftPrebuiltExternalModuleDetails {
guard case .swiftPrebuiltExternal(let prebuiltModuleDetails) =
try moduleInfo(of: moduleId).details else {
throw Driver.Error.malformedModuleDependency(moduleId.moduleName,
"no SwiftPrebuiltExternal `details` object")
}
return prebuiltModuleDetails
}
func clangModuleDetails(of moduleId: ModuleDependencyId) throws -> ClangModuleDetails {
guard case .clang(let clangModuleDetails) = try moduleInfo(of: moduleId).details else {
throw Driver.Error.malformedModuleDependency(moduleId.moduleName, "no Clang `details` object")
}
return clangModuleDetails
}
func swiftModulePCMArgs(of moduleId: ModuleDependencyId) throws -> [String] {
let moduleDetails = try swiftModuleDetails(of: moduleId)
return moduleDetails.extraPcmArgs
}
}
internal extension ExplicitDependencyBuildPlanner {
func explainDependency(_ dependencyModuleName: String) throws -> [[ModuleDependencyId]]? {
return try dependencyGraph.explainDependency(dependencyModuleName: dependencyModuleName)
}
}
// InterModuleDependencyGraph printing, useful for debugging
internal extension InterModuleDependencyGraph {
func prettyPrintString() throws -> String {
let encoder = JSONEncoder()
encoder.outputFormatting = [.prettyPrinted]
let contents = try encoder.encode(self)
return String(data: contents, encoding: .utf8)!
}
}