forked from swiftlang/swift-build
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSwiftCompiler.swift
More file actions
3706 lines (3218 loc) · 199 KB
/
Copy pathSwiftCompiler.swift
File metadata and controls
3706 lines (3218 loc) · 199 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift open source project
//
// Copyright (c) 2025 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
import class Foundation.ProcessInfo
import class Foundation.JSONEncoder
import struct Foundation.Data
import SWBLibc
public import SWBProtocol
public import SWBUtil
public import struct SWBProtocol.TargetDescription
public import enum SWBProtocol.BuildAction
import Foundation
public import SWBMacro
#if canImport(Darwin) && canImport(os.log)
// For Previews logging
import os.log
#endif
/// The minimal data we need to serialize to reconstruct `SwiftSourceFileIndexingInfo` from `generateIndexingInfoForTask`
public struct SwiftIndexingPayload: Serializable, Sendable {
// If `USE_SWIFT_RESPONSE_FILE` is enabled, we use `filePaths`, otherwise `range`.
// This is very unfortunate and will be removed in rdar://53000820
public enum Inputs: Encodable, Sendable {
case filePaths(Path, [Path])
case range(Range<Int>)
}
private enum InputsCode: Int, Serializable {
case filePaths = 0
case range = 1
}
public let inputs: Inputs
public let inputReplacements: [Path: Path]
public let builtProductsDir: Path
public let assetSymbolIndexPath: Path
public let objectFileDir: Path
public let toolchains: [String]
init(inputs: Inputs, inputReplacements: [Path: Path], builtProductsDir: Path, assetSymbolIndexPath: Path, objectFileDir: Path, toolchains: [String]) {
self.inputs = inputs
self.inputReplacements = inputReplacements
self.builtProductsDir = builtProductsDir
self.assetSymbolIndexPath = assetSymbolIndexPath
self.objectFileDir = objectFileDir
self.toolchains = toolchains
}
public func serialize<T: Serializer>(to serializer: T) {
serializer.serializeAggregate(7) {
switch inputs {
case let .filePaths(responseFilePath, inputFiles):
serializer.serialize(InputsCode.filePaths)
serializer.serializeAggregate(2) {
serializer.serialize(responseFilePath)
serializer.serialize(inputFiles)
}
case let .range(range):
serializer.serialize(InputsCode.range)
serializer.serialize(range)
}
serializer.serialize(inputReplacements)
serializer.serialize(builtProductsDir)
serializer.serialize(assetSymbolIndexPath)
serializer.serialize(objectFileDir)
serializer.serialize(toolchains)
}
}
public init(from deserializer: any Deserializer) throws {
try deserializer.beginAggregate(7)
switch try deserializer.deserialize() as InputsCode {
case .filePaths:
try deserializer.beginAggregate(2)
self.inputs = try .filePaths(deserializer.deserialize(), deserializer.deserialize())
case .range:
self.inputs = .range(try deserializer.deserialize())
}
self.inputReplacements = try deserializer.deserialize()
self.builtProductsDir = try deserializer.deserialize()
self.assetSymbolIndexPath = try deserializer.deserialize()
self.objectFileDir = try deserializer.deserialize()
self.toolchains = try deserializer.deserialize()
}
}
/// The indexing info for a file being compiled by swiftc. This will be sent to the client in a property list format described below.
public struct SwiftSourceFileIndexingInfo: SourceFileIndexingInfo {
@_spi(Testing) public let commandLine: [ByteString]
let builtProductsDir: Path
let assetSymbolIndexPath: Path
let toolchains: [String]
public let outputFile: Path
public var compilerArguments: [String]? {
var result = commandLine.map { $0.asString }
// commandLine does not contain the `-index-unit-output-path` but we want to return it from the
// `IndexBuildSettingsRequest`, so add it.
if !result.contains(where: { $0 == "-o" || $0 == "-index-unit-output-path" }), let indexOutputFile {
result += ["-index-unit-output-path", indexOutputFile]
}
return result
}
public var indexOutputFile: String? { outputFile.str }
public var language: IndexingInfoLanguage? { .swift }
public init(task: any ExecutableTask, payload: SwiftIndexingPayload, outputFile: Path, enableIndexBuildArena: Bool, integratedDriver: Bool) {
self.commandLine = Self.indexingCommandLine(commandLine: task.commandLine.map(\.asByteString), payload: payload, enableIndexBuildArena: enableIndexBuildArena, integratedDriver: integratedDriver)
self.builtProductsDir = payload.builtProductsDir
self.assetSymbolIndexPath = payload.assetSymbolIndexPath
self.toolchains = payload.toolchains
self.outputFile = outputFile
}
// Arguments to skip for background indexing/AST building. This could be
// to save computing them when it's not necessary, to avoid additional
// outputs, or just because they don't make sense in the context of
// indexing (eg. skipping all function bodies).
//
// TODO: It's pretty brittle relying on this to exclude supplementary
// outputs, the driver ought to provide an easier way of doing that, either
// through a dedicated indexing mode (which it sort of already has, as it
// recognizes '-index-file' as a primary output), or a more generic
// "only give me the primary output and nothing else" mode.
private static let removeFlags: Set<ByteString> = [
"-emit-dependencies",
"-serialize-diagnostics",
"-incremental",
"-incremental-dependency-scan",
"-parseable-output",
"-use-frontend-parseable-output",
"-whole-module-optimization",
"-save-temps",
"-no-color-diagnostics",
"-color-diagnostics",
"-disable-cmo",
"-validate-clang-modules-once",
"-emit-module",
"-emit-module-interface",
"-emit-objc-header",
"-lto=llvm-thin",
"-lto=llvm-full"
]
private static let removeArgs: Set<ByteString> = [
"-o",
"-output-file-map",
"-clang-build-session-file",
"-num-threads",
"-emit-module-path",
"-emit-module-interface-path",
"-emit-private-module-interface-path",
"-emit-package-module-interface-path",
"-emit-objc-header-path"
]
private static let removeFrontendFlags: Set<ByteString> = [
"-experimental-skip-non-inlinable-function-bodies",
"-experimental-skip-all-function-bodies"
]
private static let removeFrontendArgs: Set<ByteString> = [
"-const-gather-protocols-file"
]
// SourceKit uses the old driver to determine the frontend args. Remove all
// new driver flags as a workaround for cases were corresponding no-op
// flags weren't added to the old driver. This shouldn't be required and
// can be removed after we use the new driver instead (rdar://75851402).
private static let newDriverFlags: Set<ByteString> = [
"-driver-print-graphviz",
"-incremental-dependency-scan",
"-explicit-module-build",
"-experimental-explicit-module-build",
"-nonlib-dependency-scanner",
"-driver-warn-unused-options",
"-experimental-emit-module-separately",
"-emit-module-separately-wmo",
"-no-emit-module-separately-wmo",
"-use-frontend-parseable-output",
"-emit-digester-baseline"]
private static let newDriverArgs: Set<ByteString> = [
"-emit-module-serialize-diagnostics-path",
"-dependency-scan-serialize-diagnostics-path",
"-emit-module-dependencies-path",
"-emit-digester-baseline-path",
"-compare-to-baseline-path",
"-serialize-breaking-changes-path",
"-digester-breakage-allowlist-path",
"-digester-mode",
"-const-gather-protocols-list"]
private static func indexingCommandLine(commandLine: [ByteString], payload: SwiftIndexingPayload, enableIndexBuildArena: Bool, integratedDriver: Bool) -> [ByteString] {
precondition(!commandLine.isEmpty)
var result: [ByteString] = []
var index = 0
if integratedDriver {
index = commandLine.firstIndex(of: "--") ?? commandLine.endIndex
index += 1
}
// Skip the compiler path
index += 1
while index < commandLine.count {
let arg = commandLine[index]
index += 1
// Skip unwanted single flags
guard !removeFlags.contains(arg), !newDriverFlags.contains(arg) else {
continue
}
// Skip unwanted flags and their argument
guard !removeArgs.contains(arg), !newDriverArgs.contains(arg) else {
index += 1
continue
}
if let nextArg = commandLine[safe: index] {
// Remove frontend args (including the -Xfrontend)
if removeFrontendFlags.contains(nextArg) {
index += 1
continue
}
if arg == "-Xfrontend", removeFrontendArgs.contains(nextArg), commandLine[safe: index + 1] == "-Xfrontend" {
index += 3
continue
}
// <rdar://problem/23297285> Swift tests are not being discovered, XCTest framework from the project fails to import correctly
if !enableIndexBuildArena, UserDefaults.enableFixFor23297285,
arg == "-I" || arg == "-F" {
result.append(contentsOf: ["-Xcc", arg, "-Xcc", nextArg])
}
}
switch payload.inputs {
case let .filePaths(responseFilePath, paths):
// Replace file lists with all files
if arg == ByteString(encodingAsUTF8: "@" + responseFilePath.str) {
for input in paths {
let pathToAdd = payload.inputReplacements[input] ?? input
result.append(ByteString(encodingAsUTF8: pathToAdd.str))
}
continue
}
case .range(_):
if let pathToAdd = payload.inputReplacements[Path(arg.asString)] {
result.append(ByteString(encodingAsUTF8: pathToAdd.str))
continue
}
}
result.append(arg)
}
if !enableIndexBuildArena {
// Add the supplemental C compiler options in the legacy case.
let clangArgs = ClangCompilerSpec.supplementalIndexingArgs(allowCompilerErrors: false)
result += clangArgs.flatMap { ["-Xcc", ByteString(encodingAsUTF8: $0)] }
}
return result
}
/// The indexing info is packaged and sent to the client in the property list format defined here.
public var propertyListItem: PropertyListItem {
var dict = [String: PropertyListItem]()
// FIXME: Convert to bytes.
dict["LanguageDialect"] = PropertyListItem("swift")
// FIXME: Convert to bytes.
dict["swiftASTCommandArguments"] = PropertyListItem(commandLine.map{ $0.asString })
dict["swiftASTBuiltProductsDir"] = PropertyListItem(builtProductsDir.str)
dict["assetSymbolIndexPath"] = PropertyListItem(assetSymbolIndexPath.str)
dict["toolchains"] = PropertyListItem(toolchains)
func getopt(_ key: ByteString) -> ByteString? {
guard let argIndex = commandLine.firstIndex(of: key) else { return nil }
let valueIndex = commandLine.index(after: argIndex)
guard valueIndex < commandLine.endIndex else { return nil }
return commandLine[valueIndex]
}
guard let moduleName = getopt("-module-name")?.asString else { preconditionFailure("Expected to have -module-name in: \(commandLine.map{$0.asString})") }
dict["swiftASTModuleName"] = PropertyListItem(moduleName)
dict["outputFilePath"] = PropertyListItem(outputFile.str)
return .plDict(dict)
}
}
/// The minimal data we need to serialize to reconstruct `generatePreviewInfo`
public struct SwiftPreviewPayload: Serializable, Encodable, Sendable {
public let architecture: String
public let buildVariant: String
public let objectFileDir: Path
public let moduleCacheDir: Path
init(architecture: String, buildVariant: String, objectFileDir: Path, moduleCacheDir: Path) {
self.architecture = architecture
self.buildVariant = buildVariant
self.objectFileDir = objectFileDir
self.moduleCacheDir = moduleCacheDir
}
public func serialize<T: Serializer>(to serializer: T) {
serializer.serializeAggregate(4) {
serializer.serialize(architecture)
serializer.serialize(buildVariant)
serializer.serialize(objectFileDir)
serializer.serialize(moduleCacheDir)
}
}
public init(from deserializer: any Deserializer) throws {
try deserializer.beginAggregate(4)
self.architecture = try deserializer.deserialize()
self.buildVariant = try deserializer.deserialize()
self.objectFileDir = try deserializer.deserialize()
self.moduleCacheDir = try deserializer.deserialize()
}
}
/// The minimal data we need to serialize to reconstruct `generateLocalizationInfo`
public struct SwiftLocalizationPayload: Serializable, Sendable {
public let effectivePlatformName: String
public let buildVariant: String
public let architecture: String
init(effectivePlatformName: String, buildVariant: String, architecture: String) {
self.effectivePlatformName = effectivePlatformName
self.buildVariant = buildVariant
self.architecture = architecture
}
public func serialize<T>(to serializer: T) where T : Serializer {
serializer.serializeAggregate(3) {
serializer.serialize(effectivePlatformName)
serializer.serialize(buildVariant)
serializer.serialize(architecture)
}
}
public init(from deserializer: any Deserializer) throws {
try deserializer.beginAggregate(3)
self.effectivePlatformName = try deserializer.deserialize()
self.buildVariant = try deserializer.deserialize()
self.architecture = try deserializer.deserialize()
}
}
public struct SwiftDriverPayload: Serializable, TaskPayload, Encodable {
public let uniqueID: String
public let compilerLocation: LibSwiftDriver.CompilerLocation
public let moduleName: String
public let outputPrefix: String
public let tempDirPath: Path
public let explicitModulesTempDirPath: Path
public let variant: String
public let architecture: String
public let cohortArchitectures: [String]
public let eagerCompilationEnabled: Bool
public let explicitModulesEnabled: Bool
public let commandLine: [String]
public let ruleInfo: [String]
public let isUsingWholeModuleOptimization: Bool
public let casOptions: CASOptions?
public let reportRequiredTargetDependencies: BooleanWarningLevel
public let linkerResponseFilePath: Path?
public let linkerResponseFileFormat: ResponseFileFormat
public let dependencyFilteringRootPath: Path?
public let verifyScannerDependencies: Bool
public let scannerDiagnosticsOutputPath: Path?
public let diagnosticAttachmentInfo: LibclangDiagnosticAttachmentInfo?
internal init(uniqueID: String, compilerLocation: LibSwiftDriver.CompilerLocation, moduleName: String, outputPrefix: String, tempDirPath: Path, explicitModulesTempDirPath: Path, variant: String, architecture: String, cohortArchitectures: [String], eagerCompilationEnabled: Bool, explicitModulesEnabled: Bool, commandLine: [String], ruleInfo: [String], isUsingWholeModuleOptimization: Bool, casOptions: CASOptions?, reportRequiredTargetDependencies: BooleanWarningLevel, linkerResponseFilePath: Path?, linkerResponseFileFormat: ResponseFileFormat, dependencyFilteringRootPath: Path?, verifyScannerDependencies: Bool, scannerDiagnosticsOutputPath: Path?, diagnosticAttachmentInfo: LibclangDiagnosticAttachmentInfo?) {
self.uniqueID = uniqueID
self.compilerLocation = compilerLocation
self.moduleName = moduleName
self.outputPrefix = outputPrefix
self.tempDirPath = tempDirPath
self.explicitModulesTempDirPath = explicitModulesTempDirPath
self.variant = variant
self.architecture = architecture
self.cohortArchitectures = cohortArchitectures
self.eagerCompilationEnabled = eagerCompilationEnabled
self.explicitModulesEnabled = explicitModulesEnabled
self.commandLine = commandLine
self.ruleInfo = ruleInfo
self.isUsingWholeModuleOptimization = isUsingWholeModuleOptimization
self.casOptions = casOptions
self.reportRequiredTargetDependencies = reportRequiredTargetDependencies
self.linkerResponseFilePath = linkerResponseFilePath
self.linkerResponseFileFormat = linkerResponseFileFormat
self.dependencyFilteringRootPath = dependencyFilteringRootPath
self.verifyScannerDependencies = verifyScannerDependencies
self.scannerDiagnosticsOutputPath = scannerDiagnosticsOutputPath
self.diagnosticAttachmentInfo = diagnosticAttachmentInfo
}
public init(from deserializer: any Deserializer) throws {
try deserializer.beginAggregate(22)
self.uniqueID = try deserializer.deserialize()
self.compilerLocation = try deserializer.deserialize()
self.moduleName = try deserializer.deserialize()
self.outputPrefix = try deserializer.deserialize()
self.tempDirPath = try deserializer.deserialize()
self.explicitModulesTempDirPath = try deserializer.deserialize()
self.variant = try deserializer.deserialize()
self.architecture = try deserializer.deserialize()
self.cohortArchitectures = try deserializer.deserialize()
self.eagerCompilationEnabled = try deserializer.deserialize()
self.explicitModulesEnabled = try deserializer.deserialize()
self.commandLine = try deserializer.deserialize()
self.ruleInfo = try deserializer.deserialize()
self.isUsingWholeModuleOptimization = try deserializer.deserialize()
self.casOptions = try deserializer.deserialize()
self.reportRequiredTargetDependencies = try deserializer.deserialize()
self.linkerResponseFilePath = try deserializer.deserialize()
self.linkerResponseFileFormat = try deserializer.deserialize()
self.dependencyFilteringRootPath = try deserializer.deserialize()
self.verifyScannerDependencies = try deserializer.deserialize()
self.scannerDiagnosticsOutputPath = try deserializer.deserialize()
self.diagnosticAttachmentInfo = try deserializer.deserialize()
}
public func serialize<T>(to serializer: T) where T : Serializer {
serializer.serializeAggregate(22) {
serializer.serialize(self.uniqueID)
serializer.serialize(self.compilerLocation)
serializer.serialize(self.moduleName)
serializer.serialize(self.outputPrefix)
serializer.serialize(self.tempDirPath)
serializer.serialize(self.explicitModulesTempDirPath)
serializer.serialize(self.variant)
serializer.serialize(self.architecture)
serializer.serialize(self.cohortArchitectures)
serializer.serialize(self.eagerCompilationEnabled)
serializer.serialize(self.explicitModulesEnabled)
serializer.serialize(self.commandLine)
serializer.serialize(self.ruleInfo)
serializer.serialize(self.isUsingWholeModuleOptimization)
serializer.serialize(self.casOptions)
serializer.serialize(self.reportRequiredTargetDependencies)
serializer.serialize(self.linkerResponseFilePath)
serializer.serialize(self.linkerResponseFileFormat)
serializer.serialize(self.dependencyFilteringRootPath)
serializer.serialize(self.verifyScannerDependencies)
serializer.serialize(self.scannerDiagnosticsOutputPath)
serializer.serialize(self.diagnosticAttachmentInfo)
}
}
}
public protocol ParentTaskPayload: TaskPayload {
var numExpectedCompileSubtasks: Int { get }
}
/// Payload information for Swift tasks.
public struct SwiftTaskPayload: ParentTaskPayload {
public let moduleName: String
/// The indexing specific information.
public let indexingPayload: SwiftIndexingPayload
/// The preview specific information.
public let previewPayload: SwiftPreviewPayload?
/// Localization-specific information (about extracted .stringsdata).
public let localizationPayload: SwiftLocalizationPayload?
/// The expected number of compile subtasks that will be spawned by the Swift compiler.
public let numExpectedCompileSubtasks: Int
/// Extra payload for the swift driver invocation
public let driverPayload: SwiftDriverPayload?
/// The preview build style in effect (dynamic replacement or XOJIT), if any.
public let previewStyle: PreviewStyleMessagePayload?
init(moduleName: String, indexingPayload: SwiftIndexingPayload, previewPayload: SwiftPreviewPayload?, localizationPayload: SwiftLocalizationPayload?, numExpectedCompileSubtasks: Int, driverPayload: SwiftDriverPayload?, previewStyle: PreviewStyle?) {
self.moduleName = moduleName
self.indexingPayload = indexingPayload
self.previewPayload = previewPayload
self.localizationPayload = localizationPayload
self.numExpectedCompileSubtasks = numExpectedCompileSubtasks
self.driverPayload = driverPayload
switch previewStyle {
case .dynamicReplacement:
self.previewStyle = .dynamicReplacement
case .xojit:
self.previewStyle = .xojit
case nil:
self.previewStyle = nil
}
}
public func serialize<T: Serializer>(to serializer: T) {
serializer.serializeAggregate(7) {
serializer.serialize(moduleName)
serializer.serialize(indexingPayload)
serializer.serialize(previewPayload)
serializer.serialize(localizationPayload)
serializer.serialize(numExpectedCompileSubtasks)
serializer.serialize(driverPayload)
serializer.serialize(previewStyle)
}
}
public init(from deserializer: any Deserializer) throws {
try deserializer.beginAggregate(7)
self.moduleName = try deserializer.deserialize()
self.indexingPayload = try deserializer.deserialize()
self.previewPayload = try deserializer.deserialize()
self.localizationPayload = try deserializer.deserialize()
self.numExpectedCompileSubtasks = try deserializer.deserialize()
self.driverPayload = try deserializer.deserialize()
self.previewStyle = try deserializer.deserialize()
}
}
public struct SwiftBlocklists: Sendable {
public struct ExplicitModulesInfo : ProjectFailuresBlockList, Codable, Sendable {
let KnownFailures: [String]
enum CodingKeys: String, CodingKey {
case KnownFailures
}
}
var explicitModules: ExplicitModulesInfo? = nil
public struct InstallAPILazyTypecheckInfo : Codable, Sendable {
/// A blocklist of module names that do not support the `SWIFT_INSTALLAPI_LAZY_TYPECHECK` build setting.
let Modules: [String]
}
var installAPILazyTypecheck: InstallAPILazyTypecheckInfo? = nil
public struct CachingBlockList : ProjectFailuresBlockList, Codable, Sendable {
let KnownFailures: [String]
/// A blocklist of module names that do not support the `SWIFT_ENABLE_COMPILE_CACHE` build setting.
let Modules: [String]
}
var caching: CachingBlockList? = nil
public struct LanguageFeatureEnablementInfo : Codable, Sendable {
public struct Feature: Codable, Sendable {
public enum DiagnosticLevel: String, Codable, Sendable {
case ignore
case warn
case error
}
/// The level of the diagnostic to emit when the feature is disabled.
let level: DiagnosticLevel
/// The names of build settings to check. If any of these build settings are enabled, then the feature is considered enabled.
let buildSettings: [String]?
/// A URL that developers can go to to learn more about why the feature should be enabled.
let learnMoreURL: URL?
/// Whether or not the feature is experimental (as opposed to an upcoming, official language feature).
let experimental: Bool?
/// A list of module names that should not receive the diagnostic.
let moduleExceptions: [String]?
}
let features: [String: Feature]
}
var languageFeatureEnablement: LanguageFeatureEnablementInfo? = nil
public init() {}
}
public struct DiscoveredSwiftCompilerToolSpecInfo: DiscoveredCommandLineToolSpecInfo {
/// The path to the tool from which we captured this info.
public let toolPath: Path
/// The version of the Swift language in the tool.
public let swiftVersion: Version
/// The name that this Swift was tagged with.
public let swiftTag: String
/// The version of the stable ABI for the Swift language in the tool.
public let swiftABIVersion: String?
/// `compilerClientsConfig` blocklists for Swift
public let blocklists: SwiftBlocklists
public var toolVersion: Version? { return self.swiftVersion }
public var hostLibraryDirectory: Path {
toolPath.dirname.dirname.join("lib/swift/host")
}
public enum FeatureFlag: String, CaseIterable, Sendable {
case experimentalSkipAllFunctionBodies = "experimental-skip-all-function-bodies"
case experimentalAllowModuleWithCompilerErrors = "experimental-allow-module-with-compiler-errors"
case emitLocalizedStrings = "emit-localized-strings"
case libraryLevel = "library-level"
case packageName = "package-name-if-supported"
case vfsDirectoryRemap = "vfs-directory-remap"
case indexUnitOutputPath = "index-unit-output-path"
case indexUnitOutputPathWithoutWarning = "no-warn-superfluous-index-unit-path"
case emitABIDescriptor = "emit-abi-descriptor"
case emptyABIDescriptor = "empty-abi-descriptor"
case clangVfsRedirectingWith = "clang-vfs-redirecting-with"
case emitContValuesSidecar = "emit-const-value-sidecar"
case vfsstatcache = "clang-vfsstatcache"
case emitExtensionBlockSymbols = "emit-extension-block-symbols"
case constExtractCompleteMetadata = "const-extract-complete-metadata"
case emitPackageModuleInterfacePath = "emit-package-module-interface-path"
case compilationCaching = "compilation-caching"
case Isystem = "Isystem"
case apiDigesterXcc = "api-digester-Xcc"
case debugInfoExplicitDependency = "debug-info-explicit-dependency"
}
public var toolFeatures: ToolFeatures<FeatureFlag>
public func hasFeature(_ flag: String) -> Bool {
return toolFeatures.has(flag)
}
public init(toolPath: Path, swiftVersion: Version, swiftTag: String, swiftABIVersion: String?, blocklists: SwiftBlocklists, toolFeatures: ToolFeatures<DiscoveredSwiftCompilerToolSpecInfo.FeatureFlag>) {
self.toolPath = toolPath
self.swiftVersion = swiftVersion
self.swiftTag = swiftTag
self.swiftABIVersion = swiftABIVersion
self.blocklists = blocklists
self.toolFeatures = toolFeatures
}
}
public struct SwiftMacroImplementationDescriptor: Hashable, Comparable, Sendable {
private let value: String
public let path: Path
// The flag passed to the compiler to load the macro implementation.
public var compilerFlags: [String] {
["-Xfrontend", "-load-plugin-executable", "-Xfrontend", value]
}
public init(declaringModuleNames: [String], path: Path) {
self.value = "\(path.str)#\(declaringModuleNames.joined(separator: ","))"
self.path = path
}
public init?(value: String) {
self.value = value
guard let endOfPath = value.lastIndex(of: "#") else {
return nil
}
self.path = Path(value[..<endOfPath])
}
public static func < (lhs: SwiftMacroImplementationDescriptor, rhs: SwiftMacroImplementationDescriptor) -> Bool {
return lhs.value < rhs.value
}
}
public final class SwiftCompilerSpec : CompilerSpec, SpecIdentifierType, SwiftDiscoveredCommandLineToolSpecInfo, @unchecked Sendable {
@_spi(Testing) public static let parallelismLevel = ProcessInfo.processInfo.activeProcessorCount
public static let identifier = "com.apple.xcode.tools.swift.compiler"
/// The name of a source file which the Swift compiler will recognize in order implicitly lift its content into an automatically-generated `main()` function.
static let mainFileName = "main.swift"
public override var supportsInstallAPI: Bool {
return true
}
fileprivate func getABIBaselinePath(_ scope: MacroEvaluationScope, _ delegate: any TaskGenerationDelegate,
_ mode: SwiftCompilationMode) -> Path? {
switch mode {
case .api, .prepareForIndex:
return nil
case .generateModule, .compile:
guard scope.evaluate(BuiltinMacros.RUN_SWIFT_ABI_CHECKER_TOOL_DRIVER) else {
return nil
}
let baselineDir = scope.evaluate(BuiltinMacros.SWIFT_ABI_CHECKER_BASELINE_DIR)
let fileName = mode.destinationModuleFileName(scope)
if !baselineDir.isEmpty {
let path1 = Path(baselineDir).join(Path("\(fileName).abi.json"))
if delegate.fileExists(at: path1) {
return path1
}
let path2 = Path(baselineDir).join("ABI").join(Path("\(fileName).json"))
if delegate.fileExists(at: path2) {
return path2
}
delegate.warning("cannot find Swift ABI baseline file at: `\(path1.str)` or `\(path2.str)`")
}
return nil
}
}
/// Indicates whether a Swift version is considered invalid by the spec, valid-as-is, or if only the major version component is valid.
public enum SwiftVersionState {
/// The Swift version is valid exactly as it is.
case valid
/// Only the Swift major version is valid.
case validMajor
/// The Swift version is invalid.
case invalid
}
static let outputAgnosticCompilerArgumentsWithValues = Set<ByteString>([
"-index-store-path",
"-index-unit-output-path",
])
static let outputAgnosticJoinedCompilerArgumentsWithValues = Set<ByteString>([
"-diagnostic-style",
])
static func isOutputAgnosticCommandLineArgument(_ argument: ByteString, prevArgument: ByteString?) -> Bool {
if SwiftCompilerSpec.outputAgnosticCompilerArgumentsWithValues.contains(argument) {
return true
}
if let prevArgument, SwiftCompilerSpec.outputAgnosticCompilerArgumentsWithValues.contains(prevArgument) {
return true
}
guard let argumentPrefixString = argument.split(separator: UInt8(ascii: "=")).first else {
return false
}
let argumentPrefix = ByteString(argumentPrefixString)
if SwiftCompilerSpec.outputAgnosticJoinedCompilerArgumentsWithValues.contains(argumentPrefix) {
return true
}
return false
}
public override func commandLineForSignature(for task: any ExecutableTask) -> [ByteString] {
// TODO: We should probably allow the specs themselves to mark options
// as output agnostic, rather than always postprocessing the command
// line. In some cases we will have to postprocess, because of settings
// like OTHER_SWIFT_FLAGS where the user can't possibly add this
// metadata to the values, but those settings be handled on a
// case-by-case basis.
let taskCommandLine = task.commandLine
return taskCommandLine.indices.compactMap { index in
let arg = taskCommandLine[index].asByteString
let prevArg = index > taskCommandLine.startIndex ? taskCommandLine[index - 1].asByteString : nil
if SwiftCompilerSpec.isOutputAgnosticCommandLineArgument(arg, prevArgument: prevArg) {
return nil
}
return arg
}
}
override public func environmentFromSpec(_ cbc: CommandBuildContext, _ delegate: any DiagnosticProducingDelegate, lookup: ((MacroDeclaration) -> MacroExpression?)? = nil) -> [(String, String)] {
var env: [(String, String)] = super.environmentFromSpec(cbc, delegate, lookup: lookup)
// Pass through SWIFT_DRIVER_SWIFT_FRONTEND_EXEC if set
// This is consumed by the driver to select which swift-frontend binary to use.
let frontendExecValue = cbc.scope.evaluate(cbc.scope.namespace.parseString("$(SWIFT_DRIVER_SWIFT_FRONTEND_EXEC)"))
if !frontendExecValue.isEmpty {
env.append(("SWIFT_DRIVER_SWIFT_FRONTEND_EXEC", frontendExecValue))
}
return env
}
// remove in rdar://53000820
/// Describes how input files are passed to the compiler invocation
private enum SwiftCompilerInputMode {
case responseFile(Path)
case individualFiles
}
/// Enum to determine the mode in which to run the compiler.
enum SwiftCompilationMode {
case compile
case api
case generateModule(triplePlatform: String, tripleSuffix: String, moduleOnly: Bool)
case prepareForIndex
/// Returns the rule info name to use for this mode.
var compileSources: Bool {
switch self {
case .compile:
return true
default:
return false
}
}
/// Returns the string to use as the first item in the ruleInfo when using the binary driver flow
var ruleName: String {
switch self {
case .generateModule, .prepareForIndex:
return "GenerateSwiftModule"
default:
return "CompileSwiftSources"
}
}
/// Returns the string to use as the first item in the ruleInfo when using the integrated driver flow
var ruleNameIntegratedDriver: String {
switch self {
case .generateModule, .prepareForIndex:
return "SwiftDriver GenerateModule"
default:
return "SwiftDriver"
}
}
/// The suffix to apply to the module basename for this mode.
var moduleBaseNameSuffix: String {
switch self {
case .generateModule(let triplePlatform, let tripleSuffix, _):
return "-\(triplePlatform)\(tripleSuffix)"
default:
return ""
}
}
/// Returns true if this mode will generate the ObjC bridging header.
var emitObjCHeader: Bool {
switch self {
case .generateModule(_, _, let moduleOnly):
return moduleOnly
default:
return true
}
}
/// Returns true if we must avoid passing `-index-store-path` to the task.
var omitIndexStorePath: Bool {
switch self {
case .generateModule, .prepareForIndex:
return true
default:
return false
}
}
/// Returns true if this mode will generate the .swiftdoc file.
var generateDocumentation: Bool {
switch self {
case .api:
return false
default:
return true
}
}
var canEmitABIDescriptor: Bool {
switch self {
case .compile, .generateModule:
return true
case .prepareForIndex, .api:
return false
}
}
/// Returns the destination module file basename for the mode.
func destinationModuleFileName(_ scope: MacroEvaluationScope) -> String {
let mode = self
let lookup: ((MacroDeclaration) -> MacroExpression?) = { macro in
switch (macro, mode) {
case (BuiltinMacros.SWIFT_PLATFORM_TARGET_PREFIX, .generateModule(let triplePlatform, _, _)):
return scope.namespace.parseLiteralString(triplePlatform)
case (BuiltinMacros.LLVM_TARGET_TRIPLE_SUFFIX, .generateModule(_, let tripleSuffix, _)):
return scope.namespace.parseLiteralString(tripleSuffix)
case (BuiltinMacros.SWIFT_DEPLOYMENT_TARGET, _):
return Static { scope.namespace.parseString("") } as MacroStringExpression
default:
return nil
}
}
return scope.evaluate(BuiltinMacros.SWIFT_TARGET_TRIPLE, lookup: lookup)
}
/// Returns true if the compilation mode supports emitting modules early to unblock downstream targets
func supportsEagerCompilation(isUsingWholeModuleOptimization: Bool) -> Bool {
switch self {
case .compile:
return true
case .generateModule:
return !isUsingWholeModuleOptimization
default:
return false
}
}
var installAPI: Bool {
guard case .api = self else { return false }
return true
}
}
/// Validates the given `swiftVersion` against the Swift spec, indicating whether it is invalid, valid-as-is, or if only the major version is valid.
public func validateSwiftVersion(_ swiftVersion: Version) -> SwiftVersionState {
if supportedLanguageVersions.contains(swiftVersion) {
return .valid
} else {
let majorSwiftVersion = Version(swiftVersion[0], 0, 0)
if supportedLanguageVersions.contains(majorSwiftVersion) {
return .validMajor
} else {
return .invalid
}
}
}
private func supportConstSupplementaryMetadata(_ cbc: CommandBuildContext, _ delegate: any TaskGenerationDelegate, compilationMode: SwiftCompilationMode) async -> Bool {
guard compilationMode.compileSources else {
return false
}
return cbc.scope.evaluate(BuiltinMacros.SWIFT_ENABLE_EMIT_CONST_VALUES)
}
static func getSwiftModuleFilePathInternal(_ scope: MacroEvaluationScope, _ mode: SwiftCompilationMode) -> Path {
let moduleFileDir = scope.evaluate(BuiltinMacros.PER_ARCH_MODULE_FILE_DIR)
let moduleName = scope.evaluate(BuiltinMacros.SWIFT_MODULE_NAME)
return moduleFileDir.join(moduleName + ".swiftmodule").appendingFileNameSuffix(mode.moduleBaseNameSuffix)
}
static public func getSwiftModuleFilePath(_ scope: MacroEvaluationScope) -> Path {
return SwiftCompilerSpec.getSwiftModuleFilePathInternal(scope, .compile)
}
static public func collectInputSearchPaths(_ cbc: CommandBuildContext, toolInfo: DiscoveredSwiftCompilerToolSpecInfo) -> [String] {
var results: [String] = []
// For SWIFT_INCLUDE_PATHS.
results.append(contentsOf: cbc.producer.expandedSearchPaths(for: BuiltinMacros.SWIFT_INCLUDE_PATHS, scope: cbc.scope))
// For PRODUCT_TYPE_SWIFT_INCLUDE_PATHS.
results.append(contentsOf: cbc.producer.expandedSearchPaths(for: BuiltinMacros.PRODUCT_TYPE_SWIFT_INCLUDE_PATHS, scope: cbc.scope))
if cbc.scope.evaluate(BuiltinMacros.SWIFT_ADD_TOOLCHAIN_SWIFTSYNTAX_SEARCH_PATHS) {
results.append(toolInfo.hostLibraryDirectory.str)
}
return results
}
private func compilerWorkingDirectory(_ cbc: CommandBuildContext) -> Path {
cbc.scope.evaluate(BuiltinMacros.COMPILER_WORKING_DIRECTORY).nilIfEmpty.map { Path($0) } ?? cbc.producer.defaultWorkingDirectory
}
private func getExplicitModuleBlocklist(_ producer: any CommandProducer, _ scope: MacroEvaluationScope, _ delegate: any CoreClientTargetDiagnosticProducingDelegate) async -> SwiftBlocklists.ExplicitModulesInfo? {
let specInfo = await (discoveredCommandLineToolSpecInfo(producer, scope, delegate) as? DiscoveredSwiftCompilerToolSpecInfo)
return specInfo?.blocklists.explicitModules
}
public func swiftShouldGenerateAdditionalLinkerArgsResponseFile(_ producer: any CommandProducer, _ scope: MacroEvaluationScope, _ delegate: any CoreClientTargetDiagnosticProducingDelegate) async -> Bool {
let toolSpecInfo: DiscoveredSwiftCompilerToolSpecInfo
do {
toolSpecInfo = try await discoveredCommandLineToolSpecInfo(producer, scope, delegate)
} catch {
delegate.error("Unable to discover `swiftc` command line tool info: \(error)")
return false
}
let responseFileSetting = scope.evaluate(BuiltinMacros.SWIFT_GENERATE_ADDITIONAL_LINKER_ARGS)
let explicitModulesEnabled = await swiftExplicitModuleBuildEnabled(producer, scope, delegate)
let compilerSupportsExplicitModulesBasedDebugInfo = toolSpecInfo.hasFeature(DiscoveredSwiftCompilerToolSpecInfo.FeatureFlag.debugInfoExplicitDependency.rawValue)
return responseFileSetting && explicitModulesEnabled && !compilerSupportsExplicitModulesBasedDebugInfo
}
public func swiftExplicitModuleBuildEnabled(_ producer: any CommandProducer, _ scope: MacroEvaluationScope, _ delegate: any CoreClientTargetDiagnosticProducingDelegate) async -> Bool {
let buildSettingEnabled = scope.evaluate(BuiltinMacros.SWIFT_ENABLE_EXPLICIT_MODULES) == .enabled ||
scope.evaluate(BuiltinMacros._EXPERIMENTAL_SWIFT_EXPLICIT_MODULES) == .enabled
// If this project is on the blocklist, override the blocklist default enable for it
if let explicitModuleBlocklist = await getExplicitModuleBlocklist(producer, scope, delegate), explicitModuleBlocklist.isProjectListed(producer, scope) {
return false
}
// rdar://122829880 (Turn off Swift explicit modules when c++ interop is enabled)
guard scope.evaluate(BuiltinMacros.SWIFT_OBJC_INTEROP_MODE) != "objcxx" && !scope.evaluate(BuiltinMacros.OTHER_SWIFT_FLAGS).contains("-cxx-interoperability-mode=default") else {
return scope.evaluate(BuiltinMacros._SWIFT_EXPLICIT_MODULES_ALLOW_CXX_INTEROP) && buildSettingEnabled
}
// Disable explicit modules in the pre-Swift-5 language modes to avoid versioned API notes confusion.
guard let swiftVersion = try? Version(scope.evaluate(BuiltinMacros.SWIFT_VERSION)), swiftVersion >= Version(5) else {