-
Notifications
You must be signed in to change notification settings - Fork 1.5k
Expand file tree
/
Copy pathPackagePIFProjectBuilder+Products.swift
More file actions
1225 lines (1095 loc) · 58.7 KB
/
PackagePIFProjectBuilder+Products.swift
File metadata and controls
1225 lines (1095 loc) · 58.7 KB
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
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift open source project
//
// Copyright (c) 2025 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
import Foundation
import TSCBasic
import TSCUtility
import struct Basics.AbsolutePath
import class Basics.ObservabilitySystem
import struct Basics.SourceControlURL
import PackageLoading
import class PackageModel.BinaryModule
import class PackageModel.Manifest
import enum PackageModel.PackageCondition
import enum PackageModel.PrebuiltsPlatform
import class PackageModel.Product
import enum PackageModel.ProductType
import struct PackageModel.RegistryReleaseMetadata
import struct PackageGraph.ResolvedModule
import struct PackageGraph.ResolvedPackage
import struct PackageGraph.ResolvedProduct
import PackageLoading
import enum SwiftBuild.ProjectModel
/// Extension to create PIF **products** for a given package.
extension PackagePIFProjectBuilder {
// MARK: - Main Module Products
mutating func makeMainModuleProduct(_ product: PackageGraph.ResolvedProduct) throws {
precondition(product.isMainModuleProduct)
// We'll be infusing the product's main module into the one for the product itself.
guard let mainModule = product.mainModule, mainModule.isSourceModule else {
return
}
// Skip test products from non-root packages. libSwiftPM will stop vending them after
// target-based dependency resolution anyway but this should be fine until then.
if !pifBuilder.delegate.isRootPackage && (mainModule.type == .test || mainModule.type == .binary) {
return
}
// Determine the kind of PIF target *product type* to create for the package product.
let pifProductType: ProjectModel.Target.ProductType
let moduleOrProductType: PackagePIFBuilder.ModuleOrProductType
let synthesizedResourceGeneratingPluginInvocationResults: [PackagePIFBuilder.BuildToolPluginInvocationResult] =
[]
if [.executable, .snippet].contains(product.type) {
if let customPIFProductType = pifBuilder.delegate.customProductType(forExecutable: product.underlying) {
pifProductType = customPIFProductType
moduleOrProductType = PackagePIFBuilder.ModuleOrProductType(from: customPIFProductType)
} else {
// No custom type provider. Current behavior is to fall back on regular executable.
pifProductType = .executable
moduleOrProductType = .executable
}
} else {
// If it's not an executable product, it must currently be a test bundle.
assert(product.type == .test, "Unexpected product type: \(product.type)")
pifProductType = .unitTest
moduleOrProductType = .unitTest
}
// It's not a library product, so create a regular PIF target of the appropriate product type.
let mainModuleTargetKeyPath = try self.project.addTarget { _ in
ProjectModel.Target(
id: product.pifTargetGUID,
productType: pifProductType,
name: product.targetName(),
productName: "$(EXECUTABLE_NAME)"
)
}
do {
let mainModuleTarget = self.project[keyPath: mainModuleTargetKeyPath]
log(
.debug,
"Created target '\(mainModuleTarget.id)' of type '\(mainModuleTarget.productType)' " +
"with name '\(mainModuleTarget.name)' and product name '\(mainModuleTarget.productName)'"
)
}
// We're currently *not* handling other module targets (and SwiftPM should never return them) for
// a main-module product but, for diagnostic purposes, we warn about any that we do come across.
if product.otherModules.hasContent {
let otherModuleNames = product.otherModules.map(\.name).joined(separator: ",")
log(.debug, indent: 1, "Warning: ignored unexpected other module targets \(otherModuleNames)")
}
// Deal with any generated source files or resource files.
let generatedFiles = computePluginGeneratedFiles(
module: mainModule,
targetKeyPath: mainModuleTargetKeyPath,
addBuildToolPluginCommands: pifProductType == .application
)
if mainModule.resources.hasContent || generatedFiles.resources.hasContent {
mainModuleTargetNamesWithResources.insert(mainModule.name)
}
// Configure the target-wide build settings. The details depend on the kind of product we're building,
// but are in general the ones that are suitable for end-product artifacts such as executables and test bundles.
var settings: ProjectModel.BuildSettings = package.underlying.packageBaseBuildSettings
settings[.TARGET_NAME] = product.name
settings[.TARGET_TEMP_DIR_SUFFIX] = "-p"
settings[.PACKAGE_RESOURCE_TARGET_KIND] = "regular"
settings[.PRODUCT_NAME] = "$(TARGET_NAME)"
// We must use the main module name here instead of the product name, because they're not guranteed to be the same, and the users may have authored e.g. tests which rely on an executable's module name.
settings[.PRODUCT_MODULE_NAME] = mainModule.c99name
if product.type == .executable {
// Don't install the Swift module of the executable product, lest it conflict with the testable variant.
// The contents of the testable variant's module will exactly match the binary linked by dependencies (test targets).
// Also, multiple executable products may incorporate sources from the same executable target, while the testable
// variant of an executable target's module will always be unique, so we avoid producing conflicting copies.
settings[.SWIFT_INSTALL_MODULE] = "NO"
}
settings[.PRODUCT_BUNDLE_IDENTIFIER] = "\(self.package.identity).\(product.name)"
.spm_mangledToBundleIdentifier()
settings[.SWIFT_PACKAGE_NAME] = mainModule.packageName
if mainModule.type == .test {
settings[.BUILD_SERVER_PROTOCOL_TARGET_TAGS, default: ["$(inherited)"]].append("test")
// FIXME: we shouldn't always include both the deep and shallow bundle paths here, but for that we'll need rdar://31867023
if pifBuilder.addLocalRpaths {
settings[.LD_RUNPATH_SEARCH_PATHS] = [
"$(RPATH_ORIGIN)/Frameworks",
"$(RPATH_ORIGIN)/../Frameworks",
"$(inherited)"
]
}
settings[.GENERATE_INFOPLIST_FILE] = "YES"
settings[.SKIP_INSTALL] = "NO"
settings[.SWIFT_ACTIVE_COMPILATION_CONDITIONS].lazilyInitialize { ["$(inherited)"] }
// Enable index-while building for Swift compilations to facilitate discovery of XCTest tests.
settings[.INDEX_ENABLE_DATA_STORE] = "YES"
if mainModule.platformConstraint == .host {
// This is a macro test using prebuilts
settings[.SUPPORTED_PLATFORMS] = ["$(HOST_PLATFORM)"]
switch PrebuiltsPlatform.hostPlatform?.arch {
case .aarch64:
settings[.ARCHS] = ["arm64"]
case .x86_64:
settings[.ARCHS] = ["86_64"]
case .none:
break
}
}
} else if mainModule.type == .executable {
// Setup install path for executables if it's in root of a pure Swift package.
if pifBuilder.delegate.hostsOnlyPackages && pifBuilder.delegate.isRootPackage {
settings[.SKIP_INSTALL] = "NO"
settings[.INSTALL_PATH] = "/usr/local/bin"
settings[.LD_RUNPATH_SEARCH_PATHS] = ["$(inherited)", "@executable_path/../lib"]
}
// When the fuzzing is enabled via build request overrides, rename the entry point of executables
// so that we use the libFuzzer entrypoint.
settings[.OTHER_SWIFT_FLAGS].lazilyInitializeAndMutate(initialValue: ["$(inherited)"]) {
$0.append("$(OTHER_SWIFT_FLAGS_ENABLE_LIBFUZZER_$(ENABLE_LIBFUZZER))")
}
settings[multiple: "OTHER_SWIFT_FLAGS_ENABLE_LIBFUZZER_YES"] = ["-Xfrontend", "-entry-point-function-name", "-Xfrontend", "\(mainModule.c99name)_main"]
}
mainModule.addParseAsLibrarySettings(to: &settings, toolsVersion: package.manifest.toolsVersion, fileSystem: pifBuilder.fileSystem)
let mainTargetDeploymentTargets = mainModule.deploymentTargets(using: pifBuilder.delegate)
settings[.MACOSX_DEPLOYMENT_TARGET] = mainTargetDeploymentTargets[.macOS] ?? nil
settings[.IPHONEOS_DEPLOYMENT_TARGET] = mainTargetDeploymentTargets[.iOS] ?? nil
if let deploymentTarget_macCatalyst = mainTargetDeploymentTargets[.macCatalyst] {
settings[.IPHONEOS_DEPLOYMENT_TARGET, .macCatalyst] = deploymentTarget_macCatalyst
}
settings[.TVOS_DEPLOYMENT_TARGET] = mainTargetDeploymentTargets[.tvOS] ?? nil
settings[.WATCHOS_DEPLOYMENT_TARGET] = mainTargetDeploymentTargets[.watchOS] ?? nil
settings[.DRIVERKIT_DEPLOYMENT_TARGET] = mainTargetDeploymentTargets[.driverKit] ?? nil
settings[.XROS_DEPLOYMENT_TARGET] = mainTargetDeploymentTargets[.visionOS] ?? nil
// If the main module includes C headers, then we need to set up the HEADER_SEARCH_PATHS setting appropriately.
var headerSearchPaths: [AbsolutePath] = []
if let includeDirAbsolutePath = mainModule.includeDirAbsolutePath {
headerSearchPaths.append(includeDirAbsolutePath)
}
headerSearchPaths += generatedFiles.publicHeaderPaths
if !headerSearchPaths.isEmpty {
// Let the main module itself find its own headers.
settings[.HEADER_SEARCH_PATHS] = headerSearchPaths.map(\.pathString) + ["$(inherited)"]
for path in headerSearchPaths {
log(.debug, indent: 1, "Added '\(path)' to HEADER_SEARCH_PATHS")
}
}
// Set the appropriate language versions.
settings[.SWIFT_VERSION] = mainModule.packageSwiftLanguageVersion(manifest: packageManifest)
settings[.GCC_C_LANGUAGE_STANDARD] = mainModule.cLanguageStandard
settings[.CLANG_CXX_LANGUAGE_STANDARD] = mainModule.cxxLanguageStandard
settings[.SWIFT_ENABLE_BARE_SLASH_REGEX] = "NO"
// Create a group for the source files of the main module
// For now we use an absolute path for it, but we should really make it
// container-relative, since it's always inside the package directory.
let mainTargetSourceFileGroupKeyPath = self.project.mainGroup.addGroup { id in
ProjectModel.Group(
id: id,
path: mainModule.sourceDirAbsolutePath.pathString,
pathBase: .absolute
)
}
do {
let mainTargetSourceFileGroup = self.project.mainGroup[keyPath: mainTargetSourceFileGroupKeyPath]
log(.debug, indent: 1, "Added source file group '\(mainTargetSourceFileGroup.path)'")
}
// Add a source file reference for each of the source files, and also an indexable-file URL for each one.
// Note that the indexer requires them to have any symbolic links resolved.
var indexableFileURLs: [SourceControlURL] = []
for sourcePath in mainModule.sourceFileRelativePaths {
let sourceFileRef = self.project.mainGroup[keyPath: mainTargetSourceFileGroupKeyPath]
.addFileReference { id in
FileReference(
id: id,
path: sourcePath.pathString,
pathBase: .groupDir
)
}
self.project[keyPath: mainModuleTargetKeyPath].addSourceFile { id in
BuildFile(id: id, fileRef: sourceFileRef)
}
log(.debug, indent: 2, "Added source file '\(sourcePath)'")
indexableFileURLs.append(
SourceControlURL(fileURLWithPath: mainModule.sourceDirAbsolutePath.appending(sourcePath))
)
}
let headerFiles = Set(mainModule.headerFileAbsolutePaths)
let doccCatalogs = mainModule.underlying.doccCatalogPaths
// Add any additional source files emitted by custom build commands.
for path in generatedFiles.sources {
let sourceFileRef = self.project.mainGroup[keyPath: mainTargetSourceFileGroupKeyPath]
.addFileReference { id in
FileReference(
id: id,
path: path.pathString,
pathBase: .absolute
)
}
self.project[keyPath: mainModuleTargetKeyPath].addSourceFile { id in
BuildFile(id: id, fileRef: sourceFileRef)
}
log(.debug, indent: 2, "Added generated source file '\(path)'")
}
// Add any additional resource files emitted by synthesized build commands
let generatedResourceFiles: [String] = {
var generatedResourceFiles = generatedFiles.resources.keys.map(\.pathString)
generatedResourceFiles.append(
contentsOf: addBuildToolCommands(
from: synthesizedResourceGeneratingPluginInvocationResults,
targetKeyPath: mainModuleTargetKeyPath,
addBuildToolPluginCommands: pifProductType == .application
)
)
return generatedResourceFiles
}()
// Create a separate target to build a resource bundle for any resources files in the product's main target.
// FIXME: We should extend this to other kinds of products, but the immediate need for Swift Playgrounds Projects is for applications.
if pifProductType == .application {
let result = processResources(
for: mainModule,
sourceModuleTargetKeyPath: mainModuleTargetKeyPath,
// For application products we embed the resources directly into the PIF target.
resourceBundleTargetKeyPath: nil,
generatedResourceFiles: generatedResourceFiles
)
if result.shouldGenerateBundleAccessor {
settings[.GENERATE_RESOURCE_ACCESSORS] = "YES"
// Do not set `SWIFT_MODULE_RESOURCE_BUNDLE_AVAILABLE` here since it is just going to point to the same bundle as code.
// #bundle can use its default implementation for that.
}
if result.shouldGenerateEmbedInCodeAccessor {
settings[.GENERATE_EMBED_IN_CODE_ACCESSORS] = "YES"
}
// FIXME: We should also adjust the generated module bundle glue so that `Bundle.module` is a synonym for `Bundle.main` in this case.
} else {
let (result, resourceBundle) = try addResourceBundle(
for: mainModule,
targetKeyPath: mainModuleTargetKeyPath,
generatedResourceFiles: generatedResourceFiles
)
if let resourceBundle { self.builtModulesAndProducts.append(resourceBundle) }
if let resourceBundle = result.bundleName {
// Associate the resource bundle with the target.
settings[.PACKAGE_RESOURCE_BUNDLE_NAME] = resourceBundle
if result.shouldGenerateBundleAccessor {
settings[.GENERATE_RESOURCE_ACCESSORS] = "YES"
if mainModule.usesSwift {
settings[.SWIFT_ACTIVE_COMPILATION_CONDITIONS].lazilyInitializeAndMutate(initialValue: ["$(inherited)"]) { $0.append("SWIFT_MODULE_RESOURCE_BUNDLE_AVAILABLE") }
}
} else if mainModule.usesSwift {
settings[.SWIFT_ACTIVE_COMPILATION_CONDITIONS].lazilyInitializeAndMutate(initialValue: ["$(inherited)"]) { $0.append("SWIFT_MODULE_RESOURCE_BUNDLE_UNAVAILABLE") }
}
if result.shouldGenerateEmbedInCodeAccessor {
settings[.GENERATE_EMBED_IN_CODE_ACCESSORS] = "YES"
}
// If it's a kind of product that can contain resources, we also add a use of it.
let resourceBundleRef = self.project.mainGroup.addFileReference { id in
FileReference(id: id, path: "$(CONFIGURATION_BUILD_DIR)/\(resourceBundle).bundle")
}
if pifProductType == .bundle || pifProductType == .unitTest {
settings[.COREML_CODEGEN_LANGUAGE] = mainModule.usesSwift ? "Swift" : "Objective-C"
settings[.COREML_COMPILER_CONTAINER] = "swift-package"
self.project[keyPath: mainModuleTargetKeyPath].addResourceFile { id in
BuildFile(id: id, fileRef: resourceBundleRef)
}
log(.debug, indent: 2, "Added use of resource bundle '\(resourceBundleRef.path)'")
} else {
log(
.debug,
indent: 2,
"Ignored resource bundle '\(resourceBundleRef.path)' for main module of type \(type(of: mainModule))"
)
}
// Add build tool commands to the resource bundle target.
let mainResourceBundleTargetKeyPath = self.resourceBundleTargetKeyPath(forModuleName: mainModule.name)
let resourceBundleTargetKeyPath = mainResourceBundleTargetKeyPath ?? mainModuleTargetKeyPath
addBuildToolCommands(
module: mainModule,
sourceModuleTargetKeyPath: mainModuleTargetKeyPath,
resourceBundleTargetKeyPath: resourceBundleTargetKeyPath,
sourceFilePaths: generatedFiles.sources.map(\.self),
resourceFilePaths: generatedFiles.resources.keys.map(\.pathString)
)
} else {
// Generated resources always trigger the creation of a bundle accessor.
settings[.GENERATE_RESOURCE_ACCESSORS] = "YES"
settings[.GENERATE_EMBED_IN_CODE_ACCESSORS] = "NO"
// Do not set `SWIFT_MODULE_RESOURCE_BUNDLE_AVAILABLE` here since it is just going to point to the same bundle as code.
// #bundle can use its default implementation for that.
// If we did not create a resource bundle target,
// we still need to add build tool commands for any generated files.
addBuildToolCommands(
module: mainModule,
sourceModuleTargetKeyPath: mainModuleTargetKeyPath,
resourceBundleTargetKeyPath: mainModuleTargetKeyPath,
sourceFilePaths: generatedFiles.sources.map(\.self),
resourceFilePaths: generatedFiles.resources.keys.map(\.pathString)
)
}
}
// Handle the main target's dependencies (and link against them).
mainModule.recursivelyTraverseDependencies { dependency in
switch dependency {
case .module(let moduleDependency, let packageConditions):
// This assertion is temporarily disabled since we may see targets from
// _other_ packages, but this should be resolved; see rdar://95467710.
/* assert(moduleDependency.packageName == self.package.name) */
switch moduleDependency.type {
case .binary:
guard let binaryModule = moduleDependency.underlying as? BinaryModule else {
log(.error, "'\(moduleDependency.name)' is a binary dependency, but its underlying module was not")
break
}
let binaryFileRef = self.binaryGroup.addFileReference { id in
Self.createBinaryModuleFileReference(binaryModule, id: id)
}
let toolsVersion = self.package.manifest.toolsVersion
self.project[keyPath: mainModuleTargetKeyPath].addLibrary { id in
BuildFile(
id: id,
fileRef: binaryFileRef,
platformFilters: packageConditions.toPlatformFilter(toolsVersion: toolsVersion),
codeSignOnCopy: true,
removeHeadersOnCopy: true
)
}
log(.debug, indent: 1, "Added use of binary library '\(moduleDependency.path)'")
case .plugin:
let dependencyId = moduleDependency.pifTargetGUID
self.project[keyPath: mainModuleTargetKeyPath].common.addDependency(
on: dependencyId,
platformFilters: packageConditions
.toPlatformFilter(toolsVersion: package.manifest.toolsVersion),
linkProduct: false
)
log(.debug, indent: 1, "Added use of plugin target '\(dependencyId)'")
case .macro:
let dependencyId = moduleDependency.pifTargetGUID
self.project[keyPath: mainModuleTargetKeyPath].common.addDependency(
on: dependencyId,
platformFilters: packageConditions
.toPlatformFilter(toolsVersion: package.manifest.toolsVersion),
linkProduct: false
)
log(.debug, indent: 1, "Added dependency on product '\(dependencyId)'")
// Link with a testable version of the macro if appropriate.
if product.type == .test {
self.project[keyPath: mainModuleTargetKeyPath].common.addDependency(
on: moduleDependency.pifTargetGUID(suffix: .testable),
platformFilters: packageConditions
.toPlatformFilter(toolsVersion: package.manifest.toolsVersion),
linkProduct: true
)
log(
.debug,
indent: 1,
"Added linked dependency on target '\(moduleDependency.pifTargetGUID(suffix: .testable))'"
)
// FIXME: Manually propagate product dependencies of macros but the build system should really handle this.
moduleDependency.recursivelyTraverseDependencies { dependency in
switch dependency {
case .product(let productDependency, let packageConditions):
let isLinkable = productDependency.isLinkable
self.handleProduct(
productDependency,
with: packageConditions,
isLinkable: isLinkable,
targetKeyPath: mainModuleTargetKeyPath,
settings: &settings
)
case .module:
break
}
}
}
case .executable, .snippet:
// For executable targets, we depend on the *product* instead
// (i.e., we infuse the product's main module target into the one for the product itself).
let productDependency = modulesGraph.allProducts.only { $0.mainModule?.name == moduleDependency.name }
if let productDependency {
let productDependencyGUID = productDependency.pifTargetGUID
self.project[keyPath: mainModuleTargetKeyPath].common.addDependency(
on: productDependencyGUID,
platformFilters: packageConditions
.toPlatformFilter(toolsVersion: package.manifest.toolsVersion),
linkProduct: false
)
log(.debug, indent: 1, "Added dependency on product '\(productDependencyGUID)'")
}
// If we're linking against an executable and the tools version is new enough,
// we also link against a testable version of the executable.
if product.type == .test, self.package.manifest.toolsVersion >= .v5_5 {
let moduleDependencyGUID = moduleDependency.pifTargetGUID(suffix: .testable)
self.project[keyPath: mainModuleTargetKeyPath].common.addDependency(
on: moduleDependencyGUID,
platformFilters: packageConditions
.toPlatformFilter(toolsVersion: package.manifest.toolsVersion),
// Only link the testable version of executables which use Swift, as we do not currently support renaming entrypoints written in other languages.
linkProduct: moduleDependency.usesSwift
)
log(.debug, indent: 1, "Added linked dependency on target '\(moduleDependencyGUID)'")
}
case .library, .systemModule, .test:
if moduleDependency.type == .test && product.type == .test {
log(
.error,
"Test target '\(product.name)' cannot depend on another test target '\(moduleDependency.name)'",
)
}
let shouldLinkProduct = moduleDependency.type != .systemModule
let dependencyGUID = moduleDependency.pifTargetGUID
self.project[keyPath: mainModuleTargetKeyPath].common.addDependency(
on: dependencyGUID,
platformFilters: packageConditions
.toPlatformFilter(toolsVersion: package.manifest.toolsVersion),
linkProduct: shouldLinkProduct
)
log(
.debug,
indent: 1,
"Added \(shouldLinkProduct ? "linked " : "")dependency on target '\(dependencyGUID)'"
)
}
case .product(let productDependency, let packageConditions):
let isLinkable = productDependency.isLinkable
self.handleProduct(
productDependency,
with: packageConditions,
isLinkable: isLinkable,
targetKeyPath: mainModuleTargetKeyPath,
settings: &settings
)
}
}
// Custom source module build settings, if any.
pifBuilder.delegate.configureSourceModuleBuildSettings(sourceModule: mainModule, settings: &settings)
// Until this point the build settings for the target have been the same between debug and release
// configurations.
// The custom manifest settings might cause them to diverge.
var debugSettings: ProjectModel.BuildSettings = settings
var releaseSettings: ProjectModel.BuildSettings = settings
// Apply target-specific build settings defined in the manifest.
let allBuildSettings = mainModule.computeAllBuildSettings(observabilityScope: pifBuilder.observabilityScope, forRemotePackage: pifBuilder.delegate.isRemote)
// Apply settings using the convenience methods
allBuildSettings.apply(to: &debugSettings, for: .debug)
allBuildSettings.apply(to: &releaseSettings, for: .release)
self.project[keyPath: mainModuleTargetKeyPath].common.addBuildConfig { id in
BuildConfig(id: id, name: "Debug", settings: debugSettings)
}
self.project[keyPath: mainModuleTargetKeyPath].common.addBuildConfig { id in
BuildConfig(id: id, name: "Release", settings: releaseSettings)
}
// Collect linked binaries.
let linkedPackageBinaries: [PackagePIFBuilder.LinkedPackageBinary] = mainModule.dependencies.compactMap {
PackagePIFBuilder.LinkedPackageBinary(dependency: $0)
}
let moduleOrProduct = PackagePIFBuilder.ModuleOrProduct(
type: moduleOrProductType,
name: product.name,
moduleName: product.c99name,
pifTarget: .target(self.project[keyPath: mainModuleTargetKeyPath]),
indexableFileURLs: indexableFileURLs,
headerFiles: headerFiles,
doccCatalogs: doccCatalogs,
linkedPackageBinaries: linkedPackageBinaries,
swiftLanguageVersion: mainModule.packageSwiftLanguageVersion(manifest: packageManifest),
declaredPlatforms: self.declaredPlatforms,
deploymentTargets: mainTargetDeploymentTargets,
toolsVersion: pifBuilder.packageManifest.toolsVersion
)
self.builtModulesAndProducts.append(moduleOrProduct)
if moduleOrProductType == .unitTest {
try makeTestRunnerProduct(for: moduleOrProduct)
}
}
private mutating func handleProduct(
_ product: PackageGraph.ResolvedProduct,
with packageConditions: [PackageModel.PackageCondition],
isLinkable: Bool,
targetKeyPath: WritableKeyPath<ProjectModel.Project, ProjectModel.Target>,
settings: inout ProjectModel.BuildSettings
) {
// Do not add a dependency for binary-only executable products since they are not part of the build.
if product.isBinaryOnlyExecutableProduct {
return
}
if !pifBuilder.delegate.shouldSuppressProductDependency(product: product.underlying, buildSettings: &settings) {
let shouldLinkProduct = isLinkable
self.project[keyPath: targetKeyPath].common.addDependency(
on: product.pifTargetGUID,
platformFilters: packageConditions.toPlatformFilter(toolsVersion: package.manifest.toolsVersion),
linkProduct: shouldLinkProduct
)
log(
.debug,
indent: 1,
"Added \(shouldLinkProduct ? "linked " : "")dependency on product '\(product.pifTargetGUID)'"
)
}
}
// MARK: - Library Products
/// We treat library products specially, in that they are just collections of other targets.
mutating func makeLibraryProduct(
_ libraryProduct: PackageGraph.ResolvedProduct,
type libraryType: ProductType.LibraryType
) throws {
precondition(libraryProduct.type.isLibrary)
let library = try self.buildLibraryProduct(
libraryProduct,
type: libraryType,
embedResources: false
)
self.builtModulesAndProducts.append(library)
// Also create a dynamic product for use by development-time features such as Previews and Swift Playgrounds.
// If all targets this product is comprised of are binaries, we should *not* create a dynamic variant.
if libraryType == .automatic && libraryProduct.hasSourceTargets && pifBuilder.createDynamicVariantsForLibraryProducts {
var dynamicLibraryVariant = try self.buildLibraryProduct(
libraryProduct,
type: .dynamic,
targetSuffix: .dynamic,
embedResources: true
)
dynamicLibraryVariant.isDynamicLibraryVariant = true
self.builtModulesAndProducts.append(dynamicLibraryVariant)
guard let pifTarget = library.pifTarget,
let pifTargetKeyPath = self.project.findTarget(id: pifTarget.id),
let dynamicPifTarget = dynamicLibraryVariant.pifTarget
else {
fatalError("Could not assign dynamic PIF target")
}
self.project[keyPath: pifTargetKeyPath].dynamicTargetVariantId = dynamicPifTarget.id
}
}
/// Helper function to create a PIF target for a **library product**.
///
/// In order to support development-time features such as Preview and Swift Playgrounds,
/// all SwiftPM library products are represented by two PIF targets:
/// one of the "native" manifestation that gets linked into the client,
/// and another for a dynamic framework specifically for use by the development-time features.
private mutating func buildLibraryProduct(
_ product: PackageGraph.ResolvedProduct,
type desiredProductType: ProductType.LibraryType,
targetSuffix: TargetSuffix? = nil,
embedResources: Bool
) throws -> PackagePIFBuilder.ModuleOrProduct {
precondition(product.type.isLibrary)
// FIXME: Cleanup this mess with <rdar://56889224>
let productType: ProjectModel.Target.ProductType
var productName = "$(EXECUTABLE_NAME)"
if desiredProductType == .dynamic {
if pifBuilder.createDylibForDynamicProducts {
productType = .dynamicLibrary
} else {
productName = "$(WRAPPER_NAME)"
productType = .framework
}
} else if pifBuilder.delegate.isRootPackage && pifBuilder.materializeStaticArchiveProductsForRootPackages {
productType = .staticArchive
} else {
productType = .packageProduct
}
// Create a special kind of PIF target that just "groups" a set of targets for clients to depend on.
// Swift Build will *not* produce a separate artifact for a package product, but will instead consider any
// dependency on the package product to be a dependency on the whole set of targets
// on which the package product depends.
let libraryUmbrellaTargetKeyPath = try self.project.addTarget { _ in
ProjectModel.Target(
id: product.pifTargetGUID(suffix: targetSuffix),
productType: productType,
name: product.targetName(suffix: targetSuffix),
productName: productName
)
}
do {
let librayTarget = self.project[keyPath: libraryUmbrellaTargetKeyPath]
log(
.debug,
"Created target '\(librayTarget.id)' of type '\(librayTarget.productType)' with " +
"name '\(librayTarget.name)' and product name '\(librayTarget.productName)'"
)
}
// Add linked dependencies on the *targets* that comprise the product.
for module in product.modules {
// Binary targets are special in that they are just linked, not built.
if let binaryTarget = module.underlying as? BinaryModule {
let binaryFileRef = self.binaryGroup.addFileReference { id in
FileReference(id: id, path: binaryTarget.artifactPath.pathString)
}
self.project[keyPath: libraryUmbrellaTargetKeyPath].addLibrary { id in
BuildFile(id: id, fileRef: binaryFileRef, codeSignOnCopy: true, removeHeadersOnCopy: true)
}
log(.debug, indent: 1, "Added use of binary library '\(binaryTarget.artifactPath)'")
continue
}
// We add these as linked dependencies; because the product type is `.packageProduct`,
// SwiftBuild won't actually link them, but will instead impart linkage to any clients that
// link against the package product.
self.project[keyPath: libraryUmbrellaTargetKeyPath].common.addDependency(
on: module.pifTargetGUID,
platformFilters: [],
linkProduct: true
)
log(.debug, indent: 1, "Added linked dependency on target '\(module.pifTargetGUID)'")
}
for module in product.modules where module.underlying.isSourceModule && module.resources.hasContent {
// FIXME: Find a way to determine whether a module has generated resources
// here so that we can embed resources into dynamic targets.
self.project[keyPath: libraryUmbrellaTargetKeyPath].common.addDependency(
on: pifTargetIdForResourceBundle(module.name),
platformFilters: []
)
let packageName = self.package.name
let fileRef = self.project.mainGroup.addFileReference { id in
FileReference(id: id, path: "$(CONFIGURATION_BUILD_DIR)/\(packageName)_\(module.name).bundle")
}
if embedResources {
self.project[keyPath: libraryUmbrellaTargetKeyPath].addResourceFile { id in
BuildFile(id: id, fileRef: fileRef)
}
log(.debug, indent: 1, "Added use of resource bundle '\(fileRef.path)'")
} else {
log(
.debug,
indent: 1,
"Ignored resource bundle '\(fileRef.path)' because resource embedding is disabled"
)
}
}
var settings: ProjectModel.BuildSettings = package.underlying.packageBaseBuildSettings
// Add other build settings when we're building an actual dylib.
if desiredProductType == .dynamic {
settings.configureDynamicSettings(
product: product.underlying,
productName: product.name,
targetName: product.targetName(),
packageIdentity: package.identity,
packageName: package.identity.c99name,
createDylibForDynamicProducts: pifBuilder.createDylibForDynamicProducts,
installPath: installPath(for: product.underlying),
delegate: pifBuilder.delegate
)
// An empty sources phase is required in order to trigger linking.
self.project[keyPath: libraryUmbrellaTargetKeyPath].common.addSourcesBuildPhase { id in
ProjectModel.SourcesBuildPhase(id: id)
}
// For dynamic libraries, track which source modules are DIRECT dependencies so we can set
// SWIFT_COMPILE_FOR_STATIC_LINKING=NO on Windows for those modules.
// Collect only DIRECT module dependencies (not recursive)
for module in product.modules where module.isSourceModule {
self.modulesInDynamicLibraries.insert(module.name)
}
} else if productType == .staticArchive {
settings[.TARGET_NAME] = product.targetName()
settings[.TARGET_TEMP_DIR_SUFFIX] = "-p"
settings[.PRODUCT_NAME] = product.name
// This should really be swift-build defaults set in the .xcspec files, but changing that requires
// some extensive testing to ensure xcode projects are not affected.
// So for now lets just force it here.
settings[.EXECUTABLE_PREFIX] = "lib"
settings[.EXECUTABLE_PREFIX, ProjectModel.BuildSettings.Platform.windows] = ""
// An empty sources phase is required in order to trigger linking.
self.project[keyPath: libraryUmbrellaTargetKeyPath].common.addSourcesBuildPhase { id in
ProjectModel.SourcesBuildPhase(id: id)
}
}
// Additional configuration and files for this library product.
pifBuilder.delegate.configureLibraryProduct(
product: product.underlying,
project: &self.project,
target: libraryUmbrellaTargetKeyPath,
additionalFiles: additionalFilesGroupKeyPath
)
// If the given package is a root package or it is used via a branch/revision, we allow unsafe flags.
let implicitlyAllowAllUnsafeFlags = pifBuilder.delegate.isBranchOrRevisionBased ||
pifBuilder.delegate.isUserManaged
let recordUsesUnsafeFlags = try !implicitlyAllowAllUnsafeFlags && product.usesUnsafeFlags
settings[.USES_SWIFTPM_UNSAFE_FLAGS] = recordUsesUnsafeFlags ? "YES" : "NO"
// Handle the dependencies of the targets in the product
// (and link against them, which in the case of a package product, really just means that clients should link
// against them).
product.modules.recursivelyTraverseDependencies { dependency in
switch dependency {
case .module(let moduleDependency, let packageConditions):
// This assertion is temporarily disabled since we may see targets from
// _other_ packages, but this should be resolved; see rdar://95467710.
/* assert(moduleDependency.packageName == self.package.name) */
if moduleDependency.type == .systemModule {
log(.debug, indent: 1, "Noted use of system module '\(moduleDependency.name)'")
return
}
if let binaryTarget = moduleDependency.underlying as? BinaryModule {
let binaryFileRef = self.binaryGroup.addFileReference { id in
FileReference(id: id, path: binaryTarget.artifactPath.pathString)
}
let toolsVersion = package.manifest.toolsVersion
self.project[keyPath: libraryUmbrellaTargetKeyPath].addLibrary { id in
BuildFile(
id: id,
fileRef: binaryFileRef,
platformFilters: packageConditions.toPlatformFilter(toolsVersion: toolsVersion),
codeSignOnCopy: true,
removeHeadersOnCopy: true
)
}
log(.debug, indent: 1, "Added use of binary library '\(binaryTarget.path)'")
return
}
if moduleDependency.type == .plugin {
let dependencyId = moduleDependency.pifTargetGUID
self.project[keyPath: libraryUmbrellaTargetKeyPath].common.addDependency(
on: dependencyId,
platformFilters: packageConditions
.toPlatformFilter(toolsVersion: package.manifest.toolsVersion),
linkProduct: false
)
log(.debug, indent: 1, "Added use of plugin target '\(dependencyId)'")
return
}
// If this dependency is already present in the product's module target then don't re-add it.
if product.modules.contains(where: { $0.name == moduleDependency.name }) { return }
// For executable targets, add a build time dependency on the product.
// FIXME: Maybe we should we do this at the libSwiftPM level.
if moduleDependency.isExecutable {
let mainModuleProducts = package.products.filter(\.isMainModuleProduct)
if let product = moduleDependency
.productRepresentingDependencyOfBuildPlugin(in: mainModuleProducts)
{
self.project[keyPath: libraryUmbrellaTargetKeyPath].common.addDependency(
on: product.pifTargetGUID,
platformFilters: packageConditions
.toPlatformFilter(toolsVersion: package.manifest.toolsVersion),
linkProduct: false
)
log(.debug, indent: 1, "Added dependency on product '\(product.pifTargetGUID)'")
return
} else {
log(
.debug,
indent: 1,
"Could not find a build plugin product to depend on for target '\(product.pifTargetGUID)'"
)
}
}
self.project[keyPath: libraryUmbrellaTargetKeyPath].common.addDependency(
on: moduleDependency.pifTargetGUID,
platformFilters: packageConditions.toPlatformFilter(toolsVersion: package.manifest.toolsVersion),
linkProduct: true
)
log(.debug, indent: 1, "Added linked dependency on target '\(moduleDependency.pifTargetGUID)'")
case .product(let productDependency, let packageConditions):
// Do not add a dependency for binary-only executable products since they are not part of the build.
if productDependency.isBinaryOnlyExecutableProduct {
return
}
if !pifBuilder.delegate.shouldSuppressProductDependency(
product: productDependency.underlying,
buildSettings: &settings
) {
let shouldLinkProduct = productDependency.isLinkable
self.project[keyPath: libraryUmbrellaTargetKeyPath].common.addDependency(
on: productDependency.pifTargetGUID,
platformFilters: packageConditions
.toPlatformFilter(toolsVersion: package.manifest.toolsVersion),
linkProduct: shouldLinkProduct
)
log(
.debug,
indent: 1,
"Added \(shouldLinkProduct ? "linked" : "") dependency on product '\(productDependency.pifTargetGUID)'"
)
}
}
}
// For *registry* packages, vend any registry release metadata to the build system.
if let metadata = package.registryMetadata,
let signature = metadata.signature,
let version = pifBuilder.packageDisplayVersion,
case RegistryReleaseMetadata.Source.registry(let url) = metadata.source
{
let signatureData = PackageRegistrySignature(
packageIdentity: package.identity.description,
packageVersion: version,
signature: signature,
libraryName: product.name,
source: .registry(url: url)
)
let encoder = PropertyListEncoder()
encoder.outputFormat = .xml
let data = try encoder.encode(signatureData)
settings[.PACKAGE_REGISTRY_SIGNATURE] = String(data: data, encoding: .utf8)
}
self.project[keyPath: libraryUmbrellaTargetKeyPath].common.addBuildConfig { id in
BuildConfig(id: id, name: "Debug", settings: settings)
}
self.project[keyPath: libraryUmbrellaTargetKeyPath].common.addBuildConfig { id in
BuildConfig(id: id, name: "Release", settings: settings)
}
// Collect linked binaries.
let linkedPackageBinaries = product.modules.compactMap {
PackagePIFBuilder.LinkedPackageBinary(module: $0)
}
let moduleOrProductType: PackagePIFBuilder.ModuleOrProductType = switch product.libraryType {
case .dynamic:
pifBuilder.createDylibForDynamicProducts ? .dynamicLibrary : .framework
default:
.staticArchive
}
return PackagePIFBuilder.ModuleOrProduct(
type: moduleOrProductType,
name: product.name,
moduleName: product.c99name,
pifTarget: .target(self.project[keyPath: libraryUmbrellaTargetKeyPath]),
indexableFileURLs: [],
headerFiles: [],
linkedPackageBinaries: linkedPackageBinaries,
swiftLanguageVersion: nil,
declaredPlatforms: self.declaredPlatforms,
deploymentTargets: self.deploymentTargets,
toolsVersion: pifBuilder.packageManifest.toolsVersion
)
}
// MARK: - System Library Products
mutating func makeSystemLibraryProduct(_ product: PackageGraph.ResolvedProduct) throws {
precondition(product.type == .library(.automatic))
let systemLibraryTargetKeyPath = try self.project.addTarget { _ in
ProjectModel.Target(
id: product.pifTargetGUID,
productType: .packageProduct,
name: product.targetName(),
productName: product.name
)
}
do {
let systemLibraryTarget = self.project[keyPath: systemLibraryTargetKeyPath]
log(
.debug,
"Created target '\(systemLibraryTarget.id)' of type '\(systemLibraryTarget.productType)' " +
"with name '\(systemLibraryTarget.name)' and product name '\(systemLibraryTarget.productName)'"
)
}
let buildSettings = self.package.underlying.packageBaseBuildSettings
self.project[keyPath: systemLibraryTargetKeyPath].common.addBuildConfig { id in
BuildConfig(id: id, name: "Debug", settings: buildSettings)
}
self.project[keyPath: systemLibraryTargetKeyPath].common.addBuildConfig { id in
BuildConfig(id: id, name: "Release", settings: buildSettings)
}
self.project[keyPath: systemLibraryTargetKeyPath].common.addDependency(
on: product.systemModule!.pifTargetGUID,
platformFilters: [],
linkProduct: false
)
let systemLibrary = PackagePIFBuilder.ModuleOrProduct(
type: .staticArchive,
name: product.name,
moduleName: product.c99name,
pifTarget: .target(self.project[keyPath: systemLibraryTargetKeyPath]),
indexableFileURLs: [],
headerFiles: [],
linkedPackageBinaries: [],
swiftLanguageVersion: nil,
declaredPlatforms: self.declaredPlatforms,
deploymentTargets: self.deploymentTargets,