-
Notifications
You must be signed in to change notification settings - Fork 187
Expand file tree
/
Copy pathTaskProducer.swift
More file actions
1776 lines (1493 loc) · 94.9 KB
/
Copy pathTaskProducer.swift
File metadata and controls
1776 lines (1493 loc) · 94.9 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
//
//===----------------------------------------------------------------------===//
public import SWBUtil
public import SWBCore
import struct SWBProtocol.BuildOperationTaskEnded
public import Foundation
public import SWBMacro
import Synchronization
/// A `TaskProducer` has two distinct phases that are used to create the necessary planning work.
enum TaskProducerPhase {
/// Used to denote that the task producer is not currently under any particular phase.
case none
/// The planning phase allows all task producers to add information to their `TaskProducerContext` via the `prepare()` method. This allows information to be shared from one task producer to another without needing to create any direct dependency ordering. The only guarantee for ordering is that `generateTasks()` will not be called before all of the task producers have finished with their `planning` phase.
case planning
/// The task generation phase allows all of the task producers to create their respective tasks.
case taskGeneration
}
/// A TaskProducer embodies a set of work which needs to be done create the tasks which, when run, will generate all or part of the product of a ProductPlan.
package protocol TaskProducer
{
/// Immutable data available to the task producer.
var context: TaskProducerContext { get }
/// Additional paths which invalidate the build description
var invalidationPaths: [Path] { get }
/// Generates the tasks to run.
func generateTasks() async -> [any PlannedTask]
/// Allows for tasks to pre-plan any work that needs to be done, primarily for exposure to other task producers.
func prepare() async
}
extension TaskProducer
{
/// By default, most task producers should not need to make use of this functionality.
package func prepare() async {}
}
/// Context of immutable data available to a task producer.
public class TaskProducerContext: StaleFileRemovalContext, BuildFileResolution
{
/// The workspace context.
public let workspaceContext: WorkspaceContext
/// The configured target the task producer is creating tasks for.
public let configuredTarget: ConfiguredTarget?
/// The current phase the task producer is in.
var phase: TaskProducerPhase = .none
/// The project this context is for.
public let project: Project?
/// The high-level global build information.
package let globalProductPlan: GlobalProductPlan
var dynamicallyBuildingTargets: Set<Target> {
return globalProductPlan.dynamicallyBuildingTargets
}
public var globalTargetInfoProvider: any GlobalTargetInfoProvider {
return globalProductPlan
}
/// The delegate to use for creating tasks.
///
/// This is private because clients should only interact with it via the exposed forwarding methods. This ensures that constraints on task construction (e.g., attachment to the target or phase ordering nodes) are followed.
fileprivate let delegate: any TaskPlanningDelegate
/// Tasks that mark that the 'prepare-for-index' module content output of a target is ready.
/// This is only getting populated for an index build.
var preparedForIndexModuleContentTasks: [any PlannedTask] = []
// File type specs corresponding to compilation requirements
let compilationRequirementOutputFileTypes: [FileTypeSpec]
/// The build settings the task producer should use.
public let settings: Settings
/// The build rule set for file references (includes system rules as well as any custom rules).
package let buildRuleSet: any BuildRuleSet
/// The default working directory path to use.
///
/// This is the directory containing the .xcodeproj of the project for the configured target.
public var defaultWorkingDirectory: Path
// On-Demand Resources
let onDemandResourcesEnabled: Bool
let onDemandResourcesInitialInstallTags: Set<String>
let onDemandResourcesPrefetchOrder: [String]
/// The registry used for spec data caches.
public let specDataCaches = Registry<Spec, any SpecDataCache>()
/// Whether a task planned by this producer has requested frontend command line emission.
var emitFrontendCommandLines: Bool
/// Registers a path accessed during task construction.
func access(path: Path) {
state.withLock { $0.accessedPaths.insert(path) }
}
/// Paths accessed during task construction that invalidate the build description.
/// On the context so ephemeral producers are included.
var accessedPaths: Set<Path> {
state.withLock { $0.accessedPaths }
}
private struct State: Sendable {
fileprivate var accessedPaths = Set<Path>()
fileprivate var onDemandResourcesAssetPacks: [ODRTagSet: ODRAssetPackInfo] = [:]
fileprivate var onDemandResourcesAssetPackSubPaths: [String: Set<String>] = [:]
/// The list of generated source files produced in this target.
fileprivate var _generatedSourceFiles: [Path] = []
/// The list of generated info plist additions produced in this target.
fileprivate var _generatedInfoPlistContents: [Path] = []
fileprivate var _generatedPrivacyContentFilePaths: Set<Path> = []
/// The list of generated TBD files produced in this target.
///
/// This is currently only ever done by Swift.
fileprivate var _generatedTBDFiles: [String: [Path]] = [:]
/// The map of architecture names to generated Swift Objective-C interface header files produced in this target.
///
/// This is currently only ever done by Swift.
fileprivate var _generatedSwiftObjectiveCHeaderFiles: [String: Path] = [:]
/// The map of architecture names to generated Swift compile-time value metadata files produced in this target.
/// Only ever done by Swift.
fileprivate var _generatedGeneratedSwiftConstMetadataFiles: [String: [Path]] = [:]
/// Virtual output nodes for shell script build phases that don't have any declared outputs.
fileprivate var _shellScriptVirtualOutputs: [PlannedVirtualNode] = []
/// The outputs of the tasks for this target prior to deferred task production.
fileprivate var _outputsOfMainTaskProducers: [any PlannedNode] = []
/// The map of top-level binaries path, keyed by variant.
fileprivate var _producedBinaryPaths: [String: Path] = [:]
/// The map of dSYM paths, keyed by variant.
fileprivate var _producedDSYMPaths: [String: Path] = [:]
/// The list of deferred task production blocks.
fileprivate var _deferredProducers: [() async -> [any PlannedTask]] = []
/// Whether we have transitioned to processing deferred tasks.
fileprivate var _inDeferredMode = false
/// Map of the files which are copied during the build, used for mapping diagnostics.
fileprivate var _copiedPathMap: [String: Set<String>] = [:]
/// The set of additional inputs for codesigning. These are tracked explicitly on the codesign task and are captured during the `.planning` phase.
fileprivate var _additionalCodeSignInputs: OrderedSet<Path> = []
/// Notes generated by the internal state of the task producer context. These are harvested by the `BuildPlan` once all task producers have been run.
///
/// This is an `OrderedSet` because the context is shared among all task producers for a target, and multiple producers could cause the same note to be emitted
fileprivate(set) var notes = OrderedSet<String>()
/// Warnings generated by the internal state of the task producer context. These are harvested by the `BuildPlan` once all task producers have been run.
///
/// This is an `OrderedSet` because the context is shared among all task producers for a target, and multiple producers could cause the same warning to be emitted
fileprivate(set) var warnings = OrderedSet<String>()
/// Errors generated by the internal state of the task producer context. These are harvested by the `BuildPlan` once all task producers have been run.
///
/// This is an `OrderedSet` because the context is shared among all task producers for a target, and multiple producers could cause the same error to be emitted .
fileprivate(set) var errors = OrderedSet<String>()
}
/// Notes generated by the internal state of the task producer context. These are harvested by the `BuildPlan` once all task producers have been run.
///
/// This is an `OrderedSet` because the context is shared among all task producers for a target, and multiple producers could cause the same note to be emitted
var notes: OrderedSet<String> {
state.withLock { $0.notes }
}
/// Warnings generated by the internal state of the task producer context. These are harvested by the `BuildPlan` once all task producers have been run.
///
/// This is an `OrderedSet` because the context is shared among all task producers for a target, and multiple producers could cause the same warning to be emitted
var warnings: OrderedSet<String> {
state.withLock { $0.warnings }
}
/// Errors generated by the internal state of the task producer context. These are harvested by the `BuildPlan` once all task producers have been run.
///
/// This is an `OrderedSet` because the context is shared among all task producers for a target, and multiple producers could cause the same error to be emitted .
var errors: OrderedSet<String> {
state.withLock { $0.errors }
}
private let state = SWBMutex<State>(.init())
// MARK: Bound Tool Specs.
/// For a spec property which is represented by a `Result`, either return the concrete spec if it was found, or else log an error that an attempt to access a missing spec occurred and return nil.
func specForResult<T: CommandLineToolSpec>(_ result: Result<T, any Error>) -> T? {
switch result {
case .success(let toolSpec):
return toolSpec
case .failure(let error):
return state.withLock { state in
state.errors.append("\(error)")
return nil
}
}
}
public let appShortcutStringsMetadataCompilerSpec: AppShortcutStringsMetadataCompilerSpec?
let appleScriptCompilerSpec: CommandLineToolSpec?
public let clangSpec: ClangCompilerSpec
public let clangAssemblerSpec: ClangCompilerSpec
public let clangPreprocessorSpec: ClangCompilerSpec
public let clangStaticAnalyzerSpec: ClangCompilerSpec
public let entityLinkerToolSpec: CommandLineToolSpec
public let ssafAnalyzerToolSpec: CommandLineToolSpec
public let clangModuleVerifierSpec: ClangCompilerSpec
private let _clangStatCacheSpec: Result<ClangStatCacheSpec, any Error>
var clangStatCacheSpec: ClangStatCacheSpec? { return specForResult(_clangStatCacheSpec) }
public let codesignSpec: CodesignToolSpec
private let _concatenateSpec: Result<ConcatenateToolSpec, any Error>
var concatenateSpec: ConcatenateToolSpec? { return specForResult(_concatenateSpec) }
public let copySpec: CopyToolSpec
let copyPlistSpec: CommandLineToolSpec
public let copyPngSpec: CommandLineToolSpec?
public let copyTiffSpec: CommandLineToolSpec?
let cppSpec: CommandLineToolSpec
let createAssetPackManifestSpec: CreateAssetPackManifestToolSpec
public let createBuildDirectorySpec: CreateBuildDirectorySpec
public let diffSpec: CommandLineToolSpec
let dsymutilSpec: DsymutilToolSpec
let infoPlistSpec: InfoPlistToolSpec
let mergeInfoPlistSpec: MergeInfoPlistSpec
let launchServicesRegisterSpec: CommandLineToolSpec?
public let ldLinkerSpec: LdLinkerSpec
public let libtoolLinkerSpec: LibtoolLinkerSpec
public let lipoSpec: LipoToolSpec
let prelinkedObjectLinkSpec: CommandLineToolSpec
public let mkdirSpec: MkdirToolSpec
let modulesVerifierSpec: ModulesVerifierToolSpec
let clangModuleVerifierInputGeneratorSpec: ClangModuleVerifierInputGeneratorSpec
let productPackagingSpec: ProductPackagingToolSpec
let setAttributesSpec: SetAttributesSpec
let shellScriptSpec: ShellScriptToolSpec
let signatureCollectionSpec: SignatureCollectionSpec
public let stripSpec: StripToolSpec
public let swiftCompilerSpec: SwiftCompilerSpec
let swiftHeaderToolSpec: SwiftHeaderToolSpec
let swiftStdlibToolSpec: SwiftStdLibToolSpec
private let _swiftABICheckerToolSpec: Result<SwiftABICheckerToolSpec, any Error>
var swiftABICheckerToolSpec: SwiftABICheckerToolSpec? { return specForResult(_swiftABICheckerToolSpec) }
private let _swiftABIGenerationToolSpec: Result<SwiftABIGenerationToolSpec, any Error>
var swiftABIGenerationToolSpec: SwiftABIGenerationToolSpec? { return specForResult(_swiftABIGenerationToolSpec) }
let symlinkSpec: SymlinkToolSpec
let tapiSpec: TAPIToolSpec
let tapiMergeSpec: CommandLineToolSpec
let tapiStubifySpec: CommandLineToolSpec
let touchSpec: CommandLineToolSpec
public let unifdefSpec: UnifdefToolSpec
let validateEmbeddedBinarySpec: ValidateEmbeddedBinaryToolSpec?
let validateProductSpec: ValidateProductToolSpec?
let processXCFrameworkLibrarySpec: ProcessXCFrameworkLibrarySpec
public let processSDKImportsSpec: ProcessSDKImportsSpec
public let writeFileSpec: WriteFileSpec
private let _generateEmbedInCodeAccessorSpec: Result<GenerateEmbedInCodeAccessorSpec, any Error>
public var generateEmbedInCodeAccessorSpec: GenerateEmbedInCodeAccessorSpec? { return specForResult(_generateEmbedInCodeAccessorSpec) }
private let _documentationCompilerSpec: Result<CommandLineToolSpec, any Error>
var documentationCompilerSpec: CommandLineToolSpec? { return specForResult(_documentationCompilerSpec) }
private let _tapiSymbolExtractorSpec: Result<TAPISymbolExtractor, any Error>
var tapiSymbolExtractor: TAPISymbolExtractor? { return specForResult(_tapiSymbolExtractorSpec) }
private let _swiftSymbolExtractorSpec: Result<CommandLineToolSpec, any Error>
var swiftSymbolExtractor: CommandLineToolSpec? { return specForResult(_swiftSymbolExtractorSpec) }
private let _developmentAssetsSpec: Result<CommandLineToolSpec, any Error>
public var developmentAssetsSpec: CommandLineToolSpec? { return specForResult(_developmentAssetsSpec) }
private let _generateAppPlaygroundAssetCatalogSpec: Result<CommandLineToolSpec, any Error>
var generateAppPlaygroundAssetCatalogSpec: CommandLineToolSpec? { return specForResult(_generateAppPlaygroundAssetCatalogSpec) }
private let _realityAssetsCompilerSpec: Result<CommandLineToolSpec, any Error>
public var realityAssetsCompilerSpec: CommandLineToolSpec? { return specForResult(_realityAssetsCompilerSpec) }
/// Create the context for producing tasks independent of any particular target.
///
/// - parameter workspaceContext: The containing workspace and context.
/// - parameter globalProductPlan: The high-level global build information.
/// - parameter delegate: The delegate to use for task construction.
init(configuredTarget: ConfiguredTarget? = nil, workspaceContext: WorkspaceContext, globalProductPlan: GlobalProductPlan, delegate: any TaskPlanningDelegate)
{
self.workspaceContext = workspaceContext
self.configuredTarget = configuredTarget
self.globalProductPlan = globalProductPlan
let settings = configuredTarget.map(globalProductPlan.getTargetSettings) ?? globalProductPlan.getWorkspaceSettings()
self.settings = settings
self.delegate = delegate
// Construct a build ruleset from the built-in system rules (which may be different for different platforms), and for any custom rules from the target.
//
// FIXME: We could cache these.
let projectBuildRules: [(any BuildRuleCondition, any BuildRuleAction)]
if let configuredTarget, let asStandardTarget = configuredTarget.target as? StandardTarget {
let settings = self.settings
projectBuildRules = asStandardTarget.buildRules.compactMap { rule in
do {
// Create and return a build rule condition/action pair for the build rule item. If a platform is given, any specifications mentioned in the build rule (such as file types or command line specs) will be bound from the point of view of that platform.
switch rule.actionSpecifier {
case let .compiler(compilerSpecificationIdentifier):
return try workspaceContext.core.createSpecBasedBuildRule(rule.inputSpecifier, compilerSpecificationIdentifier, platform: settings.platform)
case let .shellScript(contents, inputs, inputFileLists, outputs, outputFileLists, dependencyInfo, runOncePerArchitecture):
return try workspaceContext.core.createShellScriptBuildRule(rule.guid, rule.name, rule.inputSpecifier, contents, inputs, inputFileLists, outputs.map { ($0.path, $0.additionalCompilerFlags) }, outputFileLists, dependencyInfo, runOncePerArchitecture, platform: settings.platform, scope: settings.globalScope)
}
} catch {
// FIXME: This probably should be an error, since the only case where the above calls can fail is if a spec is of the wrong type (code error) or fails to load (code error or potentially an Xcode installation issue). However, since projects could theoretically be relying on this behavior, we'll avoid changing it for now.
delegate.warning(.overrideTarget(configuredTarget), "\(error)")
return nil
}
}
} else {
projectBuildRules = []
}
self.buildRuleSet = LeveledBuildRuleSet(ruleSets: [
BasicBuildRuleSet(rules: projectBuildRules),
DisambiguatingBuildRuleSet(rules: settings.systemBuildRules, enableDebugActivityLogs: workspaceContext.userPreferences.enableDebugActivityLogs)
])
self.project = configuredTarget.map { workspaceContext.workspace.project(for: $0.target) }
self.defaultWorkingDirectory = settings.project?.sourceRoot ?? workspaceContext.workspace.path.dirname
// On-Demand Resources
self.onDemandResourcesEnabled = settings.globalScope.evaluate(BuiltinMacros.ENABLE_ON_DEMAND_RESOURCES)
self.onDemandResourcesInitialInstallTags = Set(settings.globalScope.evaluate(BuiltinMacros.ON_DEMAND_RESOURCES_INITIAL_INSTALL_TAGS))
self.onDemandResourcesPrefetchOrder = settings.globalScope.evaluate(BuiltinMacros.ON_DEMAND_RESOURCES_PREFETCH_ORDER)
// Bind known tool specs.
//
// FIXME: These should really be bound even earlier, like in the spec cache. Or at least, we should throw here and just produce a dep graph error if any are missing.
let domain = settings.platform?.name ?? ""
self.appShortcutStringsMetadataCompilerSpec = workspaceContext.core.specRegistry.getSpec("com.apple.compilers.appshortcutstringsmetadata", domain: domain) as? AppShortcutStringsMetadataCompilerSpec
self.appleScriptCompilerSpec = workspaceContext.core.specRegistry.getSpec("com.apple.compilers.osacompile", domain: domain) as? CommandLineToolSpec
self.clangSpec = try! workspaceContext.core.specRegistry.getSpec(domain: domain, ofType: ClangCompilerSpec.self)
self.clangAssemblerSpec = try! workspaceContext.core.specRegistry.getSpec(domain: domain, ofType: ClangAssemblerSpec.self)
self.clangPreprocessorSpec = try! workspaceContext.core.specRegistry.getSpec(domain: domain, ofType: ClangPreprocessorSpec.self)
self.clangStaticAnalyzerSpec = try! workspaceContext.core.specRegistry.getSpec(domain: domain, ofType: ClangStaticAnalyzerSpec.self)
self.entityLinkerToolSpec = try! workspaceContext.core.specRegistry.getSpec("com.apple.build-tools.clang-ssaf-linker", domain: domain, ofType: CommandLineToolSpec.self)
self.ssafAnalyzerToolSpec = try! workspaceContext.core.specRegistry.getSpec("com.apple.build-tools.clang-ssaf-analyzer", domain: domain, ofType: CommandLineToolSpec.self)
self.clangModuleVerifierSpec = try! workspaceContext.core.specRegistry.getSpec(domain: domain, ofType: ClangModuleVerifierSpec.self)
self._clangStatCacheSpec = Result { try workspaceContext.core.specRegistry.getSpec("com.apple.compilers.clang-stat-cache", ofType: ClangStatCacheSpec.self) }
self.codesignSpec = try! workspaceContext.core.specRegistry.getSpec("com.apple.build-tools.codesign", domain: domain, ofType: CodesignToolSpec.self)
self._concatenateSpec = Result { try workspaceContext.core.specRegistry.getSpec("com.apple.build-tools.concatenate", ofType: ConcatenateToolSpec.self) }
self.copySpec = try! workspaceContext.core.specRegistry.getSpec(domain: domain, ofType: CopyToolSpec.self)
self.copyPlistSpec = try! workspaceContext.core.specRegistry.getSpec("com.apple.build-tasks.copy-plist-file", domain: domain, ofType: CommandLineToolSpec.self)
self.copyPngSpec = try? workspaceContext.core.specRegistry.getSpec("com.apple.build-tasks.copy-png-file", domain: domain, ofType: CommandLineToolSpec.self)
self.copyTiffSpec = try? workspaceContext.core.specRegistry.getSpec("com.apple.build-tasks.copy-tiff-file", domain: domain, ofType: CommandLineToolSpec.self)
self.cppSpec = try! workspaceContext.core.specRegistry.getSpec("com.apple.compilers.cpp", domain: domain, ofType: CommandLineToolSpec.self)
self.createAssetPackManifestSpec = try! workspaceContext.core.specRegistry.getSpec(CreateAssetPackManifestToolSpec.identifier, domain: domain, ofType: CreateAssetPackManifestToolSpec.self)
self.createBuildDirectorySpec = try! workspaceContext.core.specRegistry.getSpec("com.apple.tools.create-build-directory", domain: domain, ofType: CreateBuildDirectorySpec.self)
self.diffSpec = try! workspaceContext.core.specRegistry.getSpec("com.apple.build-tools.diff", domain: domain, ofType: CommandLineToolSpec.self)
self.dsymutilSpec = try! workspaceContext.core.specRegistry.getSpec("com.apple.tools.dsymutil", domain: domain, ofType: DsymutilToolSpec.self)
self.infoPlistSpec = try! workspaceContext.core.specRegistry.getSpec("com.apple.tools.info-plist-utility", domain: domain, ofType: InfoPlistToolSpec.self)
self.mergeInfoPlistSpec = try! workspaceContext.core.specRegistry.getSpec(MergeInfoPlistSpec.identifier, domain: domain, ofType: MergeInfoPlistSpec.self)
self.launchServicesRegisterSpec = try? workspaceContext.core.specRegistry.getSpec("com.apple.build-tasks.ls-register-url", domain: domain, ofType: CommandLineToolSpec.self)
self.ldLinkerSpec = try! workspaceContext.core.specRegistry.getSpec(domain: domain, ofType: LdLinkerSpec.self)
self.libtoolLinkerSpec = try! workspaceContext.core.specRegistry.getSpec(domain: domain, ofType: LibtoolLinkerSpec.self)
self.lipoSpec = try! workspaceContext.core.specRegistry.getSpec("com.apple.xcode.linkers.lipo", domain: domain, ofType: LipoToolSpec.self)
self.prelinkedObjectLinkSpec = try! workspaceContext.core.specRegistry.getSpec(PrelinkedObjectLinkSpec.identifier, domain: domain, ofType: CommandLineToolSpec.self)
self.mkdirSpec = try! workspaceContext.core.specRegistry.getSpec("com.apple.tools.mkdir", domain: domain, ofType: MkdirToolSpec.self)
self.modulesVerifierSpec = try! workspaceContext.core.specRegistry.getSpec("com.apple.build-tools.modules-verifier", domain: domain, ofType: ModulesVerifierToolSpec.self)
self.clangModuleVerifierInputGeneratorSpec = try! workspaceContext.core.specRegistry.getSpec("com.apple.build-tools.module-verifier-input-generator", domain: domain, ofType: ClangModuleVerifierInputGeneratorSpec.self)
self.productPackagingSpec = try! workspaceContext.core.specRegistry.getSpec(domain: domain, ofType: ProductPackagingToolSpec.self)
self.setAttributesSpec = try! workspaceContext.core.specRegistry.getSpec("com.apple.build-tools.set-attributes", domain: domain, ofType: SetAttributesSpec.self)
self.shellScriptSpec = try! workspaceContext.core.specRegistry.getSpec("com.apple.commands.shell-script", domain: domain, ofType: ShellScriptToolSpec.self)
self.signatureCollectionSpec = try! workspaceContext.core.specRegistry.getSpec("com.apple.build-tools.signature-collection", domain: domain, ofType: SignatureCollectionSpec.self)
self.stripSpec = workspaceContext.core.specRegistry.getSpec("com.apple.build-tools.strip", domain: domain) as! StripToolSpec
self.swiftCompilerSpec = try! workspaceContext.core.specRegistry.getSpec(domain: domain, ofType: SwiftCompilerSpec.self)
self.swiftHeaderToolSpec = try! workspaceContext.core.specRegistry.getSpec(SwiftHeaderToolSpec.identifier, domain: domain, ofType: SwiftHeaderToolSpec.self)
self.swiftStdlibToolSpec = try! workspaceContext.core.specRegistry.getSpec("com.apple.build-tools.swift-stdlib-tool", domain: domain, ofType: SwiftStdLibToolSpec.self)
self._swiftABICheckerToolSpec = Result { try workspaceContext.core.specRegistry.getSpec("com.apple.build-tools.swift-abi-checker", domain: domain, ofType: SwiftABICheckerToolSpec.self) }
self._swiftABIGenerationToolSpec = Result { try workspaceContext.core.specRegistry.getSpec("com.apple.build-tools.swift-abi-generation", domain: domain, ofType: SwiftABIGenerationToolSpec.self) }
self.symlinkSpec = try! workspaceContext.core.specRegistry.getSpec("com.apple.tools.symlink", domain: domain, ofType: SymlinkToolSpec.self)
self.tapiSpec = try! workspaceContext.core.specRegistry.getSpec("com.apple.build-tools.tapi.installapi", domain: domain, ofType: TAPIToolSpec.self)
self.tapiMergeSpec = try! workspaceContext.core.specRegistry.getSpec("com.apple.build-tools.tapi.merge", domain: domain, ofType: CommandLineToolSpec.self)
self.tapiStubifySpec = try! workspaceContext.core.specRegistry.getSpec("com.apple.build-tools.tapi.stubify", domain: domain, ofType: CommandLineToolSpec.self)
self.touchSpec = try! workspaceContext.core.specRegistry.getSpec("com.apple.tools.touch", domain: domain, ofType: CommandLineToolSpec.self)
self.unifdefSpec = try! workspaceContext.core.specRegistry.getSpec("public.build-task.unifdef", domain: domain, ofType: UnifdefToolSpec.self)
self.validateEmbeddedBinarySpec = try? workspaceContext.core.specRegistry.getSpec("com.apple.tools.validate-embedded-binary-utility", domain: domain, ofType: ValidateEmbeddedBinaryToolSpec.self)
self.validateProductSpec = try? workspaceContext.core.specRegistry.getSpec("com.apple.build-tools.platform.validate", domain: domain, ofType: ValidateProductToolSpec.self)
self.processXCFrameworkLibrarySpec = try! workspaceContext.core.specRegistry.getSpec(ProcessXCFrameworkLibrarySpec.identifier, domain: domain, ofType: ProcessXCFrameworkLibrarySpec.self)
self.processSDKImportsSpec = try! workspaceContext.core.specRegistry.getSpec(ProcessSDKImportsSpec.identifier, domain: domain, ofType: ProcessSDKImportsSpec.self)
self.writeFileSpec = try! workspaceContext.core.specRegistry.getSpec("com.apple.build-tools.write-file", domain: domain, ofType: WriteFileSpec.self)
self._generateEmbedInCodeAccessorSpec = Result { try workspaceContext.core.specRegistry.getSpec(GenerateEmbedInCodeAccessorSpec.identifier, domain: domain, ofType: GenerateEmbedInCodeAccessorSpec.self) }
self._documentationCompilerSpec = Result { try workspaceContext.core.specRegistry.getSpec("com.apple.compilers.documentation", domain: domain, ofType: CommandLineToolSpec.self) }
self._tapiSymbolExtractorSpec = Result { try workspaceContext.core.specRegistry.getSpec("com.apple.compilers.documentation.objc-symbol-extract", domain: domain, ofType: TAPISymbolExtractor.self) }
self._swiftSymbolExtractorSpec = Result { try workspaceContext.core.specRegistry.getSpec("com.apple.compilers.documentation.swift-symbol-extract", domain: domain, ofType: CommandLineToolSpec.self) }
self._developmentAssetsSpec = Result { try workspaceContext.core.specRegistry.getSpec(ValidateDevelopmentAssets.identifier, domain: domain, ofType: CommandLineToolSpec.self) }
self._generateAppPlaygroundAssetCatalogSpec = Result { try workspaceContext.core.specRegistry.getSpec(GenerateAppPlaygroundAssetCatalog.identifier, domain: domain, ofType: CommandLineToolSpec.self) }
self._realityAssetsCompilerSpec = Result { try workspaceContext.core.specRegistry.getSpec("com.apple.build-tasks.compile-rk-assets.xcplugin", domain: domain, ofType: CommandLineToolSpec.self) }
self.compilationRequirementOutputFileTypes = (SpecRegistry.headerFileTypeIdentifiers + [SpecRegistry.modulemapFileTypeIdentifier]).compactMap { workspaceContext.core.specRegistry.lookupFileType(identifier: $0, domain: domain) }
self.emitFrontendCommandLines = settings.globalScope.evaluate(BuiltinMacros.EMIT_FRONTEND_COMMAND_LINES)
for diagnostic in settings.diagnostics {
delegate.emit(diagnostic)
}
for diagnostic in settings.targetDiagnostics {
delegate.emit(configuredTarget.map { .overrideTarget($0) } ?? .default, diagnostic)
}
let context = configuredTarget.map { TargetDiagnosticContext.overrideTarget($0) } ?? .default
// Report any issues detected while we were being constructed.
for error in settings.errors {
delegate.error(context, error)
}
for warning in settings.warnings {
delegate.warning(context, warning)
}
for note in settings.notes {
delegate.note(context, note)
}
}
/// The set of all known deployment target macro names, even if the platforms that use those settings are not installed.
func allDeploymentTargetMacroNames() async -> Set<String> {
await (clangSpec.discoveredCommandLineToolSpecInfo(self, settings.globalScope, delegate) as? DiscoveredClangToolSpecInfo)?.deploymentTargetEnvironmentVariableNames() ?? []
}
/// Make an input path absolute, resolving relative to the current project.
func makeAbsolute(_ path: Path) -> Path {
return defaultWorkingDirectory.join(path)
}
public func lookupReference(for guid: String) -> Reference? {
return workspaceContext.workspace.lookupReference(for: guid)
}
/// Get the list of source files generated for this target.
var generatedSourceFiles: [Path] {
return state.withLock { state in
assert(state._inDeferredMode)
return state._generatedSourceFiles
}
}
/// Add a source file generated by this target.
func addGeneratedSourceFile(_ path: Path) {
state.withLock { state in
assert(!state._inDeferredMode)
state._generatedSourceFiles.append(path)
}
}
/// Get the list of info plist additions generated for this target.
var generatedInfoPlistContents: [Path] {
return state.withLock { state in
assert(state._inDeferredMode)
return state._generatedInfoPlistContents
}
}
var generatedPrivacyContentFilePaths: Set<Path> {
return state.withLock { state in
assert(state._inDeferredMode)
return state._generatedPrivacyContentFilePaths
}
}
/// Add an info plist addition generated by this target.
public func addGeneratedInfoPlistContent(_ path: Path) {
state.withLock { state in
assert(!state._inDeferredMode)
state._generatedInfoPlistContents.append(path)
}
}
func addPrivacyContentPlistContent(_ path: Path) {
state.withLock { state in
assert(!state._inDeferredMode)
state._generatedPrivacyContentFilePaths.insert(path)
}
}
/// Get the produced binary path for the given variant, if any.
func producedBinary(forVariant variant: String) -> Path? {
return state.withLock { state in
assert(state._inDeferredMode)
return state._producedBinaryPaths[variant]
}
}
/// Add a produced binary path for the given variant.
func addProducedBinary(path: Path, forVariant variant: String) {
state.withLock { state in
assert(!state._inDeferredMode)
assert(state._producedBinaryPaths[variant] == nil || state._producedBinaryPaths[variant] == path)
state._producedBinaryPaths[variant] = path
}
}
/// Get the produced dSYM path for the given variant, if any.
func producedDSYM(forVariant variant: String) -> Path? {
return state.withLock { state in
assert(state._inDeferredMode)
return state._producedDSYMPaths[variant]
}
}
/// Add a produced dSYM path for the given variant.
func addProducedDSYM(path: Path, forVariant variant: String) {
state.withLock { state in
assert(!state._inDeferredMode)
assert(state._producedDSYMPaths[variant] == nil || state._producedDSYMPaths[variant] == path)
state._producedDSYMPaths[variant] = path
}
}
/// Add a file that was copied.
func addCopiedPath(src: String, dst: String) {
state.withLock { state in
assert(!state._inDeferredMode)
state._copiedPathMap[dst, default: []].insert(src)
}
}
/// Get the map of the files which will be copied.
func copiedPathMap() -> [String: Set<String>] {
return state.withLock { state in
assert(state._inDeferredMode)
return state._copiedPathMap
}
}
/// Get the product custom TBD paths.
func generatedTBDFiles(forVariant variant: String) -> [Path] {
return state.withLock { state in
assert(state._inDeferredMode)
return state._generatedTBDFiles[variant] ?? []
}
}
/// Add a produced binary path for the given variant.
func addGeneratedTBDFile(_ path: Path, forVariant variant: String) {
state.withLock { state in
assert(!state._inDeferredMode)
state._generatedTBDFiles[variant, default: []].append(path)
}
}
/// Get the product generated Swift Objective-C interface header files.
func generatedSwiftObjectiveCHeaderFiles() -> [String: Path] {
return state.withLock { state in
//assert(state._inDeferredMode)
return state._generatedSwiftObjectiveCHeaderFiles
}
}
/// Add a generated Swift Objective-C interface header file.
func addGeneratedSwiftObjectiveCHeaderFile(_ path: Path, architecture: String) {
state.withLock { state in
assert(!state._inDeferredMode)
state._generatedSwiftObjectiveCHeaderFiles[architecture] = path
}
}
/// Get the product generated Swift Objective-C interface header files.
public func generatedSwiftConstMetadataFiles() -> [String: [Path]] {
return state.withLock { state in
assert(state._inDeferredMode)
return state._generatedGeneratedSwiftConstMetadataFiles
}
}
/// Add a generated Swift supplementary const metadata file.
func addGeneratedSwiftConstMetadataFile(_ path: Path, architecture: String) {
state.withLock { state in
assert(!state._inDeferredMode)
if state._generatedGeneratedSwiftConstMetadataFiles[architecture] != nil {
state._generatedGeneratedSwiftConstMetadataFiles[architecture]?.append(path)
} else {
state._generatedGeneratedSwiftConstMetadataFiles[architecture] = [path]
}
}
}
/// Virtual output nodes for shell script build phases that don't have any declared outputs.
func shellScriptVirtualOutputs() -> [PlannedVirtualNode] {
return state.withLock { state in
assert(state._inDeferredMode)
return state._shellScriptVirtualOutputs
}
}
func addShellScriptVirtualOutput(_ virtualOutput: PlannedVirtualNode) {
state.withLock { state in
assert(!state._inDeferredMode)
state._shellScriptVirtualOutputs.append(virtualOutput)
}
}
/// The outputs of the tasks for this target prior to deferred task production.
var outputsOfMainTaskProducers: [any PlannedNode] {
get {
state.withLock { state in
assert(state._inDeferredMode)
return state._outputsOfMainTaskProducers
}
}
set {
state.withLock { state in
assert(!state._inDeferredMode)
state._outputsOfMainTaskProducers = newValue
}
}
}
/// Add a deferred task production block.
public func addDeferredProducer(_ body: @escaping () async -> [any PlannedTask]) {
state.withLock { state in
assert(!state._inDeferredMode)
state._deferredProducers.append(body)
}
}
/// Take the list of deferred producers.
///
/// We model this as a "take" operation to ensure that any potential reference cycles through the producers are automatically discarded.
func takeDeferredProducers() -> [() async -> [any PlannedTask]] {
return state.withLock { state in
assert(!state._inDeferredMode)
state._inDeferredMode = true
let result = state._deferredProducers
state._deferredProducers.removeAll()
return result
}
}
/// Adds an additional codesign input that needs to be tracked.
/// - parameter alwaysAdd: Skips the check for the input path existing on disk. This is defaulted to `false`.
func addAdditionalCodeSignInput(_ path: Path, scope: MacroEvaluationScope, alwaysAdd: Bool = false) {
// This API should only be used during the `planning` phase.
assert(phase == .planning)
// A feature guard to provide a fallback mechanism, primarily to alleviate risk.
guard scope.evaluate(BuiltinMacros.ENABLE_ADDITIONAL_CODESIGN_INPUT_TRACKING) else { return }
// This is a bit unfortunate, but to prevent workspace diagnostic issues downstream, silently ignore any missing items, it's necessary to allow callers to ignore files that do not actually exist on disk.
let exists = fs.exists(path)
state.withLock { state in
assert(!state._inDeferredMode)
if alwaysAdd || exists {
state._additionalCodeSignInputs.append(path)
}
}
}
/// Adds all of the appropriate build files as additional codesign inputs.
func addAdditionalCodeSignInputs(_ buildFiles: [BuildFile], _ context: TaskProducerContext) {
for buildFile in buildFiles {
// A failure to resolve the build file reference is primarily when a file is being referenced that does not actually exist. There's not need to track that error here.
if let (ref, path, _) = try? context.resolveBuildFileReference(buildFile) {
// If the reference is coming from a product, we always add file to the signing input.
let alwaysAdd = ref is ProductReference
context.addAdditionalCodeSignInput(path, scope: context.settings.globalScope, alwaysAdd: alwaysAdd)
}
}
}
public func discoveredCommandLineToolSpecInfo(_ delegate: any CoreClientTargetDiagnosticProducingDelegate, _ toolName: String, _ path: Path, _ process: @Sendable (_ contents: Data) async throws -> any DiscoveredCommandLineToolSpecInfo) async throws -> any DiscoveredCommandLineToolSpecInfo {
try await workspaceContext.discoveredCommandLineToolSpecInfoCache.run(delegate, toolName, path, process)
}
public func discoveredCommandLineToolSpecInfo(_ delegate: any CoreClientTargetDiagnosticProducingDelegate, _ toolName: String?, _ commandLine: [String], _ process: @Sendable (_ processResult: Processes.ExecutionResult) async throws -> any DiscoveredCommandLineToolSpecInfo) async throws -> any DiscoveredCommandLineToolSpecInfo {
try await workspaceContext.discoveredCommandLineToolSpecInfoCache.run(delegate, toolName, commandLine, process)
}
public func shouldUseSDKStatCache() async -> Bool {
guard UserDefaults.enableSDKStatCaching else { return false }
if settings.globalScope.evaluate(BuiltinMacros.INDEX_ENABLE_BUILD_ARENA) {
return false
}
guard !Set(settings.globalScope.evaluate(BuiltinMacros.BUILD_COMPONENTS)).intersection(["build", "api"]).isEmpty else { return false }
// clang-stat-cache will currently treat the fs as case-insensitive if `taskpolicy -x` was used to force case-sensitivity.
guard !ProcessInfo.processInfo.isRunningUnderFilesystemCaseSensitivityIOPolicy else { return false }
guard let sdk, !localFS.isOnPotentiallyRemoteFileSystem(sdk.path) else { return false }
guard settings.globalScope.evaluate(BuiltinMacros.SDK_STAT_CACHE_ENABLE) else { return false }
guard let clangInfo = await clangSpec.discoveredCommandLineToolSpecInfo(self, settings.globalScope, delegate) as? DiscoveredClangToolSpecInfo, clangInfo.toolFeatures.has(.vfsstatcache) else { return false }
guard let standardTarget = configuredTarget?.target as? StandardTarget, let sourcesBuildPhase = standardTarget.sourcesBuildPhase, !sourcesBuildPhase.buildFiles.isEmpty else { return false }
return true
}
/// Retrieves a read-only view of the additional codesign inputs. This returns a sorted array for stability reasons.
var additionalCodeSignInputs: OrderedSet<Path> {
// The data from this collection should only be used after the planning phase has been completed. Doing so before can lead to incorrect assumptions due to the un-ordered nature of task producers.
assert(phase == .taskGeneration)
return state.withLock { state in
return state._additionalCodeSignInputs
}
}
// FIXME: <rdar://problem/30298464> This is something of a hack. Uses in the ProductPostprocessingTaskProducer say this should be expressed instead on a check against task validation criteria of the product.
//
/// Returns whether the product of the target is going to be produced.
///
/// Presently wrapped products are considered to always be produced. Standalone binary products are produced only if they will produce a binary.
func willProduceProduct(_ scope: MacroEvaluationScope? = nil) -> Bool {
// Non-standalone (i.e., wrapped) product types always produce a product.
guard settings.productType is StandaloneExecutableProductTypeSpec else {
return true
}
let scope = scope ?? settings.globalScope
assert(scope.values(for: BuiltinMacros.variantCondition) == nil, "calls to willProduceProduct must NOT be done in a variant scope")
assert(scope.values(for: BuiltinMacros.archCondition) == nil, "calls to willProduceProduct must NOT be done in an arch scope")
return scope.evaluate(BuiltinMacros.BUILD_VARIANTS).contains(where: { variant in willProduceBinary(scope.subscope(binding: BuiltinMacros.variantCondition, to: variant)) })
}
/// Returns whether a binary will be produced for the product.
///
/// A wrapped product will always produce a product, but it may or may not produce a binary depending on whether there are sources included in the target and other factors. This can affect some post-processing steps like codesigning.
func willProduceBinary(_ scope: MacroEvaluationScope, forArch: Bool = false) -> Bool {
assert(scope.values(for: BuiltinMacros.variantCondition) != nil, "calls to willProduceBinary must be done in a variant scope")
assert((scope.values(for: BuiltinMacros.archCondition) != nil) == forArch)
if !forArch {
return scope.evaluate(BuiltinMacros.ARCHS).contains(where: { arch in
willProduceBinary(scope.subscopeBindingArchAndTriple(arch: arch), forArch: true)
})
}
// If we're copying a stub binary for this target, then we have a binary.
guard !scope.evaluate(BuiltinMacros.PRODUCT_TYPE_HAS_STUB_BINARY) else {
return true
}
// If this target has no valid architectures, then it won't produce a binary because no files will be compiled.
guard !scope.evaluate(BuiltinMacros.ARCHS).isEmpty else {
return false
}
// If this target is generating a prelinked object file, then we assume it will produce a binary.
// FIXME: This is nasty. See SourcesTaskProducer.generateTasks() for handling of GENERATE_PRELINK_OBJECT_FILE.
guard !scope.evaluate(BuiltinMacros.GENERATE_PRELINK_OBJECT_FILE) else {
return true
}
// Otherwise, we are producing a binary if we have a Sources build phase and either that phase is not empty or we're generating a versioning stub file.
guard let target = configuredTarget?.target as? SWBCore.BuildPhaseTarget,
let sourcesBuildPhase = target.sourcesBuildPhase else {
return false
}
let context = BuildFilesProcessingContext(scope)
let hasObjectProducingSources = sourcesBuildPhase.buildFiles.filter {
guard let buildFile = try? resolveBuildFileReference($0), !context.isExcluded(buildFile.absolutePath, filters: $0.platformFilters) else {
return false
}
// AppleScript files don't produce object files either directly or transitively, so they cannot (for most definitions of "cannot") contribute to a linked Mach-O being produced.
if buildFile.fileType.identifier == "sourcecode.applescript" {
return false
}
return true
}.count > 0 || scope.generatesAppleGenericVersioningFile(context) || scope.generatesKernelExtensionModuleInfoFile(context, settings, sourcesBuildPhase)
// We will produce a binary if we have sources.
if hasObjectProducingSources {
return true
}
// Check if there are any object files or package products in the framework build phase.
if let frameworkBuildPhase = target.frameworksBuildPhase {
let containsObjectFile = frameworkBuildPhase.buildFiles.contains {
guard let buildFile = try? resolveBuildFileReference($0), !context.isExcluded(buildFile.absolutePath, filters: $0.platformFilters) else {
return false
}
// We will produce a product if the target type is a package product.
if (buildFile.reference as? ProductReference)?.target?.type == .packageProduct {
return true
}
// Finally, check if this is an object file.
return buildFile.fileType.identifier == "compiled.mach-o.objfile"
}
if containsObjectFile {
return true
}
}
return false
}
public func availableMatchingArchitecturesInStubBinary(at stubBinary: Path, requestedArchs: [String]) async -> [String] {
let stubArchs: Set<String>
let stubPlatformNames: [String]
do {
let stubInfo = try globalProductPlan.planRequest.buildRequestContext.getCachedMachOInfo(at: stubBinary)
stubArchs = stubInfo.architectures
stubPlatformNames = stubInfo.platforms.compactMap { lookupPlatformNames(platform: $0).only }
} catch {
delegate.error("unable to create tasks to copy stub binary: can't determine architectures of binary: \(stubBinary.str): \(error)")
return []
}
var archsToExtract: Set<String> = []
for arch in requestedArchs {
if stubArchs.contains(arch) {
archsToExtract.insert(arch)
} else {
let compatibilityArchs: [String] = stubPlatformNames.flatMap { platformName in
(workspaceContext.core.specRegistry.getSpec(arch, domain: platformName) as? ArchitectureSpec)?.compatibilityArchs ?? []
}
if let compatibleArch = compatibilityArchs.first(where: { stubArchs.contains($0) }) {
archsToExtract.insert(compatibleArch)
} else {
delegate.warning("stub binary at '\(stubBinary.str)' does not contain a slice for '\(arch)' or a compatible architecture. Stub architectures: \(stubArchs.joined(separator: ", ")). Compatibility architectures for \(arch): \(compatibilityArchs.joined(separator: ", "))")
}
}
}
return archsToExtract.sorted()
}
/// Returns true if we should emit errors when there are tasks that delay eager compilation.
func requiresEagerCompilation(_ scope: MacroEvaluationScope) -> Bool {
return scope.evaluate(BuiltinMacros.EAGER_COMPILATION_REQUIRE)
}
/// Returns true if we should emit errors when there are tasks that delay eager linking.
func requiresEagerLinking(_ scope: MacroEvaluationScope) -> Bool {
return scope.evaluate(BuiltinMacros.EAGER_LINKING_REQUIRE)
}
// MARK: Delegate Forwarding
package func createNode(_ path: Path) -> PlannedPathNode {
return delegate.createNode(absolutePath: makeAbsolute(path))
}
package func createDirectoryTreeNode(_ path: Path, excluding: [String]) -> PlannedDirectoryTreeNode {
return delegate.createDirectoryTreeNode(absolutePath: path, excluding: excluding)
}
package func createVirtualNode(_ name: String) -> PlannedVirtualNode {
return delegate.createVirtualNode(name)
}
package func createBuildDirectoryNode(absolutePath path: Path) -> PlannedPathNode {
return delegate.createBuildDirectoryNode(absolutePath: path)
}
func createGateTask(_ inputs: [any PlannedNode] = [], output: any PlannedNode, name: String? = nil, mustPrecede: [any PlannedTask] = [], taskConfiguration: (inout PlannedTaskBuilder) -> Void = { _ in }) -> any PlannedTask {
return delegate.createGateTask(inputs, output: output, name: name ?? output.name, mustPrecede: mustPrecede, taskConfiguration: taskConfiguration)
}
func createTask(_ options: TaskOrderingOptions = [], _ builder: inout PlannedTaskBuilder) -> any PlannedTask {
return delegate.createTask(&builder)
}
var phaseEndTasks: [any PlannedTask] = []
func createPhaseEndTask(inputs: [any PlannedNode], output: any PlannedNode, mustPrecede: [any PlannedTask]) -> any PlannedTask {
let task = createGateTask(inputs, output: output, mustPrecede: mustPrecede)
// FIXME: This is a rather gross way to collect all of these tasks, just so they can be added via the "TargetOrderTaskProducer".
phaseEndTasks.append(task)
return task
}
func recordAttachment(contents: ByteString) -> Path {
return delegate.recordAttachment(contents: contents)
}
/// Report a note from task construction.
public func note(_ message: String, location: Diagnostic.Location = .unknown, component: Component = .default) {
if let configuredTarget {
delegate.note(.overrideTarget(configuredTarget), message, location: location, component: component)
} else {
delegate.note(message, location: location, component: component)
}
}
/// Report a warning from task construction.
public func warning(_ message: String, location: Diagnostic.Location = .unknown, component: Component = .default) {
if let configuredTarget {
delegate.warning(.overrideTarget(configuredTarget), message, location: location, component: component)
} else {
delegate.warning(message, location: location, component: component)
}
}
/// Report an error from task construction.
public func error(_ message: String, location: Diagnostic.Location = .unknown, component: Component = .default) {
if let configuredTarget {
delegate.error(.overrideTarget(configuredTarget), message, location: location, component: component)
} else {
delegate.error(message, location: location, component: component)
}
}
/// Report a remark from task construction.
public func remark(_ message: String, location: Diagnostic.Location = .unknown, component: Component = .default) {
if let configuredTarget {
delegate.remark(.overrideTarget(configuredTarget), message, location: location, component: component)
} else {
delegate.remark(message, location: location, component: component)
}
}
/// Report a diagnostic from task construction.
func emit(_ kind: Diagnostic.Behavior, _ message: String, location: Diagnostic.Location = .unknown, component: Component = .default) {
switch kind {
case .error:
error(message, location: location, component: component)
case .warning:
warning(message, location: location, component: component)
case .note:
note(message, location: location, component: component)
case .remark:
remark(message, location: location, component: component)
case .ignored:
break
}
}
/// Report a diagnostic from task construction.
private func emit(data: DiagnosticData, behavior: Diagnostic.Behavior, location: Diagnostic.Location = .unknown) {
delegate.emit(Diagnostic(behavior: behavior, location: location, data: data))
}
/// Report an error that is caused by a missing package product.
func missingPackageProduct(_ packageName: String, _ buildFile: BuildFile, _ buildPhase: BuildPhase) {
error("Missing package product '\(packageName)'",
location: .buildFile(buildFileGUID: buildFile.guid, buildPhaseGUID: buildPhase.guid, targetGUID: configuredTarget?.target.guid ?? ""),
component: .packageResolution)
}
func missingNamedReference(_ name: String, _ buildFile: BuildFile, _ buildPhase: BuildPhase) {
// TODO: Semantic build file locations end up going to the General tab in Xcode, but here we have our first use case where we ALWAYS want it to go to the Build Phases tab.
// Will need to figure out a way to abstract this into the diagnostics model which doesn't directly map to Xcode's UI. Perhaps an `exact` flag?
error("This \(buildPhase.name) build phase contains a reference to a missing file '\(name)'.",
location: .buildFile(buildFileGUID: buildFile.guid, buildPhaseGUID: buildPhase.guid, targetGUID: configuredTarget?.target.guid ?? ""),
component: .targetIntegrity)
}
func emitFileExclusionDiagnostic(_ exclusionReason: BuildFileExclusionReason, _ context: any BuildFileFilteringContext, _ path: Path, _ filters: Set<PlatformFilter>, _ buildFileLocation: Diagnostic.Location?) {
guard workspaceContext.userPreferences.enableDebugActivityLogs else {
return
}
switch exclusionReason {
case .platformFilter:
let filterString = filters.sorted().map(\.comparisonString).joined(separator: ", ").nilIfEmpty ?? "<none>"
let currentFilterString = context.currentPlatformFilter?.comparisonString.nilIfEmpty ?? "<none>"
self.emit(.note, "Skipping '\(path.str)' because its platform filter (\(filterString)) does not match the platform filter of the current context (\(currentFilterString)).", location: buildFileLocation ?? .unknown)
case let .patternLists(excludePattern):
let excl = context.excludedSourceFileNames.joined(separator: " ")
let incl = context.includedSourceFileNames.joined(separator: " ")
self.delegate.emit(configuredTarget.map { .overrideTarget($0) } ?? .default, Diagnostic(behavior: .note, location: buildFileLocation ?? .unknown, data: DiagnosticData("Skipping '\(path.str)' because it is excluded by EXCLUDED_SOURCE_FILE_NAMES pattern: \(excludePattern)"), childDiagnostics: [
Diagnostic(behavior: .note, location: .buildSetting(name: BuiltinMacros.EXCLUDED_SOURCE_FILE_NAMES.name), data: DiagnosticData("EXCLUDED_SOURCE_FILE_NAMES: \(excl)")),
Diagnostic(behavior: .note, location: .buildSetting(name: BuiltinMacros.INCLUDED_SOURCE_FILE_NAMES.name), data: DiagnosticData("INCLUDED_SOURCE_FILE_NAMES: \(incl)")),
]))
}
}
package var allOnDemandResourcesAssetPacks: [ODRAssetPackInfo] {
return state.withLock { state in Array(state.onDemandResourcesAssetPacks.values) }
}
public func onDemandResourcesAssetPack(for tags: ODRTagSet) -> ODRAssetPackInfo? {
guard onDemandResourcesEnabled else { return nil }
if let r = (state.withLock { state in state.onDemandResourcesAssetPacks[tags] }) { return r }
let maxPriority = tags.lazy.compactMap { self.onDemandResourcesAssetTagPriority(tag: $0) }.max()
let productBundleIdentifier = settings.globalScope.evaluate(BuiltinMacros.PRODUCT_BUNDLE_IDENTIFIER)
guard !productBundleIdentifier.isEmpty else {
self.error("On-Demand Resources is enabled (ENABLE_ON_DEMAND_RESOURCES = YES), but the PRODUCT_BUNDLE_IDENTIFIER build setting is empty", location: .buildSetting(BuiltinMacros.PRODUCT_BUNDLE_IDENTIFIER))
return nil
}