-
Notifications
You must be signed in to change notification settings - Fork 83
/
Copy pathSettings.swift
5353 lines (4523 loc) · 300 KB
/
Settings.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
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
public import SWBUtil
public import SWBProtocol
public import SWBMacro
fileprivate struct PreOverridesSettings {
var sdk: SDK?
}
/// This class stores settings tables which are cached or shared across all clients of the Core.
@_spi(Testing) public final class CoreSettings {
/// The core this object is associated with.
unowned let core: Core
/// The default toolchain.
@_spi(Testing) public let defaultToolchain: Toolchain?
/// The core build system.
@_spi(Testing) public let coreBuildSystemSpec: BuildSystemSpec!
/// The external build system.
let externalBuildSystemSpec: BuildSystemSpec!
/// The native build system.
let nativeBuildSystemSpec: BuildSystemSpec!
init(_ core: Core) {
self.core = core
// Ensure platform extended info is initialized.
//
// FIXME: This needs to be handled better.
if !core.platformRegistry.hasLoadedExtendedInfo {
core.platformRegistry.loadExtendedInfo(core.specRegistry.internalMacroNamespace)
}
// Bind the default toolchain.
if let toolchain = core.toolchainRegistry.lookup("default") {
self.defaultToolchain = toolchain
} else {
core.delegate.error("missing required default toolchain")
self.defaultToolchain = nil
}
// We pre-bind various specifications we do not support running without.
func getRequiredBuildSystemSpec(_ identifier: String) -> BuildSystemSpec? {
guard let spec = core.specRegistry.getSpec(identifier) else {
core.delegate.error("missing required spec '\(identifier)'")
return nil
}
guard let buildSystemSpec = spec as? BuildSystemSpec else {
core.delegate.error("invalid type for required 'BuildSystem' spec '\(identifier)'")
return nil
}
return buildSystemSpec
}
self.coreBuildSystemSpec = getRequiredBuildSystemSpec("com.apple.build-system.core")
self.externalBuildSystemSpec = getRequiredBuildSystemSpec("com.apple.build-system.external")
self.nativeBuildSystemSpec = getRequiredBuildSystemSpec("com.apple.build-system.native")
}
private var unionedToolDefaultsCache = Registry<String, (MacroValueAssignmentTable, errors: [String])>()
@_spi(Testing) public func unionedToolDefaults(domain: String) -> (table: MacroValueAssignmentTable, errors: [String]) {
return unionedToolDefaultsCache.getOrInsert(domain) {
var table = MacroValueAssignmentTable(namespace: core.specRegistry.internalMacroNamespace)
var errors = [String]()
// - We have a bag of tools, each of which has build options with optional default values.
// - There's no meaningful ordering or layering between the tools (all tools in a domain are peers - even if they ended up in that domain through domain composition), so we don't want to add the same macros on top of each other (whether linked or overwritten). We'll only allow one assignment of any given macro.
// - If there's a conflict (the same macro is assigned twice with different values), we'll emit an error. Since this is an error, the order in which we traverse specs to add defaults doesn't matter.
let specs = core.specRegistry.findSpecs(CommandLineToolSpec.self, domain: domain)
let ignoredMacros: [MacroDeclaration] = [BuiltinMacros.OutputFormat, BuiltinMacros.OutputPath]
for spec in specs {
for option in spec.flattenedBuildOptions.values {
guard !ignoredMacros.contains(option.macro) else { continue }
if let value = option.defaultValue {
if let existing = table.lookupMacro(option.macro) {
if existing.expression != value {
errors.append("Conflicting default values for \(option.macro.name):\n\(value.stringRep)\n\(existing.expression.stringRep)")
}
continue
}
table.push(option.macro, value)
}
// FIXME: Xcode has support here for adding additional build settings for the option, but nothing seems to use it. Eliminate this if nothing shows up.
}
}
return (table, errors)
}
}
fileprivate var universalDefaults: MacroValueAssignmentTable { return universalDefaultsCache.getValue(self) }
private var universalDefaultsCache = LazyCache{ (settings: CoreSettings) -> MacroValueAssignmentTable in settings.computeUniversalDefaults() }
private func computeUniversalDefaults() -> MacroValueAssignmentTable {
var table = MacroValueAssignmentTable(namespace: BuiltinMacros.namespace)
// Add the constants.
// FIXME: Deprecate this setting, once we have the capability of doing so.
table.push(BuiltinMacros.OS, literal: "MACOS")
table.push(BuiltinMacros.arch, literal: "undefined_arch")
table.push(BuiltinMacros.variant, literal: "normal")
table.push(BuiltinMacros.SYSTEM_APPS_DIR, literal: "/Applications")
table.push(BuiltinMacros.SYSTEM_ADMIN_APPS_DIR, literal: "/Applications/Utilities")
table.push(BuiltinMacros.SYSTEM_DEMOS_DIR, literal: "/Applications/Extras")
table.push(BuiltinMacros.SYSTEM_LIBRARY_DIR, literal: "/System/Library")
table.push(BuiltinMacros.SYSTEM_CORE_SERVICES_DIR, literal: "/System/Library/CoreServices")
table.push(BuiltinMacros.SYSTEM_DOCUMENTATION_DIR, literal: "/Library/Documentation")
table.push(BuiltinMacros.SYSTEM_LIBRARY_EXECUTABLES_DIR, literal: "")
table.push(BuiltinMacros.SYSTEM_DEVELOPER_EXECUTABLES_DIR, literal: "")
table.push(BuiltinMacros.LOCAL_ADMIN_APPS_DIR, literal: "/Applications/Utilities")
table.push(BuiltinMacros.LOCAL_APPS_DIR, literal: "/Applications")
table.push(BuiltinMacros.LOCAL_DEVELOPER_DIR, literal: "/Library/Developer")
table.push(BuiltinMacros.LOCAL_DEVELOPER_EXECUTABLES_DIR, literal: "")
table.push(BuiltinMacros.LOCAL_LIBRARY_DIR, literal: "/Library")
table.push(BuiltinMacros.USER_APPS_DIR, BuiltinMacros.namespace.parseString("$(HOME)/Applications"))
table.push(BuiltinMacros.USER_LIBRARY_DIR, BuiltinMacros.namespace.parseString("$(HOME)/Library"))
// TODO: rdar://80796520 (Re-enable dependency validator)
//table.push(BuiltinMacros.VALIDATE_DEPENDENCIES, literal: .yes)
table.push(BuiltinMacros.VALIDATE_DEVELOPMENT_ASSET_PATHS, literal: .yesError)
table.push(BuiltinMacros.DIAGNOSE_MISSING_TARGET_DEPENDENCIES, literal: .yes)
// This is a hack to allow more tests to run in Swift CI when using older Xcode versions.
if core.xcodeProductBuildVersion < (try! ProductBuildVersion("16A242d")) {
table.push(BuiltinMacros.LM_SKIP_METADATA_EXTRACTION, BuiltinMacros.namespace.parseString("YES"))
}
// Add the "calculated" settings.
addCalculatedUniversalDefaults(&table)
return table
}
private func addCalculatedUniversalDefaults(_ table: inout MacroValueAssignmentTable) {
// NOTE: All of these settings must depend only on the core, and be immutable, as these values are cached in the universal defaults table.
// FIXME: These need to translate to "fake-VFS" paths, for the pseudo-SWB testing.
let developerPath = core.developerPath.path
switch core.developerPath {
case .xcode(let path):
let legacyDeveloperPath = path.dirname.join("PlugIns/Xcode3Core.ideplugin/Contents/SharedSupport/Developer")
table.push(BuiltinMacros.LEGACY_DEVELOPER_DIR, literal: legacyDeveloperPath.str)
default:
break
}
let developerToolsPath = developerPath.join("Tools")
let developerAppsPath = developerPath.join("Applications")
let developerLibPath = developerPath.join("Library")
let developerAppSupportPath = developerLibPath.join("Xcode")
let developerFrameworksPath = developerLibPath.join("Frameworks")
let javaToolsPath = developerAppsPath.join("Java Tools")
let perfToolsPath = developerAppsPath.join("Performance Tools")
let graphicsToolsPath = developerAppsPath.join("Graphics Tools")
let developerUtilitiesPath = developerAppsPath.join("Utilities")
let developerDemosPath = developerUtilitiesPath.join("Built Examples")
let developerDocPath = developerPath.join("ADC Reference Library")
let developerToolsDocPath = developerDocPath.join("documentation/DeveloperTools")
let developerReleaseNotesPath = developerDocPath.join("releasenotes")
let developerToolsReleaseNotesPath = developerReleaseNotesPath.join("DeveloperTools")
let developerUsrPath = developerPath.join("usr")
let developerBinPath = developerPath.join("usr/bin")
// For historical reasons, DEVELOPER_SDK_DIR is the SDKs directory inside the default (macOS) platform. If there is no macOS platform then it will not be assigned.
var developerSDKsPath: Path? = nil
if let macosPlatform = core.platformRegistry.lookup(identifier: "com.apple.platform.macosx") {
developerSDKsPath = macosPlatform.path.join("Developer/SDKs")
}
// FIXME: We should see if any of these can be deprecated, once we support that.
table.push(BuiltinMacros.SYSTEM_DEVELOPER_DIR, literal: developerPath.str)
table.push(BuiltinMacros.DEVELOPER_DIR, literal: developerPath.str)
table.push(BuiltinMacros.SYSTEM_DEVELOPER_APPS_DIR, literal: developerAppsPath.str)
table.push(BuiltinMacros.DEVELOPER_APPLICATIONS_DIR, literal: developerAppsPath.str)
table.push(BuiltinMacros.DEVELOPER_LIBRARY_DIR, literal: developerLibPath.str)
table.push(BuiltinMacros.DEVELOPER_FRAMEWORKS_DIR, literal: developerFrameworksPath.str)
table.push(BuiltinMacros.DEVELOPER_FRAMEWORKS_DIR_QUOTED, literal: developerFrameworksPath.str)
table.push(BuiltinMacros.SYSTEM_DEVELOPER_JAVA_TOOLS_DIR, literal: javaToolsPath.str)
table.push(BuiltinMacros.SYSTEM_DEVELOPER_PERFORMANCE_TOOLS_DIR, literal: perfToolsPath.str)
table.push(BuiltinMacros.SYSTEM_DEVELOPER_GRAPHICS_TOOLS_DIR, literal: graphicsToolsPath.str)
table.push(BuiltinMacros.SYSTEM_DEVELOPER_UTILITIES_DIR, literal: developerUtilitiesPath.str)
table.push(BuiltinMacros.SYSTEM_DEVELOPER_DEMOS_DIR, literal: developerDemosPath.str)
table.push(BuiltinMacros.SYSTEM_DEVELOPER_DOC_DIR, literal: developerDocPath.str)
table.push(BuiltinMacros.SYSTEM_DEVELOPER_TOOLS_DOC_DIR, literal: developerToolsDocPath.str)
table.push(BuiltinMacros.SYSTEM_DEVELOPER_RELEASENOTES_DIR, literal: developerReleaseNotesPath.str)
table.push(BuiltinMacros.SYSTEM_DEVELOPER_TOOLS_RELEASENOTES_DIR, literal: developerToolsReleaseNotesPath.str)
table.push(BuiltinMacros.SYSTEM_DEVELOPER_TOOLS, literal: developerToolsPath.str)
table.push(BuiltinMacros.DEVELOPER_TOOLS_DIR, literal: developerToolsPath.str)
table.push(BuiltinMacros.SYSTEM_DEVELOPER_USR_DIR, literal: developerUsrPath.str)
table.push(BuiltinMacros.DEVELOPER_USR_DIR, literal: developerUsrPath.str)
table.push(BuiltinMacros.SYSTEM_DEVELOPER_BIN_DIR, literal: developerBinPath.str)
table.push(BuiltinMacros.DEVELOPER_BIN_DIR, literal: developerBinPath.str)
if let developerSDKsPath {
table.push(BuiltinMacros.DEVELOPER_SDK_DIR, literal: developerSDKsPath.str)
}
table.push(BuiltinMacros.XCODE_APP_SUPPORT_DIR, literal: developerAppSupportPath.str)
let availablePlatformNames = core.platformRegistry.platformsByIdentifier.values.map({ $0.name }).sorted()
table.push(BuiltinMacros.AVAILABLE_PLATFORMS, literal: availablePlatformNames)
}
// FIXME: This never actually pushed anything to the table, so I've disabled it for now.
#if false
private var unionedCustomizedCompilerDefaultsCache = Registry<String, MacroValueAssignmentTable>()
fileprivate func unionedCustomizedCompilerDefaults(domain: String) -> MacroValueAssignmentTable {
// FIXME: This table is barely used (for Xcode proper it is almost empty). We should figure out if there might be a simpler solution to this problem.
//
// That said, it would likely be used a lot more often if we started to pull compiler specific defaults out of the unioned table, although if we had alternate support for them (for example, recognizing the macro type as compiler specific and error out on access from invalid contents), then we might still be able to push them as a single unioned table.
return unionedCustomizedCompilerDefaultsCache.getOrInsert(domain) {
// Add the defaults from all the registered tools in the given domain.
//
// FIXME: This is somewhat wasteful, as we end up duplicating values for super specifications. However, that lets us keep the condition set required to enable a particular compiler very simple.
let unionedDefaults = unionedToolDefaults(domain: domain)
let customizedDefaults = MacroValueAssignmentTable(namespace: core.specRegistry.internalMacroNamespace)
for spec in core.specRegistry.findSpecs(CompilerSpec.self, domain: domain) {
// Add all the necessary defaults.
for option in spec.flattenedBuildOptions.values {
if let defaultValue = option.defaultValue {
// Only push the default value if it diverges from the existing default.
//
// FIXME: This optimization could be subsumed by the macro assignment table itself, but for now we do it here as an important special case.
if let existingDefault = unionedDefaults.lookupMacro(option.macro)?.expression, existingDefault == defaultValue {
continue
}
// FIXME: Need ability to push conditional assignments.
}
}
}
return customizedDefaults
}
}
#endif
/// The cache for system build rules.
private let systemBuildRuleCache = Registry<SystemBuildRuleCacheKey, SystemBuildRules>()
struct SystemBuildRuleCacheKey: Hashable {
private let combineHiDPIImages: Bool
private let platform: Ref<Platform>?
init(combineHiDPIImages: Bool, platform: Ref<Platform>?) {
self.combineHiDPIImages = combineHiDPIImages
self.platform = platform
}
}
struct SystemBuildRules {
let rules: [(any BuildRuleCondition, any BuildRuleAction)]
let diagnostics: OrderedSet<Diagnostic>
}
fileprivate func systemBuildRules(combineHiDPIImages: Bool, platform: Platform?, scope: MacroEvaluationScope) -> SystemBuildRules {
let key = SystemBuildRuleCacheKey(combineHiDPIImages: combineHiDPIImages, platform: platform.map({ Ref($0) }))
let value = systemBuildRuleCache.getOrInsert(key) {
let specLookupContext = SpecLookupCtxt(specRegistry: core.specRegistry, platform: platform)
var diagnostics = OrderedSet<Diagnostic>()
// The namespace to use to parse settings.
let namespace = specLookupContext.specRegistry.internalMacroNamespace
// We’ll be building up and returning an array of condition-action pairs.
var rules = [(any BuildRuleCondition, any BuildRuleAction)]()
guard let tiffutilToolSpec = specLookupContext.getSpec("com.apple.compilers.tiffutil") as? CommandLineToolSpec else {
diagnostics.append(Diagnostic(behavior: .error, location: .unknown, data: DiagnosticData("Couldn't load tool spec com.apple.compilers.tiffutil")))
return .init(rules: [], diagnostics: diagnostics)
}
guard let copyTiffFileToolSpec = specLookupContext.getSpec("com.apple.build-tasks.copy-tiff-file") as? CommandLineToolSpec else {
diagnostics.append(Diagnostic(behavior: .error, location: .unknown, data: DiagnosticData("Couldn't load tool spec com.apple.build-tasks.copy-tiff-file")))
return .init(rules: [], diagnostics: diagnostics)
}
// Temporary hack: Add a couple of rules for combining HiDPI images. These rules are handled through custom logic in the legacy build system. We emulate this by making them precede the other rules.
let tiffRuleAction = combineHiDPIImages ? tiffutilToolSpec : copyTiffFileToolSpec
// FIXME: This should probably use file types instead of patterns once we have a good API for that.
rules.append((BuildRuleFileNameCondition(namePatterns: [Static { namespace.parseString("*.tiff") }]), BuildRuleTaskAction(toolSpec: tiffRuleAction)))
rules.append((BuildRuleFileNameCondition(namePatterns: [Static { namespace.parseString("*.tif") }]), BuildRuleTaskAction(toolSpec: tiffRuleAction)))
if combineHiDPIImages {
rules.append((BuildRuleFileNameCondition(namePatterns: [Static { namespace.parseString("*.png") }]), BuildRuleTaskAction(toolSpec: tiffutilToolSpec)))
rules.append((BuildRuleFileNameCondition(namePatterns: [Static { namespace.parseString("*.jpg") }]), BuildRuleTaskAction(toolSpec: tiffutilToolSpec)))
}
// First we synthesize build rules from tool specifications which declare that they do so.
// Sort the tool specifications by identifier, since there is no inherent order between them; this at least stable, and matches Xcode.
for toolSpec in specLookupContext.findSpecs(CommandLineToolSpec.self).sorted(by: \.identifier) {
// If the tool specification doesn’t want to synthesize build rules, we just proceed to the next one.
guard toolSpec.shouldSynthesizeBuildRules else { continue }
// If the tool specification doesn’t have any file type descriptors, we just proceed to the next one.
guard let inputFileTypeDescriptors = toolSpec.inputFileTypeDescriptors else { continue }
// Otherwise, go through its input file type descriptors
for inputFileType in inputFileTypeDescriptors {
guard let fileType = specLookupContext.getSpec(inputFileType.identifier) as? FileTypeSpec else {
diagnostics.append(Diagnostic(behavior: .error, location: .unknown, data: DiagnosticData("Couldn't load file type spec '\(inputFileType.identifier)' in domain '\(specLookupContext.domain)'")))
return .init(rules: [], diagnostics: diagnostics)
}
// Create a condition and an action from the information in the tool specification.
let condition = BuildRuleFileTypeCondition(fileType: fileType)
let action = BuildRuleTaskAction(toolSpec: toolSpec)
// Append the condition-action pair as a build rule.
rules.append((condition, action))
}
}
// Method to load all build rules from a plist file.
func loadBuildRules(from path: Path) -> [(any BuildRuleCondition, any BuildRuleAction)] {
do {
return try PropertyList.decode([BuildRuleFile].self, from: PropertyList.fromPath(path, fs: localFS)).map {
try core.createRule(buildRule: $0, platform: platform, scope: scope, namespace: namespace)
}
} catch {
diagnostics.append(Diagnostic(behavior: .error, location: .path(path), data: DiagnosticData("Couldn't load build rules file: \(error)")))
return []
}
}
func findAndLoadBuildRules(resourcesPath: Path) {
for item in (try? localFS.listdir(resourcesPath)) ?? [] {
let itemPath = resourcesPath.join(item)
// If this is a .xcbuildrules file, then load it. Ignore dotfiles, as installing roots on filesystems which don't support extended attributes (such as NFS) may create AppleDouble files.
if !itemPath.basename.hasPrefix(".") && itemPath.fileSuffix == ".xcbuildrules" {
rules.append(contentsOf: loadBuildRules(from: itemPath))
}
}
}
@preconcurrency @PluginExtensionSystemActor func searchPaths() -> [Path] {
core.pluginManager.extensions(of: SpecificationsExtensionPoint.self).flatMap { ext in
ext.specificationSearchPaths(resourceSearchPaths: core.resourceSearchPaths).compactMap { try? $0.filePath }
}.sorted()
}
// Add rules from the Resources directories of the loaded plugins. We sort the paths to ensure deterministic loading.
for searchPath in searchPaths() {
findAndLoadBuildRules(resourcesPath: searchPath)
}
return SystemBuildRules(rules: rules, diagnostics: diagnostics)
}
return value
}
}
/// This class stores settings tables which are cached by the WorkspaceContext.
final class WorkspaceSettings: Sendable {
unowned let workspaceContext: WorkspaceContext
var core: Core {
return workspaceContext.core
}
var coreSettings: CoreSettings {
return core.coreSettings
}
init(_ workspaceContext: WorkspaceContext) {
self.workspaceContext = workspaceContext
}
struct BuiltinSettingsInfoKey: Hashable, Sendable {
let targetType: TargetType?
let domain: String
}
struct BuiltinSettingsInfo: Sendable {
/// The actual settings.
let table: MacroValueAssignmentTable
/// The set of macro name to export to shell scripts.
let exportedMacros: Set<MacroDeclaration>
/// Errors generated during construction, to be reported in the build log.
let errors: [String]
}
private let builtinSettingsInfoCache = Registry<BuiltinSettingsInfoKey, BuiltinSettingsInfo>()
func builtinSettingsInfo(forTargetType targetType: TargetType?, domain: String) -> BuiltinSettingsInfo {
return builtinSettingsInfoCache.getOrInsert(BuiltinSettingsInfoKey(targetType: targetType, domain: domain)) {
var errors = [String]()
var builtinsTable = MacroValueAssignmentTable(namespace: workspaceContext.workspace.userNamespace)
var exportedMacros = Set<MacroDeclaration>()
func push(_ items: MacroValueAssignmentTable, exported: Bool = false) {
builtinsTable.pushContentsOf(items)
if exported {
exportedMacros.formUnion(items.valueAssignments.keys)
}
}
// Add the environment settings from the user info.
if let userInfo = workspaceContext.userInfo {
// FIXME: See also `createTableFromUserSettings`
var settingsCopy = [String: PropertyListItem]()
for (key, value) in userInfo.buildSystemEnvironment {
settingsCopy[key] = .plString(value)
}
do {
push(try builtinsTable.namespace.parseTable(settingsCopy, allowUserDefined: true))
} catch {
errors.append("unable to parse user environment: '\(error)'")
}
}
// Add the tool defaults.
do {
let (table, toolErrors) = coreSettings.unionedToolDefaults(domain: domain)
push(table)
errors.append(contentsOf: toolErrors)
}
// Add the builtin universal settings.
push(coreSettings.universalDefaults, exported: true)
// Add the dynamic defaults which may depend on the environment.
push(getDynamicUniversalDefaults(), exported: true)
// Add internal, implementation specific defaults.
push(getInternalDefaults())
// Add the appropriate build system settings.
// FIXME: <rdar://problem/56210749> Support BuildSystem specs per platform - Radar contains work-in-progress patches to support this.
let buildSystemSpec: BuildSystemSpec
switch targetType {
case .external?:
buildSystemSpec = coreSettings.externalBuildSystemSpec
case .standard?, .aggregate?, .packageProduct?:
buildSystemSpec = coreSettings.nativeBuildSystemSpec
case nil:
buildSystemSpec = coreSettings.coreBuildSystemSpec
}
do {
var table = MacroValueAssignmentTable(namespace: core.specRegistry.internalMacroNamespace)
for option in buildSystemSpec.flattenedBuildOptions.values {
option.addDefaultIfNecessary(&table)
}
// Add additional settings from build settings specs.
//
// FIXME: For legacy compatibility, we only do this when configuring settings for a target. This distinction most likely isn't important, and should just be eliminated.
if targetType != nil {
for spec in core.specRegistry.findSpecs(BuildSettingsSpec.self, domain: domain) {
for option in spec.flattenedBuildOptions.values {
option.addDefaultIfNecessary(&table)
}
}
}
push(table, exported: true)
}
// Add the compiler specific settings.
//
// This is necessary to support tools that have distinct values for the same settings (otherwise the tool defaults above would covert it), and is used in conjunction with a compiler condition asserted by the build phase processing.
#if false // This never did anything, see comments at `unionedCustomizedCompilerDefaults`
push(coreSettings.unionedCustomizedCompilerDefaults(domain: domain))
#endif
return BuiltinSettingsInfo(table: builtinsTable, exportedMacros: exportedMacros, errors: errors)
}
}
// MARK: Utilities
func getCacheRoot() -> Path {
// FIXME: Cache this.
// Use the value of CCHROOT if it is provided, absolute, and not doesn't look like our own caches path.
let cacheRootPath: Path
if let cchroot = workspaceContext.userInfo?.buildSystemEnvironment["CCHROOT"], cchroot.hasPrefix("/") && cchroot != "" && !cchroot.hasPrefix("/Library/Caches/com.apple.Xcode") {
cacheRootPath = Path(cchroot)
} else {
// Otherwise, derive the result from the secure system cache directory.
cacheRootPath = userCacheDir().join("com.apple.DeveloperTools")
}
// Add the version, build, and app name (to match Xcode).
return cacheRootPath.join("\(core.xcodeVersionString)-\(core.xcodeProductBuildVersionString)").join("Xcode")
}
/// Add the dynamic universal defaults.
func getDynamicUniversalDefaults() -> MacroValueAssignmentTable {
// These settings are always exported.
var table = MacroValueAssignmentTable(namespace: core.specRegistry.internalMacroNamespace)
// Add the CACHE_ROOT definition.
table.push(BuiltinMacros.CACHE_ROOT, literal: getCacheRoot().str)
// Add additional settings for which we explicitly allow the environment to override the default definition.
// Inherit or add DT_TOOLCHAIN_DIR.
if let dtToolchainDir = workspaceContext.userInfo?.buildSystemEnvironment["DT_TOOLCHAIN_DIR"] {
table.push(BuiltinMacros.DT_TOOLCHAIN_DIR, literal: dtToolchainDir)
} else if let defaultToolchain = coreSettings.defaultToolchain {
table.push(BuiltinMacros.DT_TOOLCHAIN_DIR, literal: defaultToolchain.path.str)
}
return table
}
/// Add internal implementation specific defaults.
func getInternalDefaults() -> MacroValueAssignmentTable {
var table = MacroValueAssignmentTable(namespace: core.specRegistry.internalMacroNamespace)
// Add convenience macros for access some computed files for Swift.
table.push(BuiltinMacros.SWIFT_UNEXTENDED_MODULE_MAP_PATH, Static { BuiltinMacros.namespace.parseString("$(TARGET_TEMP_DIR)/unextended-module.modulemap") })
table.push(BuiltinMacros.SWIFT_UNEXTENDED_VFS_OVERLAY_PATH, Static { BuiltinMacros.namespace.parseString("$(TARGET_TEMP_DIR)/unextended-module-overlay.yaml") })
table.push(BuiltinMacros.SWIFT_UNEXTENDED_INTERFACE_HEADER_PATH, Static { BuiltinMacros.namespace.parseString("$(TARGET_TEMP_DIR)/unextended-interface-header.h") })
// Add convenience macros for TAPI.
table.push(BuiltinMacros.TAPI_OUTPUT_PATH, Static { BuiltinMacros.namespace.parseString("$(TARGET_BUILD_DIR)/$(CONTENTS_FOLDER_PATH)/$(EXECUTABLE_PREFIX)$(PRODUCT_NAME)$(EXECUTABLE_VARIANT_SUFFIX).tbd") })
// Add shared output path for eager linking TBDs.
table.push(BuiltinMacros.EAGER_LINKING_INTERMEDIATE_TBD_DIR, Static { BuiltinMacros.namespace.parseString("$(OBJROOT)/EagerLinkingTBDs/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME)") })
table.push(BuiltinMacros.EAGER_LINKING_INTERMEDIATE_TBD_PATH, Static { BuiltinMacros.namespace.parseString("$(EAGER_LINKING_INTERMEDIATE_TBD_DIR)/$(CONTENTS_FOLDER_PATH)/$(EXECUTABLE_PREFIX)$(PRODUCT_NAME)$(EXECUTABLE_VARIANT_SUFFIX).tbd") })
// Add shared output path for clang explicit modules
table.push(BuiltinMacros.CLANG_EXPLICIT_MODULES_OUTPUT_PATH, Static { BuiltinMacros.namespace.parseString("$(OBJROOT)/ExplicitPrecompiledModules") })
// Add shared output path for Swift explicit modules
table.push(BuiltinMacros.SWIFT_EXPLICIT_MODULES_OUTPUT_PATH, Static { BuiltinMacros.namespace.parseString("$(OBJROOT)/SwiftExplicitPrecompiledModules") })
// Add default values for the compilation caching plugin (off-by-default).
table.push(BuiltinMacros.COMPILATION_CACHE_PLUGIN_PATH, Static { BuiltinMacros.namespace.parseString("$(DEVELOPER_USR_DIR)/lib/libToolchainCASPlugin.dylib") })
// Add default value for using integrated compilation cache queries.
table.push(BuiltinMacros.COMPILATION_CACHE_ENABLE_INTEGRATED_QUERIES, literal: true)
// Enable the integrated driver
table.push(BuiltinMacros.SWIFT_USE_INTEGRATED_DRIVER, literal: true)
if SWBFeatureFlag.enableEagerLinkingByDefault.value {
table.push(BuiltinMacros.EAGER_LINKING, literal: true)
}
// Add default value for using Swift response files
table.push(BuiltinMacros.USE_SWIFT_RESPONSE_FILE, literal: true)
// Do not add arm64e to ARCHS_STANDARD by default
table.push(BuiltinMacros.ENABLE_POINTER_AUTHENTICATION, literal: false)
// Enable additional codesign tracking by default, but opt-out of scripts phases as their outputs are free-form, and thus have the potential to introduce cycles in the build some circumstances. If that does happen, these build settings provide a relief valve while projects authors figure out how to break the cycle they are introducing (or how we break the target dependencies more granularly).
table.push(BuiltinMacros.ENABLE_ADDITIONAL_CODESIGN_INPUT_TRACKING, literal: true)
table.push(BuiltinMacros.ENABLE_ADDITIONAL_CODESIGN_INPUT_TRACKING_FOR_SCRIPT_OUTPUTS, literal: true)
/// <rdar://problem/59862065> Remove EnableInstallHeadersFiltering after validation
if SWBFeatureFlag.enableInstallHeadersFiltering.value {
table.push(BuiltinMacros.EXPERIMENTAL_ALLOW_INSTALL_HEADERS_FILTERING, literal: true)
}
if SWBFeatureFlag.enableClangExplicitModulesByDefault.value {
table.push(BuiltinMacros.CLANG_ENABLE_EXPLICIT_MODULES, literal: true)
}
if SWBFeatureFlag.enableSwiftExplicitModulesByDefault.value {
table.push(BuiltinMacros.SWIFT_ENABLE_EXPLICIT_MODULES, literal: .enabled)
}
if SWBFeatureFlag.enableClangCachingByDefault.value {
table.push(BuiltinMacros.CLANG_ENABLE_COMPILE_CACHE, literal: .enabled)
}
if SWBFeatureFlag.enableSwiftCachingByDefault.value {
table.push(BuiltinMacros.SWIFT_ENABLE_COMPILE_CACHE, literal: .enabled)
}
return table
}
}
/// This class represents the computed settings of a project and (optionally) target.
public final class Settings: PlatformBuildContext, Sendable {
/// The build parameters which were used to construct these settings.
public let parameters: BuildParameters
private let settingsContext: SettingsContext
/// The project the settings are for, if any.
public var project: Project? {
return settingsContext.project
}
/// The target the settings are for, if any.
public var target: Target? {
return settingsContext.target
}
/// The effective configuration for the target, if any. If there is no target, this will be nil. If there is a target, then this will be the configuration specified in the build parameters if there is one, or else the default configuration in the project, if there is one. Or else it will be nil.
public let targetConfiguration: BuildConfiguration?
// FIXME: This probably shouldn't be duplicated among all targets, and could be shared by the project or higher-level context.
//
/// The namespace in which user macros will be registered.
public let userNamespace: MacroNamespace
/// The bound platform, if any.
public let platform: Platform?
/// The bound SDK, if any.
public let sdk: SDK?
/// The bound SDK variant, if any.
public let sdkVariant: SDKVariant?
/// The bound toolchains.
public let toolchains: [Toolchain]
/// The bound sparse SDKs.
public let sparseSDKs: [SDK]
/// The settings table.
///
/// Nothing should have to access this directly once it's been created - in particular nothing should be able to push additional macros onto the table.
fileprivate let table: MacroValueAssignmentTable
/// The bound product type, if appropriate.
public let productType: ProductTypeSpec?
/// The bound package type, if appropriate.
public let packageType: PackageTypeSpec?
/// The computed preferred architecture.
///
/// This is currently only used for indexing but should be used
/// with single-file compile and analyzer as well.
public let preferredArch: String?
/// The set of macro name to export to shell scripts.
public let exportedMacroNames: Set<MacroDeclaration>
/// The set of additional macros to be exported to shell scripts running in native builds.
public let exportedNativeMacroNames: Set<MacroDeclaration>
/// The global evaluation scope.
public let globalScope: MacroEvaluationScope
/// The file path resolver.
public let filePathResolver: FilePathResolver
/// The executable search paths.
public let executableSearchPaths: StackedSearchPath
/// The framework search paths.
public let fallbackFrameworkSearchPaths: StackedSearchPath
/// The library search paths.
public let fallbackLibrarySearchPaths: StackedSearchPath
/// Errors generated during settings construction, to be reported in the build log.
public let errors: OrderedSet<String>
/// Warnings generated during settings construction, to be reported in the build log.
public let warnings: OrderedSet<String>
/// Notes generated during settings construction, to be reported in the build log.
public let notes: OrderedSet<String>
/// Diagnostics generated during settings construction, to be reported in the build log.
/// This is used for diagnostics which need the full API and aren't represented as a single string as in `errors`, `warnings`, and `notes`.
// FIXME: <rdar://70240308> Remove the latter three at some point and introduce convenience methods to emit simple-string diagnostics.
public let diagnostics: OrderedSet<Diagnostic>
/// Target-specific counterpart of `diagnostics`.
public let targetDiagnostics: OrderedSet<Diagnostic>
/// The list of XCConfigs used to construct the settings.
let macroConfigPaths: [Path]
/// The signature of the XCConfigs used to construct the settings.
public let macroConfigSignature: FilesSignature
/// The list of system build rules to use for these settings.
public let systemBuildRules: [(any BuildRuleCondition, any BuildRuleAction)]
public struct SigningSettings: Sendable {
public let inputs: ProvisioningTaskInputs
public struct Identity: Sendable {
/// May be "-" for ad hoc signing.
public let hash: String
public let name: String
}
public let identity: Identity
public struct Profile: Sendable {
public let input: Path
public let output: Path
}
public let profile: Profile?
public struct Entitlements: Sendable {
// Input may be a path (CODE_SIGN_ENTITLEMENTS in the scope) or a dict of merged entitlements in ProvisioningTaskInputs. It's currently handled at task construction, but it might make sense to move it here to share it.
public let output: Path
// DER-encoded equivalent of `output` plist.
public let outputDer: Path
}
public let signedEntitlements: Entitlements?
public let simulatedEntitlements: Entitlements?
public struct LaunchConstraints: Sendable {
public let process: Path?
public let parentProcess: Path?
public let responsibleProcess: Path?
}
public let launchConstraints: LaunchConstraints
public let libraryConstraint: Path?
}
/// The bound signing settings.
public let signingSettings: SigningSettings?
/// The bound deployment target for the deployment target macro defined in the platform.
public let deploymentTarget: Version?
/// The supported platforms of a target, taking into account pre-overrides.
/// For example, this will contain both `iOS` and `macCatalyst` when building for macCatalyst, if the target's SDKROOT was `iphoneos`.
public let supportedBuildVersionPlatforms: Set<BuildVersion.Platform>
public var targetBuildVersionPlatforms: Set<BuildVersion.Platform>? {
targetBuildVersionPlatforms(in: globalScope)
}
public static func supportsMacCatalyst(scope: MacroEvaluationScope, core: Core) -> Bool {
@preconcurrency @PluginExtensionSystemActor func sdkVariantInfoExtensions() -> [any SDKVariantInfoExtensionPoint.ExtensionProtocol] {
core.pluginManager.extensions(of: SDKVariantInfoExtensionPoint.self)
}
var supportsMacCatalystMacros: Set<String> = []
for sdkVariantInfoExtension in sdkVariantInfoExtensions() {
supportsMacCatalystMacros.formUnion(sdkVariantInfoExtension.supportsMacCatalystMacroNames)
}
return supportsMacCatalystMacros.contains { scope.evaluate(scope.namespace.parseString("$(\($0)")).boolValue } ||
// For index build ensure zippered frameworks can be configured separately for both macOS and macCatalyst.
(scope.evaluate(BuiltinMacros.IS_ZIPPERED) && scope.evaluate(BuiltinMacros.INDEX_ENABLE_BUILD_ARENA))
}
public static func supportsCompilationCaching(_ core: Core) -> Bool {
@preconcurrency @PluginExtensionSystemActor func featureAvailabilityExtensions() -> [any FeatureAvailabilityExtensionPoint.ExtensionProtocol] {
core.pluginManager.extensions(of: FeatureAvailabilityExtensionPoint.self)
}
return featureAvailabilityExtensions().contains {
$0.supportsCompilationCaching
}
}
public var enableTargetPlatformSpecialization: Bool {
return Settings.targetPlatformSpecializationEnabled(scope: globalScope)
}
public static func targetPlatformSpecializationEnabled(scope: MacroEvaluationScope) -> Bool {
return scope.evaluate(BuiltinMacros.ALLOW_TARGET_PLATFORM_SPECIALIZATION) ||
SWBFeatureFlag.allowTargetPlatformSpecialization.value
}
public var enableBuildRequestOverrides: Bool {
return Settings.buildRequestOverridesEnabled(scope: globalScope)
}
public static func buildRequestOverridesEnabled(scope: MacroEvaluationScope) -> Bool {
return scope.evaluate(BuiltinMacros.ALLOW_BUILD_REQUEST_OVERRIDES)
}
/// Structure to hold information about the project model components from which a settings object was constructed.
///
/// - remark: The overhead of this object should be very small, because the majority of the actual data are the linked lists of macro definitions, which are shared with the main table in the `Settings` object.
public struct ConstructionComponents: Sendable {
// These properties are the individual tables (and info about them) of specific levels which contributed to the Settings.
/// The path to the project-level xcconfig file.
let projectXcconfigPath: Path?
/// The project-level xcconfig settings table.
let projectXcconfigSettings: MacroValueAssignmentTable?
/// The project-level settings table.
let projectSettings: MacroValueAssignmentTable?
/// The path to the target-level xcconfig file.
let targetXcconfigPath: Path?
/// The target-level xcconfig settings table.
let targetXcconfigSettings: MacroValueAssignmentTable?
/// The target-level settings table.
let targetSettings: MacroValueAssignmentTable?
// These properties are the actual tables of settings up to a certain point, which are used to compute the resolved values of settings at that level in the build settings editor (e.g., in the Levels view).
/// The defaults settings table (basically everything below the project xcconfig settings).
let upToDefaultsSettings: MacroValueAssignmentTable?
/// The settings up to the project-level xcconfig.
let upToProjectXcconfigSettings: MacroValueAssignmentTable?
/// The settings up to the project-level.
let upToProjectSettings: MacroValueAssignmentTable?
/// The settings up to the target-level xcconfig.
let upToTargetXcconfigSettings: MacroValueAssignmentTable?
/// The settings up to the target-level.
let upToTargetSettings: MacroValueAssignmentTable?
}
/// The information about the project model components from which these settings were constructed.
public let constructionComponents: ConstructionComponents
public convenience init(workspaceContext: WorkspaceContext, buildRequestContext: BuildRequestContext, parameters: BuildParameters, project: Project, target: Target? = nil, purpose: SettingsPurpose = .build, provisioningTaskInputs: ProvisioningTaskInputs? = nil, impartedBuildProperties: [ImpartedBuildProperties]? = nil, includeExports: Bool = true, sdkRegistry: (any SDKRegistryLookup)? = nil) {
self.init(workspaceContext: workspaceContext, buildRequestContext: buildRequestContext, parameters: parameters, settingsContext: SettingsContext(purpose, project: project, target: target), purpose: purpose, provisioningTaskInputs: provisioningTaskInputs, impartedBuildProperties: impartedBuildProperties, includeExports: includeExports, sdkRegistry: sdkRegistry)
}
/// Construct the settings for a project and optionally a target.
public init(workspaceContext: WorkspaceContext, buildRequestContext: BuildRequestContext, parameters: BuildParameters, settingsContext: SettingsContext, purpose: SettingsPurpose = .build, provisioningTaskInputs: ProvisioningTaskInputs? = nil, impartedBuildProperties: [ImpartedBuildProperties]? = nil, includeExports: Bool = true, sdkRegistry: (any SDKRegistryLookup)? = nil) {
if let target = settingsContext.target {
precondition(workspaceContext.workspace.project(for: target) === settingsContext.project)
}
self.parameters = parameters
self.settingsContext = settingsContext
// Construct the settings table.
let builder = SettingsBuilder(workspaceContext, buildRequestContext, parameters, settingsContext, provisioningTaskInputs, includeExports: includeExports, sdkRegistry)
let (boundProperties, boundDeploymentTarget) = MacroNamespace.withExpressionInterningEnabled{ builder.construct(impartedBuildProperties) }
// Extract the constructed data.
self.targetConfiguration = builder.targetConfiguration
self.userNamespace = builder.userNamespace
self.platform = boundProperties.platform
self.sdk = boundProperties.sdk
self.sdkVariant = boundProperties.sdkVariant
self.toolchains = boundProperties.toolchains
self.sparseSDKs = boundProperties.sparseSDKs
self.deploymentTarget = boundDeploymentTarget.platformDeploymentTarget
self.table = builder._table
self.productType = builder.productType
self.packageType = builder.packageType
self.preferredArch = builder.preferredArch
self.exportedMacroNames = builder.exportedMacroNames
self.exportedNativeMacroNames = builder.exportedNativeMacroNames
self.macroConfigPaths = builder.macroConfigPaths.elements
self.macroConfigSignature = builder.macroConfigSignature
self.signingSettings = builder.signingSettings
// Create the global evaluation scope. This uses the bound SDK if the SettingsContext's purpose wants that condition.
let globalScope = builder.createScope(sdkToUse: settingsContext.purpose.bindToSDK ? self.sdk : nil)
self.globalScope = globalScope
// Create the file path resolver.
self.filePathResolver = FilePathResolver(scope: globalScope, projectDir: settingsContext.project == nil ? .root : nil)
// Compute the executable search paths.
self.executableSearchPaths = workspaceContext.createExecutableSearchPaths(platform: boundProperties.platform, toolchains: boundProperties.toolchains)
// Compute the fallback framework search paths.
self.fallbackFrameworkSearchPaths = workspaceContext.createFallbackFrameworkSearchPaths(platform: boundProperties.platform, toolchains: boundProperties.toolchains)
// Compute the fallback library search paths.
self.fallbackLibrarySearchPaths = workspaceContext.createFallbackLibrarySearchPaths(platform: boundProperties.platform, toolchains: boundProperties.toolchains)
// Compute the system build rules.
let combineHiDPIImages = globalScope.evaluate(BuiltinMacros.COMBINE_HIDPI_IMAGES)
let systemBuildRules = workspaceContext.core.coreSettings.systemBuildRules(combineHiDPIImages: combineHiDPIImages, platform: platform, scope: globalScope)
self.systemBuildRules = systemBuildRules.rules
self.errors = builder.errors
self.warnings = builder.warnings
self.notes = builder.notes
self.diagnostics = builder.diagnostics.appending(contentsOf: systemBuildRules.diagnostics)
self.targetDiagnostics = builder.targetDiagnostics
func effectiveSupportedPlatforms(sdkRegistry: (any SDKRegistryLookup)?) -> Set<BuildVersion.Platform> {
// Everything in SUPPORTED_PLATFORMS
let supportedPlatforms: [BuildVersion.Platform] = (globalScope.evaluate(BuiltinMacros.SUPPORTED_PLATFORMS).compactMap { try? sdkRegistry?.lookup($0, activeRunDestination: parameters.activeRunDestination) }.compactMap { $0.targetBuildVersionPlatform() })
// macCatalyst, if any of the SUPPORTS_* macros are set
let macCatalyst: [BuildVersion.Platform] = (Settings.supportsMacCatalyst(scope: globalScope, core: workspaceContext.core) ? [.macCatalyst] : [])
// The original SDK before overridden by the run destination
let originalSDK: [BuildVersion.Platform] = boundProperties.preOverrides.sdk?.targetBuildVersionPlatform().map { [$0] } ?? []
// The current SDK, if not otherwise captured for any reason
let currentSDK: [BuildVersion.Platform] = boundProperties.sdk?.targetBuildVersionPlatform(sdkVariant: boundProperties.sdkVariant).map { [$0] } ?? []
return Set(supportedPlatforms + macCatalyst + originalSDK + currentSDK)
}
self.supportedBuildVersionPlatforms = effectiveSupportedPlatforms(sdkRegistry: sdkRegistry)
self.constructionComponents = builder.constructionComponents
}
public var infoForBuildSettingsEditor: BuildSettingsEditorInfoPayload {
// FIXME: Annoyingly this probably needs to have both String and [String] values.
func assignedValues(for table: MacroValueAssignmentTable?) -> [String: String]? {
guard let table else {
return nil
}
var result = [String: String]()
for (settingName, assignment) in table.valueAssignments {
// We walk all of the assignments in the linked list, adding the first one we see of each set of conditions.
var asgn: MacroValueAssignment? = assignment
while let a = asgn {
var settingAndConditions = settingName.name
if let c = a.conditions {
settingAndConditions = settingAndConditions + c.description
}
if result[settingAndConditions] == nil {
result[settingAndConditions] = a.expression.stringRep
}
asgn = a.next
}
}
return result
}
func resolvedValues(for table: MacroValueAssignmentTable?) -> [String: String]? {
guard let table else {
return nil
}
var conditionParameterValues = [MacroConditionParameter: [String]]()
if let targetConfiguration {
conditionParameterValues[BuiltinMacros.configurationCondition] = [targetConfiguration.name]
}
// We don't set any other condition parameters because they would get in the way of showing settings across all condition parameters as the editor wants to do.
let scope = MacroEvaluationScope(table: table, conditionParameterValues: conditionParameterValues)
var result = [String: String]()
for (settingName, assignment) in table.valueAssignments {
// We walk all of the assignments in the linked list, adding the first one we see of each set of conditions.
var asgn: MacroValueAssignment? = assignment
while let a = asgn {
var settingAndConditions = settingName.name
var effectiveScope = scope
if let c = a.conditions {
settingAndConditions = settingAndConditions + c.description
// If we have any conditions in the assignment, then we create a subscope which uses those conditions as the subscope's condition parameters to evaluate the value. Because this is the best information we have to get a resolved value.
for condition in c.conditions.sorted(by: { $0.parameter.name < $1.parameter.name }) {
effectiveScope = effectiveScope.subscope(binding: condition.parameter, to: condition.valuePattern)
}
}
if result[settingAndConditions] == nil {
// This is a bit unintuitive: We don't want to evaluate the setting itself here, because that won't work right in the case of conditions. Instead we evaluate the value assignment's expression.
// This is extra-tricky because we want to evaluate it as a string, but the expression may be a string-list, and MacroEvaluationScope doesn't provide a generic method to evaluate a MacroExpression.
result[settingAndConditions] = evaluateAsString(a, macro: settingName, scope: effectiveScope)
}
asgn = a.next
}
}
return result
}
return BuildSettingsEditorInfoPayload(
// Assigned values
targetSettingAssignments: assignedValues(for: constructionComponents.targetSettings),
targetXcconfigSettingAssignments: assignedValues(for: constructionComponents.targetXcconfigSettings),
projectSettingAssignments: assignedValues(for: constructionComponents.projectSettings),
projectXcconfigSettingAssignments: assignedValues(for: constructionComponents.projectXcconfigSettings),
// Resolved values
targetResolvedSettingsValues: resolvedValues(for: constructionComponents.upToTargetSettings),
targetXcconfigResolvedSettingsValues: resolvedValues(for: constructionComponents.upToTargetXcconfigSettings),
projectResolvedSettingsValues: resolvedValues(for: constructionComponents.upToProjectSettings),
projectXcconfigResolvedSettingsValues: resolvedValues(for: constructionComponents.upToProjectXcconfigSettings),
defaultsResolvedSettingsValues: resolvedValues(for: constructionComponents.upToDefaultsSettings)
)
}
}
extension WorkspaceContext {
@_spi(Testing) public func createExecutableSearchPaths(platform: Platform?, toolchains: [Toolchain]) -> StackedSearchPath {
workspaceSettingsCache.getCachedStackedSearchPath(context: #function, platform: platform, toolchains: toolchains) { platform, toolchains in
var paths = OrderedSet<Path>()
// Add from __XCODE_BUILT_PRODUCTS_DIR_PATHS, if present.
if let value = userInfo?.buildSystemEnvironment["__XCODE_BUILT_PRODUCTS_DIR_PATHS"] {
for item in value.split(separator: ":") {
// Only honor absolute paths.
let path = Path(item)
if path.isAbsolute {
paths.append(path)