-
Notifications
You must be signed in to change notification settings - Fork 80
/
Copy pathCCompiler.swift
2075 lines (1726 loc) · 109 KB
/
CCompiler.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
//
//===----------------------------------------------------------------------===//
public import SWBUtil
public import SWBMacro
import Foundation
/// Abstract C Compiler. This is not a concrete implementation, but rather it uses various information in the command build context to choose a specific compiler and to call `constructTasks()` on that compiler. This provides a level of indirection for projects that just want their source files compiled using the default C compiler. Depending on the context, the default C compiler for any particular combination of platform, architecture, and other factors may be Clang, ICC, GCC, or some other compiler.
class AbstractCCompilerSpec : CompilerSpec, SpecIdentifierType, GCCCompatibleCompilerCommandLineBuilder, @unchecked Sendable {
static let identifier = "com.apple.compilers.gcc"
override func resolveConcreteSpec(_ cbc: CommandBuildContext) -> CommandLineToolSpec {
// Look up the “effective” compiler specification based on GCC_VERSION and other factors.
// FIXME: Xcode implements various checks here, and we should do the same. In particular we should look at GCC_VERSION.
let compilerIdentifier = ClangCompilerSpec.identifier
let spec = cbc.producer.getSpec(compilerIdentifier)
// FIXME: We should report an error if we didn’t end up finding a valid spec.
guard let compilerSpec = spec as? CompilerSpec else { return self }
return compilerSpec
}
override func constructTasks(_ cbc: CommandBuildContext, _ delegate: any TaskGenerationDelegate) async {
// FIXME: Report an error if we are ever asked to produce tasks directly.
}
}
public struct ClangPrefixInfo: Serializable, Hashable, Encodable, Sendable {
let input: Path
let pch: PCHInfo?
struct PCHInfo: Serializable, Hashable, Encodable {
let output: Path
let hashCriteria: Path? // Should be non-optional, but blocked on: <rdar://problem/24469921> [Swift Build] Complete handling of PCH precompiling
let commandLine: [ByteString]
private enum CodingKeys: CodingKey {
case output
case hashCriteria
case commandLine
}
init(output: Path, hashCriteria: Path?, commandLine: [ByteString]) {
self.output = output
self.hashCriteria = hashCriteria
self.commandLine = commandLine
}
func serialize<T: Serializer>(to serializer: T) {
serializer.serializeAggregate(3) {
serializer.serialize(self.output)
serializer.serialize(self.hashCriteria)
serializer.serialize(self.commandLine)
}
}
init(from deserializer: any Deserializer) throws {
try deserializer.beginAggregate(3)
self.output = try deserializer.deserialize()
self.hashCriteria = try deserializer.deserialize()
self.commandLine = try deserializer.deserialize()
}
}
init(input: Path, pch: PCHInfo?) {
self.input = input
self.pch = pch
}
public func serialize<T: Serializer>(to serializer: T) {
serializer.serializeAggregate(2) {
serializer.serialize(self.input)
serializer.serialize(self.pch)
}
}
public init(from deserializer: any Deserializer) throws {
try deserializer.beginAggregate(2)
self.input = try deserializer.deserialize()
self.pch = try deserializer.deserialize()
}
}
/// The minimal data we need to serialize to reconstruct `ClangSourceFileIndexingInfo` from `generateIndexingInfo`
fileprivate struct ClangIndexingPayload: Serializable, Encodable, Sendable {
let sourceFileIndex: Int
let outputFileIndex: Int
let sourceLanguageIndex: Int
let builtProductsDir: Path
let assetSymbolIndexPath: Path
let workingDir: Path
let prefixInfo: ClangPrefixInfo?
let toolchains: [String]
let responseFileAttachmentPaths: [Path: Path]
init(sourceFileIndex: Int,
outputFileIndex: Int,
sourceLanguageIndex: Int,
builtProductsDir: Path,
assetSymbolIndexPath: Path,
workingDir: Path,
prefixInfo: ClangPrefixInfo?,
toolchains: [String],
responseFileAttachmentPaths: [Path: Path]) {
self.sourceFileIndex = sourceFileIndex
self.outputFileIndex = outputFileIndex
self.sourceLanguageIndex = sourceLanguageIndex
self.builtProductsDir = builtProductsDir
self.assetSymbolIndexPath = assetSymbolIndexPath
self.workingDir = workingDir
self.prefixInfo = prefixInfo
self.toolchains = toolchains
self.responseFileAttachmentPaths = responseFileAttachmentPaths
}
func sourceFile(for task: any ExecutableTask) -> Path {
return Path(task.commandLine[self.sourceFileIndex].asString)
}
func serialize<T: Serializer>(to serializer: T) {
serializer.serializeAggregate(9) {
serializer.serialize(sourceFileIndex)
serializer.serialize(outputFileIndex)
serializer.serialize(sourceLanguageIndex)
serializer.serialize(builtProductsDir)
serializer.serialize(assetSymbolIndexPath)
serializer.serialize(workingDir)
serializer.serializeUniquely(prefixInfo)
serializer.serialize(toolchains)
serializer.serialize(responseFileAttachmentPaths)
}
}
init(from deserializer: any Deserializer) throws {
try deserializer.beginAggregate(9)
self.sourceFileIndex = try deserializer.deserialize()
self.outputFileIndex = try deserializer.deserialize()
self.sourceLanguageIndex = try deserializer.deserialize()
self.builtProductsDir = try deserializer.deserialize()
self.assetSymbolIndexPath = try deserializer.deserialize()
self.workingDir = try deserializer.deserialize()
self.prefixInfo = try deserializer.deserializeUniquely()
self.toolchains = try deserializer.deserialize()
self.responseFileAttachmentPaths = try deserializer.deserialize()
}
}
/// The indexing info for a file being compiled by clang. This will be sent to the client in a property list format described below.
public struct ClangSourceFileIndexingInfo: SourceFileIndexingInfo {
let outputFile: Path
let sourceLanguage: ByteString
let commandLine: [ByteString]
let builtProductsDir: Path
let assetSymbolIndexPath: Path
let prefixInfo: ClangPrefixInfo?
let toolchains: [String]
init(outputFile: Path, sourceLanguage: ByteString, commandLine: [ByteString], builtProductsDir: Path, assetSymbolIndexPath: Path, prefixInfo: ClangPrefixInfo?, toolchains: [String]) {
self.outputFile = outputFile
self.sourceLanguage = sourceLanguage
self.commandLine = commandLine
self.builtProductsDir = builtProductsDir
self.assetSymbolIndexPath = assetSymbolIndexPath
self.prefixInfo = prefixInfo
self.toolchains = toolchains
}
fileprivate init(task: any ExecutableTask, payload: ClangIndexingPayload, enableIndexBuildArena: Bool) {
self.outputFile = Path(task.commandLine[payload.outputFileIndex].asString)
self.sourceLanguage = task.commandLine[payload.sourceLanguageIndex].asByteString
self.commandLine = Self.indexingCommandLine(from: task.commandLine.map(\.asByteString), workingDir: payload.workingDir, prefixInfo: payload.prefixInfo, addSupplementary: !enableIndexBuildArena, responseFileMapping: payload.responseFileAttachmentPaths)
self.builtProductsDir = payload.builtProductsDir
self.assetSymbolIndexPath = payload.assetSymbolIndexPath
self.prefixInfo = payload.prefixInfo
self.toolchains = payload.toolchains
}
static let skippedArgsWithoutValues = Set<ByteString>(["-M", "-MD", "-MMD", "-MG", "-MJ", "-MM", "-MP", "-MV", "-fmodules-validate-once-per-build-session"])
static let skippedArgsWithValues = Set<ByteString>(["-MT", "-MF", "-MQ", "--serialize-diagnostics"])
public static func indexingCommandLine(from commandLine: [ByteString], workingDir: Path, prefixInfo: ClangPrefixInfo? = nil, addSupplementary: Bool = true, replaceCompile: Bool = true, responseFileMapping: [Path: Path]) -> [ByteString] {
var result = [ByteString]()
var iterator = commandLine.makeIterator()
let _ = iterator.next() // Skip compiler path
while let arg = iterator.next() {
if skippedArgsWithValues.contains(arg) {
// Skip arg and value
_ = iterator.next() // Ignore failure...
} else if skippedArgsWithoutValues.contains(arg) {
// Skip
} else if arg == "-c" && replaceCompile {
result.append("-fsyntax-only")
} else if let prefixInfo = prefixInfo, let pchInfo = prefixInfo.pch, arg == "-include" {
// Replace the PCH with the underlying header. Indexing will replace
// this with its own PCH if necessary.
result.append(arg)
guard let includePathBytes = iterator.next() else {
break
}
if let includePath = includePathBytes.stringValue,
pchInfo.output.str.hasPrefix(includePath) {
result.append(ByteString(encodingAsUTF8: prefixInfo.input.str))
} else {
result.append(includePathBytes)
}
} else if arg.bytes.starts(with: ByteString(stringLiteral: "-fbuild-session-file=").bytes) {
// Skip
} else if arg.starts(with: ByteString(unicodeScalarLiteral: "@")),
let attachmentPath = responseFileMapping[Path(arg.asString.dropFirst())],
let responseFileArgs = try? ResponseFiles.expandResponseFiles(["@\(attachmentPath.str)"], fileSystem: localFS, relativeTo: workingDir) {
result.append(contentsOf: responseFileArgs.map { ByteString(encodingAsUTF8: $0) })
} else {
result.append(arg)
}
}
// For <rdar://problem/8397100> Xcode4 can't see headers within relative paths
result.append(ByteString(encodingAsUTF8: "-working-directory=\(workingDir.str)"))
// Supplementary indexing parameters have already been added when the
// arena is enabled, just remove any unneeded options in that case.
if addSupplementary {
result += ClangCompilerSpec.supplementalIndexingArgs(allowCompilerErrors: false).map { 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]()
// sourceFile is not in this dictionary
dict["outputFilePath"] = PropertyListItem(outputFile.str)
// FIXME: Convert to bytes.
dict["LanguageDialect"] = PropertyListItem(sourceLanguage.asString)
// FIXME: Convert to bytes.
dict["clangASTCommandArguments"] = PropertyListItem(commandLine.map{ $0.asString })
dict["clangASTBuiltProductsDir"] = PropertyListItem(builtProductsDir.str)
dict["assetSymbolIndexPath"] = PropertyListItem(assetSymbolIndexPath.str)
if let prefixInfo = self.prefixInfo {
dict["clangPrefixFilePath"] = PropertyListItem(prefixInfo.input.str)
if let pch = prefixInfo.pch {
dict["clangPCHFilePath"] = PropertyListItem(pch.output.str)
if let hashCriteria = pch.hashCriteria {
dict["clangPCHHashCriteria"] = PropertyListItem(hashCriteria.str)
}
// FIXME: Convert to bytes.
dict["clangPCHCommandArguments"] = PropertyListItem(pch.commandLine.map{ $0.asString })
}
}
dict["toolchains"] = PropertyListItem(toolchains)
return .plDict(dict)
}
}
extension OutputPathIndexingInfo {
fileprivate init(task: any ExecutableTask, payload: ClangIndexingPayload) {
self.outputFile = Path(task.commandLine[payload.outputFileIndex].asString)
}
}
public enum ClangOutputParserRegex {
// 'Foo/Foo.h' file not found
public static let headerNotFoundRegEx = (RegEx(patternLiteral: "^'([^/]+)/.*' file not found$"), false)
// module 'Foo' not found
public static let moduleNotFoundRegEx = (RegEx(patternLiteral: "^module '(.+)' not found$"), true)
}
final class ClangOutputParser: TaskOutputParser {
private let task: any ExecutableTask
private let payload: ClangTaskPayload
let workspaceContext: WorkspaceContext
let buildRequestContext: BuildRequestContext
let delegate: any TaskOutputParserDelegate
init(for task: any ExecutableTask, workspaceContext: WorkspaceContext, buildRequestContext: BuildRequestContext, delegate: any TaskOutputParserDelegate, progressReporter: (any SubtaskProgressReporter)?) {
self.task = task
self.workspaceContext = workspaceContext
self.buildRequestContext = buildRequestContext
self.delegate = delegate
self.payload = task.payload as! ClangTaskPayload
}
func write(bytes: ByteString) {
// Forward the unparsed bytes immediately (without line buffering).
delegate.emitOutput(bytes)
// Disable diagnostic scraping, since we use serialized diagnostics.
}
func close(result: TaskResult?) {
defer {
delegate.close()
}
// Don't try to read diagnostics if the process crashed or got cancelled as they were almost certainly not written in this case.
if result.shouldSkipParsingDiagnostics { return }
for path in task.type.serializedDiagnosticsPaths(task, workspaceContext.fs) {
delegate.processSerializedDiagnostics(at: path, workingDirectory: task.workingDirectory, workspaceContext: workspaceContext)
}
// Read optimization remarks if the build succeeded.
if result?.isSuccess ?? false {
// If the object file path is not there, remarks might not be generated.
if let path = payload.outputObjectFilePath {
delegate.processOptimizationRemarks(at: path, workingDirectory: task.workingDirectory, workspaceContext: workspaceContext)
}
}
}
}
public struct ClangExplicitModulesPayload: Serializable, Encodable, Sendable {
public let uniqueID: String
public let sourcePath: Path
public let libclangPath: Path
public let usesCompilerLauncher: Bool
public let outputPath: Path
public let scanningOutputPath: Path
public let casOptions: CASOptions?
public let cacheFallbackIfNotAvailable: Bool
public let dependencyFilteringRootPath: Path?
public let reportRequiredTargetDependencies: BooleanWarningLevel
public let verifyingModule: String?
fileprivate init(uniqueID: String, sourcePath: Path, libclangPath: Path, usesCompilerLauncher: Bool, outputPath: Path, scanningOutputPath: Path, casOptions: CASOptions?, cacheFallbackIfNotAvailable: Bool, dependencyFilteringRootPath: Path?, reportRequiredTargetDependencies: BooleanWarningLevel, verifyingModule: String?) {
self.uniqueID = uniqueID
self.sourcePath = sourcePath
self.libclangPath = libclangPath
self.usesCompilerLauncher = usesCompilerLauncher
self.outputPath = outputPath
self.scanningOutputPath = scanningOutputPath
self.casOptions = casOptions
self.cacheFallbackIfNotAvailable = cacheFallbackIfNotAvailable
self.dependencyFilteringRootPath = dependencyFilteringRootPath
self.reportRequiredTargetDependencies = reportRequiredTargetDependencies
self.verifyingModule = verifyingModule
}
public func serialize<T: Serializer>(to serializer: T) {
serializer.serializeAggregate(11) {
serializer.serialize(uniqueID)
serializer.serialize(sourcePath)
serializer.serialize(libclangPath)
serializer.serialize(usesCompilerLauncher)
serializer.serialize(outputPath)
serializer.serialize(scanningOutputPath)
serializer.serialize(casOptions)
serializer.serialize(cacheFallbackIfNotAvailable)
serializer.serialize(dependencyFilteringRootPath)
serializer.serialize(reportRequiredTargetDependencies)
serializer.serialize(verifyingModule)
}
}
public init(from deserializer: any Deserializer) throws {
try deserializer.beginAggregate(11)
self.uniqueID = try deserializer.deserialize()
self.sourcePath = try deserializer.deserialize()
self.libclangPath = try deserializer.deserialize()
self.usesCompilerLauncher = try deserializer.deserialize()
self.outputPath = try deserializer.deserialize()
self.scanningOutputPath = try deserializer.deserialize()
self.casOptions = try deserializer.deserialize()
self.cacheFallbackIfNotAvailable = try deserializer.deserialize()
self.dependencyFilteringRootPath = try deserializer.deserialize()
self.reportRequiredTargetDependencies = try deserializer.deserialize()
self.verifyingModule = try deserializer.deserialize()
}
}
public protocol ClangModuleVerifierPayloadType: TaskPayload {
var fileNameMapPath: Path? { get }
}
struct ClangModuleVerifierPayload: ClangModuleVerifierPayloadType {
var fileNameMapPath: Path?
func serialize<T>(to serializer: T) where T : SWBUtil.Serializer {
serializer.serialize(fileNameMapPath)
}
init(from deserializer: any SWBUtil.Deserializer) throws {
self.fileNameMapPath = try deserializer.deserialize()
}
init(fileNameMapPath: Path?) {
self.fileNameMapPath = fileNameMapPath
}
}
public struct ClangTaskPayload: ClangModuleVerifierPayloadType, DependencyInfoEditableTaskPayload, Encodable {
let dependencyInfoEditPayload: DependencyInfoEditPayload?
/// The path to the serialized diagnostic output. Every clang task must provide this path.
public let serializedDiagnosticsPath: Path?
/// Additional information used to answer indexing queries. Not all clang tasks will need to provide indexing info (for example, precompilation tasks don't).
fileprivate let indexingPayload: ClangIndexingPayload?
/// Additional information used by explicit modules support.
public let explicitModulesPayload: ClangExplicitModulesPayload?
/// Additional information used by optimization remarks support.
fileprivate let outputObjectFilePath: Path?
public let fileNameMapPath: Path?
fileprivate init(serializedDiagnosticsPath: Path?, indexingPayload: ClangIndexingPayload?, explicitModulesPayload: ClangExplicitModulesPayload? = nil, outputObjectFilePath: Path? = nil, fileNameMapPath: Path? = nil, developerPathString: String? = nil) {
if let developerPathString, explicitModulesPayload == nil {
self.dependencyInfoEditPayload = .init(removablePaths: [], removableBasenames: [], developerPath: Path(developerPathString))
} else {
dependencyInfoEditPayload = nil
}
self.serializedDiagnosticsPath = serializedDiagnosticsPath
self.indexingPayload = indexingPayload
self.explicitModulesPayload = explicitModulesPayload
self.outputObjectFilePath = outputObjectFilePath
self.fileNameMapPath = fileNameMapPath
}
public func serialize<T: Serializer>(to serializer: T) {
serializer.serializeAggregate(6) {
serializer.serialize(serializedDiagnosticsPath)
serializer.serialize(indexingPayload)
serializer.serialize(explicitModulesPayload)
serializer.serialize(outputObjectFilePath)
serializer.serialize(fileNameMapPath)
serializer.serialize(dependencyInfoEditPayload)
}
}
public init(from deserializer: any Deserializer) throws {
try deserializer.beginAggregate(6)
self.serializedDiagnosticsPath = try deserializer.deserialize()
self.indexingPayload = try deserializer.deserialize()
self.explicitModulesPayload = try deserializer.deserialize()
self.outputObjectFilePath = try deserializer.deserialize()
self.fileNameMapPath = try deserializer.deserialize()
self.dependencyInfoEditPayload = try deserializer.deserialize()
}
}
/// Helper for fast argument matching.
//
// FIXME: We should eventually just redefine this to be based on regular
// expressions, not fnmatch, and then use a fast regular expression engine to
// manage this.
public enum FlagPattern: Sendable {
/// Check for an exact string.
case exact(String)
/// Check for a prefix.
case prefix(String)
/// Use a general purpose fnmatch pattern.
case fnmatch(String)
/// Create a flag pattern from a fnmatch(3) style pattern.
public static func fromFnmatch(_ pattern: String) -> FlagPattern {
// If the pattern contains any particularly special fnmatch characters, fall back.
if pattern.contains("?") || pattern.contains("[") {
return .fnmatch(pattern)
}
// If the pattern contains only the special '*' character at the end,
// see if we can use a prefix match.
if pattern.contains("*") {
if pattern.hasSuffix("*") && !pattern.hasSuffix("\\*") && !pattern.dropLast(1).contains("*") {
return .prefix(String(pattern.dropLast(1)))
} else {
return .fnmatch(pattern)
}
}
// Otherwise, we have an exact match.
return .exact(pattern)
}
/// Check if the pattern matches a given string.
public func matches(_ string: String) -> Bool {
switch self {
case .exact(let pattern):
return string == pattern
case .prefix(let pattern):
return string.hasPrefix(pattern)
case .fnmatch(let pattern):
// `fnmatch` is not really expected to fail so there is not a lot of
// benefit in handling the errors.
return (try? SWBUtil.fnmatch(pattern: pattern, input: string)) == true
}
}
}
public class ClangCompilerSpec : CompilerSpec, SpecIdentifierType, GCCCompatibleCompilerCommandLineBuilder, @unchecked Sendable {
/// Clang compiler data cache, used to cache constant flags.
fileprivate final class DataCache: SpecDataCache {
fileprivate struct ConstantFlagsKey: Hashable, Sendable {
/// The scope in use.
let scope: MacroEvaluationScope
/// The input file type.
let inputFileType: FileTypeSpec
public func hash(into hasher: inout Hasher) {
hasher.combine(ObjectIdentifier(scope))
hasher.combine(inputFileType)
}
}
fileprivate struct ConstantFlags {
/// The flags themselves.
let flags: [String]
/// The header search path arguments used to compute these flags.
let headerSearchPaths: SearchPaths
/// The compilation inputs implied by these flags.
let inputs: [Path]
/// Maps response files in `flags` to the corresponding recorded attachment in the build description.
let responseFileMapping: [Path: Path]
}
/// Cache of constant flags, keyed by the scope and input file type.
private let constantFlagsCache = Registry<ConstantFlagsKey, ConstantFlags>()
required init() { }
func getStandardFlags(_ spec: ClangCompilerSpec, producer: any CommandProducer, scope: MacroEvaluationScope, optionContext: (any BuildOptionGenerationContext)?, delegate: any TaskGenerationDelegate, inputFileType: FileTypeSpec) -> ConstantFlags {
// This cache is per-producer, so it is guaranteed to be invariant based on that.
constantFlagsCache.getOrInsert(ConstantFlagsKey(scope: scope, inputFileType: inputFileType)) {
return spec.standardFlags(producer, scope: scope, optionContext: optionContext, delegate: delegate, inputFileType: inputFileType)
}
}
}
private typealias ConstantFlags = DataCache.ConstantFlags
/// The class name under which we’re known in .xcspec files.
public class var identifier: String {
"com.apple.compilers.llvm.clang.1_0.compiler"
}
/// The GCC language names to support precompiling for.
static let gccLanguagesToPrecompile = GCCCompatibleLanguageDialect.allCLanguages
/// The output file extension to use (an extension point for the static analyzer, as well as generating assembly and preprocessor output).
func outputFileExtension(for input: FileToBuild) -> String {
return ".o"
}
/// Whether to add serialize diagnostics options (an extension point for the static analyzer).
func serializedDiagnosticsOptions(scope: MacroEvaluationScope, outputPath: Path) -> (path: Path, flags: [String])? {
if scope.evaluate(BuiltinMacros.CLANG_DISABLE_SERIALIZED_DIAGNOSTICS) {
return nil
}
let diagFilePath = Path(outputPath.withoutSuffix + ".dia")
return (diagFilePath, ["--serialize-diagnostics", diagFilePath.str])
}
var effectiveSourceFileOption: String {
return sourceFileOption ?? "-c"
}
var shouldPrecompilePrefixHeader: Bool {
return true
}
/// List of fnmatch()-style patterns for command line arguments that do not affect the validity of a precompiled header. Could be empty.
let precompNeutralFlagPatterns: [FlagPattern]
required init(_ parser: SpecParser, _ basedOnSpec: Spec?) {
// Parse an array of fnmatch()-style patterns for command line arguments that do not affect the validity of a precompiled header.
self.precompNeutralFlagPatterns = (parser.parseStringList("PatternsOfFlagsNotAffectingPrecomps") ?? []).map(FlagPattern.fromFnmatch)
// Parse and ignore the 'RuleName' key (for now).
//
// This is handled by the generic spec in Xcode, but we more strictly enforce the separation between "generic" tools and non-generic ones.
parser.parseObject("RuleName")
super.init(parser, basedOnSpec, isGeneric: false)
}
private func standardFlags(_ producer: any CommandProducer, scope: MacroEvaluationScope, optionContext: (any BuildOptionGenerationContext)?, delegate: any TaskGenerationDelegate, inputFileType: FileTypeSpec) -> ConstantFlags {
var commandLine = Array<String>()
// Add the arguments from the specification.
commandLine += self.commandLineFromOptions(producer, scope: scope, inputFileType: inputFileType, optionContext: optionContext,lookup: { declaration in
if declaration.name == "CLANG_INDEX_STORE_ENABLE" && optionContext is DiscoveredClangToolSpecInfo {
let clangToolInfo = optionContext as! DiscoveredClangToolSpecInfo
if !clangToolInfo.isAppleClang {
return BuiltinMacros.namespace.parseString("NO")
}
}
return nil
}).map(\.asString)
// Add the common header search paths.
let headerSearchPaths = GCCCompatibleCompilerSpecSupport.headerSearchPathArguments(producer, scope, usesModules: scope.evaluate(BuiltinMacros.CLANG_ENABLE_MODULES))
commandLine += headerSearchPaths.searchPathArguments(for: self, scope: scope)
// Add per-architecture flags (this is slated for deprecation, since there are now simpler ways to accomplish the same thing).
commandLine += scope.evaluate(BuiltinMacros.PER_ARCH_CFLAGS)
// Add warning flags (this is slated for deprecation, since there are now simpler ways to accomplish the same thing).
commandLine += scope.evaluate(BuiltinMacros.WARNING_CFLAGS)
// Add optimization flags (this is slated for deprecation, since there are now simpler ways to accomplish the same thing).
commandLine += scope.evaluate(BuiltinMacros.OPTIMIZATION_CFLAGS)
// Add the common framework search paths.
let frameworkSearchPaths = GCCCompatibleCompilerSpecSupport.frameworkSearchPathArguments(producer, scope)
commandLine += frameworkSearchPaths.searchPathArguments(for: self, scope: scope)
// Add GLOBAL_CFLAGS (this is slated for deprecation, since there are now simpler ways to accomplish the same thing).
commandLine += scope.evaluate(BuiltinMacros.GLOBAL_CFLAGS)
// Add either OTHER_CPLUSPLUSFLAGS or OTHER_CFLAGS.
if let dialect = inputFileType.languageDialect, dialect.isPlusPlus {
commandLine += scope.evaluate(BuiltinMacros.OTHER_CPLUSPLUSFLAGS)
} else {
commandLine += scope.evaluate(BuiltinMacros.OTHER_CFLAGS)
}
// Add per-variant flags (this is slated for deprecation, since there are now simpler ways to accomplish the same thing).
commandLine += scope.evaluate(BuiltinMacros.PER_VARIANT_CFLAGS)
// If we’re building the “profile” variant and if GCC_GENERATE_PROFILING_CODE is true then also add "-pg".
if scope.evaluate(BuiltinMacros.CURRENT_VARIANT) == "profile" && scope.evaluate(BuiltinMacros.GCC_GENERATE_PROFILING_CODE) {
commandLine.append("-pg")
}
// Add search paths for sparse SDKs.
let sparseSDKSearchPaths = GCCCompatibleCompilerSpecSupport.sparseSDKSearchPathArguments(producer.sparseSDKs, headerSearchPaths.headerSearchPaths, frameworkSearchPaths.frameworkSearchPaths)
commandLine += sparseSDKSearchPaths.searchPathArguments(for: self, scope: scope)
if scope.evaluate(BuiltinMacros.CLANG_USE_RESPONSE_FILE) && (optionContext?.toolPath.basenameWithoutSuffix == "clang" || optionContext?.toolPath.basenameWithoutSuffix == "clang++") {
var responseFileCommandLine: [String] = []
var regularCommandLine: [String] = []
var iterator = commandLine.makeIterator()
var previousArg: ByteString? = nil
while let arg = iterator.next() {
let argAsByteString = ByteString(encodingAsUTF8: arg)
if ClangSourceFileIndexingInfo.skippedArgsWithValues.contains(argAsByteString) || arg == "-include" {
// Relevant to indexing, so exclude arg and value from response file.
regularCommandLine.append(arg)
if let nextArg = iterator.next() {
regularCommandLine.append(nextArg)
}
} else if ClangSourceFileIndexingInfo.skippedArgsWithoutValues.contains(argAsByteString) || arg.starts(with: "-fbuild-session-file=") {
// Relevant to indexing, so exclude arg from response file.
regularCommandLine.append(arg)
} else if isOutputAgnosticCommandLineArgument(argAsByteString, prevArgument: previousArg) {
// Output agnostic, so exclude from response file.
regularCommandLine.append(arg)
} else if precompNeutralFlagPatterns.map({ $0.matches(arg) }).reduce(false, { $0 || $1 }) && !(previousArg ?? "").hasPrefix("-X") {
// Exclude from response file.
regularCommandLine.append(arg)
} else {
responseFileCommandLine.append(arg)
}
previousArg = argAsByteString
}
let ctx = InsecureHashContext()
ctx.add(string: inputFileType.identifier)
ctx.add(string: self.identifier)
let responseFilePath = scope.evaluate(BuiltinMacros.PER_ARCH_OBJECT_FILE_DIR).join("\(ctx.signature.asString)-common-args.resp")
let attachmentPath = producer.writeFileSpec.constructFileTasks(CommandBuildContext(producer: producer, scope: scope, inputs: [], output: responseFilePath), delegate, contents: ByteString(encodingAsUTF8: ResponseFiles.responseFileContents(args: responseFileCommandLine)), permissions: nil, logContents: true, preparesForIndexing: true, additionalTaskOrderingOptions: [.immediate, .ignorePhaseOrdering])
return ConstantFlags(flags: regularCommandLine + ["@\(responseFilePath.str)"], headerSearchPaths: headerSearchPaths, inputs: [responseFilePath], responseFileMapping: [responseFilePath: attachmentPath])
} else {
return ConstantFlags(flags: commandLine, headerSearchPaths: headerSearchPaths, inputs: [], responseFileMapping: [:])
}
}
override public func resolvedSourceFileType(file: FileToBuild, inBuildContext cbc: CommandBuildContext, delegate: any TaskGenerationDelegate) -> FileTypeSpec {
var fileType = super.resolvedSourceFileType(file: file, inBuildContext: cbc, delegate: delegate)
// If the target uses GCC_INPUT_FILETYPE to override the language, use that
let overrideFileTypeIdent = cbc.scope.evaluate(BuiltinMacros.GCC_INPUT_FILETYPE)
if !overrideFileTypeIdent.isEmpty && overrideFileTypeIdent != "automatic" {
if let overriddenType = cbc.producer.lookupFileType(identifier: overrideFileTypeIdent) {
fileType = overriddenType
} else {
delegate.warning("unsupported value '\(overrideFileTypeIdent)' for build setting GCC_INPUT_FILETYPE")
}
}
let targetFlags: [String]
if let dialect = fileType.languageDialect, dialect.isPlusPlus {
targetFlags = cbc.scope.evaluate(BuiltinMacros.OTHER_CPLUSPLUSFLAGS)
} else {
targetFlags = cbc.scope.evaluate(BuiltinMacros.OTHER_CFLAGS)
}
let fileFlags: [String]
if let additionalArgs = file.additionalArgs {
fileFlags = cbc.scope.evaluate(additionalArgs)
} else {
fileFlags = []
}
// If OTHER_C[PLUSPLUS]FLAGS or file-specific flags use -x to override the language, use that
if let dialectName = [targetFlags, fileFlags].compactMap({ $0.byExtractingElementsHavingPrefix("-x").last }).last {
if let overriddenType = cbc.producer.lookupFileType(languageDialect: GCCCompatibleLanguageDialect(dialectName: dialectName)) {
fileType = overriddenType
}
}
return fileType
}
static let outputAgnosticCompilerArguments = Set<ByteString>([
// https://clang.llvm.org/docs/UsersManual.html#formatting-of-diagnostics
"-fshow-column",
"-fno-show-column",
"-fshow-source-location",
"-fno-show-source-location",
"-fcaret-diagnostics",
"-fno-caret-diagnostics",
"-fcolor-diagnostics",
"-fno-color-diagnostics",
"-fansi-escape-codes",
"-fdiagnostics-show-option",
"-fno-diagnostics-show-option",
"-fdiagnostics-show-hotness",
"-fno-diagnostics-show-hotness",
"-fdiagnostics-fixit-info",
"-fno-diagnostics-fixit-info",
"-fdiagnostics-print-source-range-info",
"-fdiagnostics-parseable-fixits",
"-fno-elide-type",
"-fdiagnostics-show-template-tree",
// https://clang.llvm.org/docs/ClangCommandLineReference.html
"-fdiagnostics-show-note-include-stack",
"-fno-diagnostics-show-note-include-stack",
"-fmodules-validate-once-per-build-session",
])
static let outputAgnosticCompilerArgumentPrefixes = Set<ByteString>([
// https://clang.llvm.org/docs/UsersManual.html#formatting-of-diagnostics
"-fdiagnostics-format=",
"-fdiagnostics-show-category=",
"-fdiagnostics-hotness-threshold=",
// https://clang.llvm.org/docs/ClangCommandLineReference.html
"-fmessage-length=",
"-fmacro-backtrace-limit=",
"-fbuild-session-timestamp=",
])
static let outputAgnosticCompilerArgumentsWithValues = Set<ByteString>([
"-index-store-path",
"-index-unit-output-path",
])
func isOutputAgnosticCommandLineArgument(_ argument: ByteString, prevArgument: ByteString?) -> Bool {
if ClangCompilerSpec.outputAgnosticCompilerArguments.contains(argument) ||
ClangCompilerSpec.outputAgnosticCompilerArgumentsWithValues.contains(argument) {
return true
}
if ClangCompilerSpec.outputAgnosticCompilerArgumentPrefixes.first(where: { argument.hasPrefix($0) }) != nil {
return true
}
if let prevArgument, ClangCompilerSpec.outputAgnosticCompilerArgumentsWithValues.contains(prevArgument) {
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_CFLAGS where the user can't possibly add this metadata to
// the values, but those settings be handled on a case-by-case basis.
return task.commandLine.indices.compactMap { index in
let arg = task.commandLine[index].asByteString
let prevArg = index > task.commandLine.startIndex ? task.commandLine[index - 1].asByteString : nil
if isOutputAgnosticCommandLineArgument(arg, prevArgument: prevArg) {
return nil
}
return arg
}
}
func cachingBuildEnabled(
_ cbc: CommandBuildContext,
language: GCCCompatibleLanguageDialect,
clangInfo: DiscoveredClangToolSpecInfo?
) -> Bool {
guard cbc.producer.supportsCompilationCaching else { return false }
// Disabling compilation caching for index build, for now.
guard !cbc.scope.evaluate(BuiltinMacros.INDEX_ENABLE_BUILD_ARENA) else {
return false
}
let enabledCppModules: Bool = {
guard language.isPlusPlus else {
return false
}
// When response file is used the flag is in the response file, not in the commandLine array,
// so check the build setting.
if cbc.scope.evaluate(BuiltinMacros.OTHER_CPLUSPLUSFLAGS).contains("-fcxx-modules") {
return true
}
return false
}()
guard !enabledCppModules else {
return false
}
let buildSettingEnabled = cbc.scope.evaluate(BuiltinMacros.CLANG_ENABLE_COMPILE_CACHE) == .enabled
// If a blocklist is provided in the toolchain, use it to determine the default for the current project
guard let blocklist = clangInfo?.clangCachingBlocklist else {
return buildSettingEnabled
}
// If this project is on the blocklist, override the blocklist default enable for it
if blocklist.isProjectListed(cbc.scope) {
return false
}
return buildSettingEnabled
}
private func createExplicitModulesActionAndPayload(_ cbc: CommandBuildContext, _ delegate: any TaskGenerationDelegate, _ compilerLauncher: Path?, _ input: FileToBuild, _ language: GCCCompatibleLanguageDialect?, commandLine: [String], scanningOutputPath: Path, isForPCHTask: Bool, clangInfo: DiscoveredClangToolSpecInfo?) -> (action: (any PlannedTaskAction)?, usesExecutionInputs: Bool, payload: ClangExplicitModulesPayload?, signatureData: String?) {
guard let language else {
// Unknown language.
return (nil, false, nil, nil)
}
// SourceKit does not currently use explicit modules when generating an AST. Don't generate a payload here, or we might build a PCH it can't load later.
guard !cbc.scope.evaluate(BuiltinMacros.INDEX_ENABLE_BUILD_ARENA) else {
return (nil, false, nil, nil)
}
let cachedBuild = cachingBuildEnabled(cbc, language: language, clangInfo: clangInfo)
let explicitModules = cbc.scope.evaluate(BuiltinMacros.CLANG_ENABLE_MODULES)
&& (cbc.scope.evaluate(BuiltinMacros.CLANG_ENABLE_EXPLICIT_MODULES) || cbc.scope.evaluate(BuiltinMacros._EXPERIMENTAL_CLANG_EXPLICIT_MODULES))
let explicitModulesLanguages: Set<GCCCompatibleLanguageDialect> = [
.c, .objectiveC
]
let supportedLanguages = cachedBuild ? GCCCompatibleLanguageDialect.allCLanguages : explicitModulesLanguages
// Only enable dep scanner if requested by the user and if the language supports it.
EXPLICIT_MODULES: if cachedBuild || explicitModules, supportedLanguages.contains(language) {
let usesCompilerLauncher = compilerLauncher != nil
if !explicitModules && explicitModulesLanguages.contains(language) && cbc.scope.evaluate(BuiltinMacros.CLANG_ENABLE_MODULES) {
delegate.warning("Compile caching is not supported with implicit modules; enable CLANG_ENABLE_EXPLICIT_MODULES")
break EXPLICIT_MODULES
}
if usesCompilerLauncher && !cbc.scope.evaluate(BuiltinMacros.CLANG_ENABLE_EXPLICIT_MODULES_WITH_COMPILER_LAUNCHER) {
delegate.remark("Explicit modules is not supported with C_COMPILER_LAUNCHER; disable explicit modules with CLANG_ENABLE_EXPLICIT_MODULES=NO, or enable CLANG_ENABLE_EXPLICIT_MODULES_WITH_COMPILER_LAUNCHER=YES if using a compatible launcher")
break EXPLICIT_MODULES
}
guard let compiler = commandLine[safe: usesCompilerLauncher ? 1 : 0].map(Path.init)?.normalize() else {
break EXPLICIT_MODULES
}
// Check that we are using a recognized clang.
switch compiler.basenameWithoutSuffix {
case "clang", "clang++":
break
default:
// Not recognized as clang; assume the worst.
delegate.remark("Explicit modules is enabled but the compiler was not recognized; disable explicit modules with CLANG_ENABLE_EXPLICIT_MODULES=NO, or use C_COMPILER_LAUNCHER with CLANG_ENABLE_EXPLICIT_MODULES_WITH_COMPILER_LAUNCHER=YES if using a compatible launcher")
break EXPLICIT_MODULES
}
// Verify we have a clang version with the latest explicit modules bugfixes.
if let clangVersion = clangInfo?.clangVersion, clangVersion < Version(1403, 0, 300, 5) {
delegate.warning("Explicit modules is not supported with Clang version \(clangVersion), continuing with explicit modules disabled.")
break EXPLICIT_MODULES
}
func findLibclang() -> Path? {
// Let the user define the path to libclang
let userLibclang = cbc.scope.evaluate(BuiltinMacros.CLANG_EXPLICIT_MODULES_LIBCLANG_PATH)
if !userLibclang.isEmpty {
return Path(userLibclang)
}
// If not defined, try to find one from the toolchain.
var candidatesSkipped: [Path] = []
for (toolchainPath, toolchainLibrarySearchPath) in cbc.producer.toolchains.map({ ($0.path, $0.librarySearchPaths) }) {
if let path = toolchainLibrarySearchPath.findLibrary(operatingSystem: cbc.producer.hostOperatingSystem, basename: "clang") {
// Check that this is the same toolchain and version as the compiler. Mismatched clang/libclang is not supported with explicit modules.
let compilerAndLibraryAreInSameToolchain = toolchainPath.isAncestor(of: compiler)
let libclangVersion = cbc.producer.lookupLibclang(path: path).version
let compilerAndLibraryVersionsMatch = libclangVersion != nil && libclangVersion == clangInfo?.clangVersion
if compilerAndLibraryAreInSameToolchain && (compilerAndLibraryVersionsMatch || cbc.scope.evaluate(BuiltinMacros.CLANG_EXPLICIT_MODULES_IGNORE_LIBCLANG_VERSION_MISMATCH)) {
return path
}
candidatesSkipped.append(path)
}
}
// If an open-source Swift toolchain is in use, suppress warnings about libclang mismatch.
if !cbc.producer.toolchains.contains(where: { toolchain in
toolchain.identifier.hasPrefix("org.swift.")
}) {
delegate.remark("Explicit modules is enabled but could not resolve libclang.dylib, continuing with explicit modules disabled.")
for path in candidatesSkipped {
delegate.note("Candidate '\(path.str)' skipped because it did not match the configured compiler")
}
}
return nil
}
// Find the first libclang.dylib in the configured toolchains, and set it into the environment so that the scan action can read it.
if let libclangPath = findLibclang() {
let action = delegate.taskActionCreationDelegate.createClangCompileTaskAction()
let casOptions: CASOptions? = {
guard cachedBuild else { return nil }
do {
var casOpts = try CASOptions.create(cbc.scope, .compiler(language))
if casOpts.enableIntegratedCacheQueries, let clangInfo {
if !clangInfo.toolFeatures.has(.libclangCacheQueries) {
delegate.warning("COMPILATION_CACHE_ENABLE_INTEGRATED_QUERIES ignored because it's not supported by the toolchain")
casOpts.enableIntegratedCacheQueries = false
}
}
return casOpts
} catch {
delegate.error(error.localizedDescription)
return nil
}
}()
let explicitModulesPayload = ClangExplicitModulesPayload(
uniqueID: String(commandLine.hashValue),
sourcePath: input.absolutePath,
libclangPath: libclangPath,
usesCompilerLauncher: usesCompilerLauncher,
// This path is scoped to the project, so ideally different targets that use the same modules would
// share precompiled modules.
outputPath: Path(cbc.scope.evaluate(BuiltinMacros.CLANG_EXPLICIT_MODULES_OUTPUT_PATH)),
scanningOutputPath: scanningOutputPath,
casOptions: casOptions,
cacheFallbackIfNotAvailable: cbc.scope.evaluate(BuiltinMacros.CLANG_CACHE_FALLBACK_IF_UNAVAILABLE),
// To match the behavior of -MMD, our scan task should filter out headers in the SDK when discovering dependencies. In the long run, libclang should do this for us.
dependencyFilteringRootPath: isForPCHTask ? nil : cbc.producer.sdk?.path,
reportRequiredTargetDependencies: cbc.scope.evaluate(BuiltinMacros.DIAGNOSE_MISSING_TARGET_DEPENDENCIES),
verifyingModule: verifyingModule(cbc)
)
let explicitModulesSignatureData = cachedBuild ? "cached" : nil
return (action, true, explicitModulesPayload, explicitModulesSignatureData)
}
}
return (nil, false, nil, nil)
}
func createClangModuleVerifierPayload(_ cbc: CommandBuildContext) -> ClangModuleVerifierPayload? {
return nil
}