/
BuildPlan.swift
2392 lines (2039 loc) · 97.8 KB
/
BuildPlan.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) 2015-2022 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 Basics
import Foundation
import LLBuildManifest
import OrderedCollections
import PackageGraph
import PackageLoading
import PackageModel
import SPMBuildCore
@_implementationOnly import SwiftDriver
import TSCBasic
import enum TSCUtility.Diagnostics
import struct TSCUtility.Triple
import var TSCUtility.verbosity
extension String {
fileprivate var asSwiftStringLiteralConstant: String {
return unicodeScalars.reduce("", { $0 + $1.escaped(asASCII: false) })
}
}
extension AbsolutePath {
internal func nativePathString(escaped: Bool) -> String {
return URL(fileURLWithPath: self.pathString).withUnsafeFileSystemRepresentation {
let repr = String(cString: $0!)
if escaped {
return repr.replacingOccurrences(of: "\\", with: "\\\\")
}
return repr
}
}
}
extension BuildParameters {
/// Returns the directory to be used for module cache.
public var moduleCache: AbsolutePath {
// FIXME: We use this hack to let swiftpm's functional test use shared
// cache so it doesn't become painfully slow.
if let path = ProcessEnv.vars["SWIFTPM_TESTS_MODULECACHE"] {
return AbsolutePath(path)
}
return buildPath.appending(component: "ModuleCache")
}
/// Extra flags to pass to Swift compiler.
public var swiftCompilerFlags: [String] {
var flags = self.flags.cCompilerFlags.flatMap({ ["-Xcc", $0] })
flags += self.flags.swiftCompilerFlags
if self.verboseOutput {
flags.append("-v")
}
return flags
}
/// Extra flags to pass to linker.
public var linkerFlags: [String] {
// Arguments that can be passed directly to the Swift compiler and
// doesn't require -Xlinker prefix.
//
// We do this to avoid sending flags like linker search path at the end
// of the search list.
let directSwiftLinkerArgs = ["-L"]
var flags: [String] = []
var it = self.flags.linkerFlags.makeIterator()
while let flag = it.next() {
if directSwiftLinkerArgs.contains(flag) {
// `-L <value>` variant.
flags.append(flag)
guard let nextFlag = it.next() else {
// We expected a flag but don't have one.
continue
}
flags.append(nextFlag)
} else if directSwiftLinkerArgs.contains(where: { flag.hasPrefix($0) }) {
// `-L<value>` variant.
flags.append(flag)
} else {
flags += ["-Xlinker", flag]
}
}
return flags
}
/// Returns the compiler arguments for the index store, if enabled.
fileprivate func indexStoreArguments(for target: ResolvedTarget) -> [String] {
let addIndexStoreArguments: Bool
switch indexStoreMode {
case .on:
addIndexStoreArguments = true
case .off:
addIndexStoreArguments = false
case .auto:
if configuration == .debug {
addIndexStoreArguments = true
} else if target.type == .test {
// Test discovery requires an index store for the test target to discover the tests
addIndexStoreArguments = true
} else {
addIndexStoreArguments = false
}
}
if addIndexStoreArguments {
return ["-index-store-path", indexStore.pathString]
}
return []
}
/// Computes the target triple arguments for a given resolved target.
public func targetTripleArgs(for target: ResolvedTarget) throws -> [String] {
var args = ["-target"]
// Compute the triple string for Darwin platform using the platform version.
if triple.isDarwin() {
guard let macOSSupportedPlatform = target.platforms.getDerived(for: .macOS) else {
throw StringError("the target \(target) doesn't support building for macOS")
}
args += [triple.tripleString(forPlatformVersion: macOSSupportedPlatform.version.versionString)]
} else {
args += [triple.tripleString]
}
return args
}
/// Computes the linker flags to use in order to rename a module-named main function to 'main' for the target platform, or nil if the linker doesn't support it for the platform.
fileprivate func linkerFlagsForRenamingMainFunction(of target: ResolvedTarget) -> [String]? {
let args: [String]
if self.triple.isDarwin() {
args = ["-alias", "_\(target.c99name)_main", "_main"]
}
else if self.triple.isLinux() {
args = ["--defsym", "main=\(target.c99name)_main"]
}
else {
return nil
}
return args.flatMap { ["-Xlinker", $0] }
}
/// Returns the scoped view of build settings for a given target.
fileprivate func createScope(for target: ResolvedTarget) -> BuildSettings.Scope {
return BuildSettings.Scope(target.underlyingTarget.buildSettings, environment: buildEnvironment)
}
}
/// A target description which can either be for a Swift or Clang target.
public enum TargetBuildDescription {
/// Swift target description.
case swift(SwiftTargetBuildDescription)
/// Clang target description.
case clang(ClangTargetBuildDescription)
/// The objects in this target.
var objects: [AbsolutePath] {
switch self {
case .swift(let target):
return target.objects
case .clang(let target):
return target.objects
}
}
/// The resources in this target.
var resources: [Resource] {
switch self {
case .swift(let target):
return target.resources
case .clang(let target):
// TODO: Clang targets should support generated resources in the future.
return target.target.underlyingTarget.resources
}
}
/// Path to the bundle generated for this module (if any).
var bundlePath: AbsolutePath? {
switch self {
case .swift(let target):
return target.bundlePath
case .clang(let target):
return target.bundlePath
}
}
var target: ResolvedTarget {
switch self {
case .swift(let target):
return target.target
case .clang(let target):
return target.target
}
}
/// Paths to the binary libraries the target depends on.
var libraryBinaryPaths: Set<AbsolutePath> {
switch self {
case .swift(let target):
return target.libraryBinaryPaths
case .clang(let target):
return target.libraryBinaryPaths
}
}
var resourceBundleInfoPlistPath: AbsolutePath? {
switch self {
case .swift(let target):
return target.resourceBundleInfoPlistPath
case .clang(let target):
return target.resourceBundleInfoPlistPath
}
}
}
/// Target description for a Clang target i.e. C language family target.
public final class ClangTargetBuildDescription {
/// The target described by this target.
public let target: ResolvedTarget
/// The underlying clang target.
public var clangTarget: ClangTarget {
return target.underlyingTarget as! ClangTarget
}
/// The tools version of the package that declared the target. This can
/// can be used to conditionalize semantically significant changes in how
/// a target is built.
public let toolsVersion: ToolsVersion
/// The build parameters.
let buildParameters: BuildParameters
/// The build environment.
var buildEnvironment: BuildEnvironment {
buildParameters.buildEnvironment
}
/// Path to the bundle generated for this module (if any).
var bundlePath: AbsolutePath? {
target.underlyingTarget.bundleName.map(buildParameters.bundlePath(named:))
}
/// The modulemap file for this target, if any.
public private(set) var moduleMap: AbsolutePath?
/// Path to the temporary directory for this target.
var tempsPath: AbsolutePath
/// The directory containing derived sources of this target.
///
/// These are the source files generated during the build.
private var derivedSources: Sources
/// Path to the resource accessor header file, if generated.
public private(set) var resourceAccessorHeaderFile: AbsolutePath?
/// Path to the resource Info.plist file, if generated.
public private(set) var resourceBundleInfoPlistPath: AbsolutePath?
/// The objects in this target.
public var objects: [AbsolutePath] {
return compilePaths().map({ $0.object })
}
/// Paths to the binary libraries the target depends on.
fileprivate(set) var libraryBinaryPaths: Set<AbsolutePath> = []
/// Any addition flags to be added. These flags are expected to be computed during build planning.
fileprivate var additionalFlags: [String] = []
/// The filesystem to operate on.
private let fileSystem: FileSystem
/// If this target is a test target.
public var isTestTarget: Bool {
return target.type == .test
}
/// Create a new target description with target and build parameters.
init(target: ResolvedTarget, toolsVersion: ToolsVersion, buildParameters: BuildParameters, fileSystem: FileSystem) throws {
guard target.underlyingTarget is ClangTarget else {
throw InternalError("underlying target type mismatch \(target)")
}
self.fileSystem = fileSystem
self.target = target
self.toolsVersion = toolsVersion
self.buildParameters = buildParameters
self.tempsPath = buildParameters.buildPath.appending(component: target.c99name + ".build")
self.derivedSources = Sources(paths: [], root: tempsPath.appending(component: "DerivedSources"))
// Try computing modulemap path for a C library. This also creates the file in the file system, if needed.
if target.type == .library {
// If there's a custom module map, use it as given.
if case .custom(let path) = clangTarget.moduleMapType {
self.moduleMap = path
}
// If a generated module map is needed, generate one now in our temporary directory.
else if let generatedModuleMapType = clangTarget.moduleMapType.generatedModuleMapType {
let path = tempsPath.appending(component: moduleMapFilename)
let moduleMapGenerator = ModuleMapGenerator(targetName: clangTarget.name, moduleName: clangTarget.c99name, publicHeadersDir: clangTarget.includeDir, fileSystem: fileSystem)
try moduleMapGenerator.generateModuleMap(type: generatedModuleMapType, at: path)
self.moduleMap = path
}
// Otherwise there is no module map, and we leave `moduleMap` unset.
}
// Do nothing if we're not generating a bundle.
if bundlePath != nil {
try self.generateResourceAccessor()
let infoPlistPath = tempsPath.appending(component: "Info.plist")
if try generateResourceInfoPlist(fileSystem: fileSystem, target: target, path: infoPlistPath) {
resourceBundleInfoPlistPath = infoPlistPath
}
}
}
/// An array of tuple containing filename, source, object and dependency path for each of the source in this target.
public func compilePaths()
-> [(filename: RelativePath, source: AbsolutePath, object: AbsolutePath, deps: AbsolutePath)]
{
let sources = [
target.sources.root: target.sources.relativePaths,
derivedSources.root: derivedSources.relativePaths,
]
return sources.flatMap { (root, relativePaths) in
relativePaths.map { source in
let path = root.appending(source)
let object = AbsolutePath("\(source.pathString).o", relativeTo: tempsPath)
let deps = AbsolutePath("\(source.pathString).d", relativeTo: tempsPath)
return (source, path, object, deps)
}
}
}
/// Builds up basic compilation arguments for a source file in this target; these arguments may be different for C++ vs non-C++.
/// NOTE: The parameter to specify whether to get C++ semantics is currently optional, but this is only for revlock avoidance with clients. Callers should always specify what they want based either the user's indication or on a default value (possibly based on the filename suffix).
public func basicArguments(isCXX isCXXOverride: Bool? = .none) throws -> [String] {
// For now fall back on the hold semantics if the C++ nature isn't specified. This is temporary until clients have been updated.
let isCXX = isCXXOverride ?? clangTarget.isCXX
var args = [String]()
// Only enable ARC on macOS.
if buildParameters.triple.isDarwin() {
args += ["-fobjc-arc"]
}
args += try buildParameters.targetTripleArgs(for: target)
args += ["-g"]
if buildParameters.triple.isWindows() {
args += ["-gcodeview"]
}
args += optimizationArguments
args += activeCompilationConditions
args += ["-fblocks"]
// Enable index store, if appropriate.
//
// This feature is not widely available in OSS clang. So, we only enable
// index store for Apple's clang or if explicitly asked to.
if ProcessEnv.vars.keys.contains("SWIFTPM_ENABLE_CLANG_INDEX_STORE") {
args += buildParameters.indexStoreArguments(for: target)
} else if buildParameters.triple.isDarwin(), (try? buildParameters.toolchain._isClangCompilerVendorApple()) == true {
args += buildParameters.indexStoreArguments(for: target)
}
// Enable Clang module flags, if appropriate.
let enableModules: Bool
if toolsVersion < .vNext {
// For version < 5.8, we enable them except in these cases:
// 1. on Darwin when compiling for C++, because C++ modules are disabled on Apple-built Clang releases
// 2. on Windows when compiling for any language, because of issues with the Windows SDK
// 3. on Android when compiling for any language, because of issues with the Android SDK
enableModules = !(buildParameters.triple.isDarwin() && isCXX) && !buildParameters.triple.isWindows() && !buildParameters.triple.isAndroid()
} else {
// For version >= 5.8, we disable them when compiling for C++ regardless of platforms, see:
// https://github.com/llvm/llvm-project/issues/55980 for clang frontend crash when module
// enabled for C++ on c++17 standard and above.
enableModules = !isCXX && !buildParameters.triple.isWindows() && !buildParameters.triple.isAndroid()
}
if enableModules {
// Using modules currently conflicts with the Windows and Android SDKs.
args += ["-fmodules", "-fmodule-name=" + target.c99name]
}
// Only add the build path to the framework search path if there are binary frameworks to link against.
if !libraryBinaryPaths.isEmpty {
args += ["-F", buildParameters.buildPath.pathString]
}
args += ["-I", clangTarget.includeDir.pathString]
args += additionalFlags
if enableModules {
args += moduleCacheArgs
}
args += buildParameters.sanitizers.compileCFlags()
// Add arguments from declared build settings.
args += self.buildSettingsFlags()
if let resourceAccessorHeaderFile = self.resourceAccessorHeaderFile {
args += ["-include", resourceAccessorHeaderFile.pathString]
}
args += buildParameters.toolchain.extraCCFlags
// User arguments (from -Xcc and -Xcxx below) should follow generated arguments to allow user overrides
args += buildParameters.flags.cCompilerFlags
// Add extra C++ flags if this target contains C++ files.
if clangTarget.isCXX {
args += self.buildParameters.flags.cxxCompilerFlags
}
return args
}
/// Returns the build flags from the declared build settings.
private func buildSettingsFlags() -> [String] {
let scope = buildParameters.createScope(for: target)
var flags: [String] = []
// C defines.
let cDefines = scope.evaluate(.GCC_PREPROCESSOR_DEFINITIONS)
flags += cDefines.map({ "-D" + $0 })
// Header search paths.
let headerSearchPaths = scope.evaluate(.HEADER_SEARCH_PATHS)
flags += headerSearchPaths.map({
"-I\(AbsolutePath($0, relativeTo: target.sources.root).pathString)"
})
// Other C flags.
flags += scope.evaluate(.OTHER_CFLAGS)
// Other CXX flags.
flags += scope.evaluate(.OTHER_CPLUSPLUSFLAGS)
return flags
}
/// Optimization arguments according to the build configuration.
private var optimizationArguments: [String] {
switch buildParameters.configuration {
case .debug:
return ["-O0"]
case .release:
return ["-O2"]
}
}
/// A list of compilation conditions to enable for conditional compilation expressions.
private var activeCompilationConditions: [String] {
var compilationConditions = ["-DSWIFT_PACKAGE=1"]
switch buildParameters.configuration {
case .debug:
compilationConditions += ["-DDEBUG=1"]
case .release:
break
}
return compilationConditions
}
/// Module cache arguments.
private var moduleCacheArgs: [String] {
return ["-fmodules-cache-path=\(buildParameters.moduleCache.pathString)"]
}
/// Generate the resource bundle accessor, if appropriate.
private func generateResourceAccessor() throws {
// Only generate access when we have a bundle and ObjC files.
guard let bundlePath = self.bundlePath, clangTarget.sources.containsObjcFiles else { return }
// Compute the basename of the bundle.
let bundleBasename = bundlePath.basename
let implFileStream = BufferedOutputByteStream()
implFileStream <<< """
#import <Foundation/Foundation.h>
NSBundle* \(target.c99name)_SWIFTPM_MODULE_BUNDLE() {
NSURL *bundleURL = [[[NSBundle mainBundle] bundleURL] URLByAppendingPathComponent:@"\(bundleBasename)"];
return [NSBundle bundleWithURL:bundleURL];
}
"""
let implFileSubpath = RelativePath("resource_bundle_accessor.m")
// Add the file to the derived sources.
derivedSources.relativePaths.append(implFileSubpath)
// Write this file out.
// FIXME: We should generate this file during the actual build.
try fileSystem.writeIfChanged(
path: derivedSources.root.appending(implFileSubpath),
bytes: implFileStream.bytes
)
let headerFileStream = BufferedOutputByteStream()
headerFileStream <<< """
#import <Foundation/Foundation.h>
#if __cplusplus
extern "C" {
#endif
NSBundle* \(target.c99name)_SWIFTPM_MODULE_BUNDLE(void);
#define SWIFTPM_MODULE_BUNDLE \(target.c99name)_SWIFTPM_MODULE_BUNDLE()
#if __cplusplus
}
#endif
"""
let headerFile = derivedSources.root.appending(component: "resource_bundle_accessor.h")
self.resourceAccessorHeaderFile = headerFile
try fileSystem.writeIfChanged(
path: headerFile,
bytes: headerFileStream.bytes
)
}
}
/// Target description for a Swift target.
public final class SwiftTargetBuildDescription {
/// The package this target belongs to.
public let package: ResolvedPackage
/// The target described by this target.
public let target: ResolvedTarget
/// The tools version of the package that declared the target. This can
/// can be used to conditionalize semantically significant changes in how
/// a target is built.
public let toolsVersion: ToolsVersion
/// The build parameters.
let buildParameters: BuildParameters
/// Path to the temporary directory for this target.
let tempsPath: AbsolutePath
/// The directory containing derived sources of this target.
///
/// These are the source files generated during the build.
private var derivedSources: Sources
/// These are the source files derived from plugins.
private var pluginDerivedSources: Sources
/// These are the resource files derived from plugins.
private var pluginDerivedResources: [Resource]
/// Path to the bundle generated for this module (if any).
var bundlePath: AbsolutePath? {
if let bundleName = target.underlyingTarget.potentialBundleName, !resources.isEmpty {
return buildParameters.bundlePath(named: bundleName)
} else {
return .none
}
}
/// The list of all source files in the target, including the derived ones.
public var sources: [AbsolutePath] {
target.sources.paths + derivedSources.paths + pluginDerivedSources.paths
}
/// The list of all resource files in the target, including the derived ones.
public var resources: [Resource] {
target.underlyingTarget.resources + pluginDerivedResources
}
/// The objects in this target.
public var objects: [AbsolutePath] {
let relativePaths = target.sources.relativePaths + derivedSources.relativePaths + pluginDerivedSources.relativePaths
return relativePaths.map {
AbsolutePath("\($0.pathString).o", relativeTo: tempsPath)
}
}
/// The path to the swiftmodule file after compilation.
var moduleOutputPath: AbsolutePath {
// If we're an executable and we're not allowing test targets to link against us, we hide the module.
let allowLinkingAgainstExecutables = (buildParameters.triple.isDarwin() || buildParameters.triple.isLinux() || buildParameters.triple.isWindows()) && toolsVersion >= .v5_5
let dirPath = (target.type == .executable && !allowLinkingAgainstExecutables) ? tempsPath : buildParameters.buildPath
return dirPath.appending(component: target.c99name + ".swiftmodule")
}
/// The path to the wrapped swift module which is created using the modulewrap tool. This is required
/// for supporting debugging on non-Darwin platforms (On Darwin, we just pass the swiftmodule to the linker
/// using the `-add_ast_path` flag).
var wrappedModuleOutputPath: AbsolutePath {
return tempsPath.appending(component: target.c99name + ".swiftmodule.o")
}
/// The path to the swifinterface file after compilation.
var parseableModuleInterfaceOutputPath: AbsolutePath {
return buildParameters.buildPath.appending(component: target.c99name + ".swiftinterface")
}
/// Path to the resource Info.plist file, if generated.
public private(set) var resourceBundleInfoPlistPath: AbsolutePath?
/// Paths to the binary libraries the target depends on.
fileprivate(set) var libraryBinaryPaths: Set<AbsolutePath> = []
/// Any addition flags to be added. These flags are expected to be computed during build planning.
fileprivate var additionalFlags: [String] = []
/// The swift version for this target.
var swiftVersion: SwiftLanguageVersion {
return (target.underlyingTarget as! SwiftTarget).swiftVersion
}
/// If this target is a test target.
public let isTestTarget: Bool
/// True if this is the test discovery target.
public let isTestDiscoveryTarget: Bool
/// True if this module needs to be parsed as a library based on the target type and the configuration
/// of the source code
var needsToBeParsedAsLibrary: Bool {
switch self.target.type {
case .library, .test:
return true
case .executable, .snippet:
// This deactivates heuristics in the Swift compiler that treats single-file modules and source files
// named "main.swift" specially w.r.t. whether they can have an entry point.
//
// See https://bugs.swift.org/browse/SR-14488 for discussion about improvements so that SwiftPM can
// convey the intent to build an executable module to the compiler regardless of the number of files
// in the module or their names.
if self.toolsVersion < .v5_5 || self.sources.count != 1 {
return false
}
// looking into the file content to see if it is using the @main annotation which requires parse-as-library
return (try? self.containsAtMain(fileSystem: self.fileSystem, path: self.sources[0])) ?? false
default:
return false
}
}
// looking into the file content to see if it is using the @main annotation
// this is not bullet-proof since theoretically the file can contain the @main string for other reasons
// but it is the closest to accurate we can do at this point
func containsAtMain(fileSystem: FileSystem, path: AbsolutePath) throws -> Bool {
let content: String = try self.fileSystem.readFileContents(path)
let lines = content.split(separator: "\n").compactMap { String($0).spm_chuzzle() }
var multilineComment = false
for line in lines {
if line.hasPrefix("//") {
continue
}
if line.hasPrefix("/*") {
multilineComment = true
}
if line.hasSuffix("*/") {
multilineComment = false
}
if multilineComment {
continue
}
if line.hasPrefix("@main") {
return true
}
}
return false
}
/// The filesystem to operate on.
let fileSystem: FileSystem
/// The modulemap file for this target, if any.
private(set) var moduleMap: AbsolutePath?
/// The results of applying any build tool plugins to this target.
public let buildToolPluginInvocationResults: [BuildToolPluginInvocationResult]
/// The results of running any prebuild commands for this target.
public let prebuildCommandResults: [PrebuildCommandResult]
/// ObservabilityScope with which to emit diagnostics
private let observabilityScope: ObservabilityScope
/// Create a new target description with target and build parameters.
init(
package: ResolvedPackage,
target: ResolvedTarget,
toolsVersion: ToolsVersion,
additionalFileRules: [FileRuleDescription] = [],
buildParameters: BuildParameters,
buildToolPluginInvocationResults: [BuildToolPluginInvocationResult] = [],
prebuildCommandResults: [PrebuildCommandResult] = [],
isTestTarget: Bool? = nil,
isTestDiscoveryTarget: Bool = false,
fileSystem: FileSystem,
observabilityScope: ObservabilityScope
) throws {
guard target.underlyingTarget is SwiftTarget else {
throw InternalError("underlying target type mismatch \(target)")
}
self.package = package
self.target = target
self.toolsVersion = toolsVersion
self.buildParameters = buildParameters
// Unless mentioned explicitly, use the target type to determine if this is a test target.
self.isTestTarget = isTestTarget ?? (target.type == .test)
self.isTestDiscoveryTarget = isTestDiscoveryTarget
self.fileSystem = fileSystem
self.tempsPath = buildParameters.buildPath.appending(component: target.c99name + ".build")
self.derivedSources = Sources(paths: [], root: tempsPath.appending(component: "DerivedSources"))
self.pluginDerivedSources = Sources(paths: [], root: buildParameters.dataPath)
self.buildToolPluginInvocationResults = buildToolPluginInvocationResults
self.prebuildCommandResults = prebuildCommandResults
self.observabilityScope = observabilityScope
// Add any derived files that were declared for any commands from plugin invocations.
var pluginDerivedFiles = [AbsolutePath]()
for command in buildToolPluginInvocationResults.reduce([], { $0 + $1.buildCommands }) {
for absPath in command.outputFiles {
pluginDerivedFiles.append(absPath)
}
}
// Add any derived files that were discovered from output directories of prebuild commands.
for result in self.prebuildCommandResults {
for path in result.derivedFiles {
pluginDerivedFiles.append(path)
}
}
// Let `TargetSourcesBuilder` compute the treatment of plugin generated files.
let (derivedSources, derivedResources) = TargetSourcesBuilder.computeContents(for: pluginDerivedFiles, toolsVersion: toolsVersion, additionalFileRules: additionalFileRules, defaultLocalization: target.defaultLocalization, targetName: target.name, targetPath: target.underlyingTarget.path, observabilityScope: observabilityScope)
self.pluginDerivedResources = derivedResources
derivedSources.forEach { absPath in
let relPath = absPath.relative(to: self.pluginDerivedSources.root)
self.pluginDerivedSources.relativePaths.append(relPath)
}
if shouldEmitObjCCompatibilityHeader {
self.moduleMap = try self.generateModuleMap()
}
// Do nothing if we're not generating a bundle.
if bundlePath != nil {
try self.generateResourceAccessor()
let infoPlistPath = tempsPath.appending(component: "Info.plist")
if try generateResourceInfoPlist(fileSystem: self.fileSystem, target: target, path: infoPlistPath) {
resourceBundleInfoPlistPath = infoPlistPath
}
}
}
/// Generate the resource bundle accessor, if appropriate.
private func generateResourceAccessor() throws {
// Do nothing if we're not generating a bundle.
guard let bundlePath = self.bundlePath else { return }
let mainPathSubstitution: String
if buildParameters.triple.isWASI() {
// We prefer compile-time evaluation of the bundle path here for WASI. There's no benefit in evaluating this at runtime,
// especially as Bundle support in WASI Foundation is partial. We expect all resource paths to evaluate to
// `/\(resourceBundleName)/\(resourcePath)`, which allows us to pass this path to JS APIs like `fetch` directly, or to
// `<img src=` HTML attributes. The resources are loaded from the server, and we can't hardcode the host part in the URL.
// Making URLs relative by starting them with `/\(resourceBundleName)` makes it work in the browser.
let mainPath = AbsolutePath(Bundle.main.bundlePath).appending(component: bundlePath.basename).pathString
mainPathSubstitution = #""\#(mainPath.asSwiftStringLiteralConstant)""#
} else {
mainPathSubstitution = #"Bundle.main.bundleURL.appendingPathComponent("\#(bundlePath.basename.asSwiftStringLiteralConstant)").path"#
}
let stream = BufferedOutputByteStream()
stream <<< """
import class Foundation.Bundle
extension Foundation.Bundle {
static var module: Bundle = {
let mainPath = \(mainPathSubstitution)
let buildPath = "\(bundlePath.pathString.asSwiftStringLiteralConstant)"
let preferredBundle = Bundle(path: mainPath)
guard let bundle = preferredBundle ?? Bundle(path: buildPath) else {
fatalError("could not load resource bundle: from \\(mainPath) or \\(buildPath)")
}
return bundle
}()
}
"""
let subpath = RelativePath("resource_bundle_accessor.swift")
// Add the file to the derived sources.
derivedSources.relativePaths.append(subpath)
// Write this file out.
// FIXME: We should generate this file during the actual build.
let path = derivedSources.root.appending(subpath)
try self.fileSystem.writeIfChanged(path: path, bytes: stream.bytes)
}
public static func checkSupportedFrontendFlags(flags: Set<String>, fileSystem: FileSystem) -> Bool {
do {
let executor = try SPMSwiftDriverExecutor(resolver: ArgsResolver(fileSystem: fileSystem), fileSystem: fileSystem, env: [:])
let driver = try Driver(args: ["swiftc"], executor: executor)
return driver.supportedFrontendFlags.intersection(flags) == flags
} catch {
return false
}
}
/// The arguments needed to compile this target.
public func compileArguments() throws -> [String] {
var args = [String]()
args += try buildParameters.targetTripleArgs(for: target)
args += ["-swift-version", swiftVersion.rawValue]
// Enable batch mode in debug mode.
//
// Technically, it should be enabled whenever WMO is off but we
// don't currently make that distinction in SwiftPM
switch buildParameters.configuration {
case .debug:
args += ["-enable-batch-mode"]
case .release: break
}
args += buildParameters.indexStoreArguments(for: target)
args += optimizationArguments
args += testingArguments
args += ["-g"]
args += ["-j\(buildParameters.jobs)"]
args += activeCompilationConditions
args += additionalFlags
args += moduleCacheArgs
args += stdlibArguments
args += buildParameters.sanitizers.compileSwiftFlags()
args += ["-parseable-output"]
// If we're compiling the main module of an executable other than the one that
// implements a test suite, and if the package tools version indicates that we
// should, we rename the `_main` entry point to `_<modulename>_main`.
//
// This will allow tests to link against the module without any conflicts. And
// when we link the executable, we will ask the linker to rename the entry point
// symbol to just `_main` again (or if the linker doesn't support it, we'll
// generate a source containing a redirect).
if (target.type == .executable || target.type == .snippet)
&& !isTestTarget && toolsVersion >= .v5_5 {
// We only do this if the linker supports it, as indicated by whether we
// can construct the linker flags. In the future we will use a generated
// code stub for the cases in which the linker doesn't support it, so that
// we can rename the symbol unconditionally.
// No `-` for these flags because the set of Strings in driver.supportedFrontendFlags do
// not have a leading `-`
if buildParameters.canRenameEntrypointFunctionName,
buildParameters.linkerFlagsForRenamingMainFunction(of: target) != nil {
args += ["-Xfrontend", "-entry-point-function-name", "-Xfrontend", "\(target.c99name)_main"]
}
}
// If the target needs to be parsed without any special semantics involving "main.swift", do so now.
if self.needsToBeParsedAsLibrary {
args += ["-parse-as-library"]
}
// Only add the build path to the framework search path if there are binary frameworks to link against.
if !libraryBinaryPaths.isEmpty {
args += ["-F", buildParameters.buildPath.pathString]
}
// Emit the ObjC compatibility header if enabled.
if shouldEmitObjCCompatibilityHeader {
args += ["-emit-objc-header", "-emit-objc-header-path", objCompatibilityHeaderPath.pathString]
}
// Add arguments needed for code coverage if it is enabled.
if buildParameters.enableCodeCoverage {
args += ["-profile-coverage-mapping", "-profile-generate"]
}
// Add arguments to colorize output if stdout is tty
if buildParameters.colorizedOutput {
args += ["-color-diagnostics"]
}
// Add arguments from declared build settings.
args += self.buildSettingsFlags()
// Add the output for the `.swiftinterface`, if requested or if library evolution has been enabled some other way.
if buildParameters.enableParseableModuleInterfaces || args.contains("-enable-library-evolution") {
args += ["-emit-module-interface-path", parseableModuleInterfaceOutputPath.pathString]
}
args += buildParameters.toolchain.extraSwiftCFlags
// User arguments (from -Xswiftc) should follow generated arguments to allow user overrides
args += buildParameters.swiftCompilerFlags
// suppress warnings if the package is remote
if self.package.isRemote {
args += ["-suppress-warnings"]
// suppress-warnings and warnings-as-errors are mutually exclusive
if let index = args.firstIndex(of: "-warnings-as-errors") {
args.remove(at: index)
}
}
return args
}
/// When `scanInvocation` argument is set to `true`, omit the side-effect producing arguments
/// such as emitting a module or supplementary outputs.
public func emitCommandLine(scanInvocation: Bool = false) throws -> [String] {
var result: [String] = []
result.append(buildParameters.toolchain.swiftCompilerPath.pathString)
result.append("-module-name")
result.append(target.c99name)
if !scanInvocation {
result.append("-emit-dependencies")
// FIXME: Do we always have a module?
result.append("-emit-module")
result.append("-emit-module-path")
result.append(moduleOutputPath.pathString)
result.append("-output-file-map")
// FIXME: Eliminate side effect.
result.append(try writeOutputFileMap().pathString)
}
if buildParameters.useWholeModuleOptimization {
result.append("-whole-module-optimization")
result.append("-num-threads")
result.append(String(ProcessInfo.processInfo.activeProcessorCount))
} else {
result.append("-incremental")
}
result.append("-c")
result.append(contentsOf: sources.map { $0.pathString })
result.append("-I")
result.append(buildParameters.buildPath.pathString)
result += try self.compileArguments()
return result
}
/// Command-line for emitting just the Swift module.
public func emitModuleCommandLine() throws -> [String] {
guard buildParameters.emitSwiftModuleSeparately else {
throw InternalError("expecting emitSwiftModuleSeparately in build parameters")
}
var result: [String] = []
result.append(buildParameters.toolchain.swiftCompilerPath.pathString)
result.append("-module-name")
result.append(target.c99name)
result.append("-emit-module")
result.append("-emit-module-path")
result.append(moduleOutputPath.pathString)
result += buildParameters.toolchain.extraSwiftCFlags
result.append("-Xfrontend")
result.append("-experimental-skip-non-inlinable-function-bodies")
result.append("-force-single-frontend-invocation")
// FIXME: Handle WMO
for source in target.sources.paths {
result.append(source.pathString)
}
result.append("-I")
result.append(buildParameters.buildPath.pathString)