forked from apple/swift-driver
/
Driver.swift
2157 lines (1857 loc) · 80.6 KB
/
Driver.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
//===--------------- Driver.swift - Swift Driver --------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2019 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
import TSCBasic
import TSCUtility
import Foundation
import SwiftOptions
/// The Swift driver.
public struct Driver {
public enum Error: Swift.Error, Equatable, DiagnosticData {
case invalidDriverName(String)
case invalidInput(String)
case noInputFiles
case invalidArgumentValue(String, String)
case relativeFrontendPath(String)
case subcommandPassedToDriver
case integratedReplRemoved
case conflictingOptions(Option, Option)
case unableToLoadOutputFileMap(String)
case unableToDecodeFrontendTargetInfo(String?, [String], String)
case failedToRetrieveFrontendTargetInfo
case failedToRunFrontendToRetrieveTargetInfo(Int, String?)
case unableToReadFrontendTargetInfo
case missingProfilingData(String)
case conditionalCompilationFlagHasRedundantPrefix(String)
case conditionalCompilationFlagIsNotValidIdentifier(String)
// Explicit Module Build Failures
case malformedModuleDependency(String, String)
case missingPCMArguments(String)
case missingModuleDependency(String)
case dependencyScanningFailure(Int, String)
case missingExternalDependency(String)
public var description: String {
switch self {
case .invalidDriverName(let driverName):
return "invalid driver name: \(driverName)"
case .invalidInput(let input):
return "invalid input: \(input)"
case .noInputFiles:
return "no input files"
case .invalidArgumentValue(let option, let value):
return "invalid value '\(value)' in '\(option)'"
case .relativeFrontendPath(let path):
// TODO: where is this error thrown
return "relative frontend path: \(path)"
case .subcommandPassedToDriver:
return "subcommand passed to driver"
case .integratedReplRemoved:
return "Compiler-internal integrated REPL has been removed; use the LLDB-enhanced REPL instead."
case .conflictingOptions(let one, let two):
return "conflicting options '\(one.spelling)' and '\(two.spelling)'"
case let .unableToDecodeFrontendTargetInfo(outputString, arguments, errorDesc):
let output = outputString.map { ": \"\($0)\""} ?? ""
return """
could not decode frontend target info; compiler driver and frontend executables may be incompatible
details: frontend: \(arguments.first ?? "")
arguments: \(arguments.dropFirst())
error: \(errorDesc)
output\n\(output)
"""
case .failedToRetrieveFrontendTargetInfo:
return "failed to retrieve frontend target info"
case .unableToReadFrontendTargetInfo:
return "could not read frontend target info"
case let .failedToRunFrontendToRetrieveTargetInfo(returnCode, stderr):
return "frontend job retrieving target info failed with code \(returnCode)"
+ (stderr.map {": \($0)"} ?? "")
case .missingProfilingData(let arg):
return "no profdata file exists at '\(arg)'"
case .conditionalCompilationFlagHasRedundantPrefix(let name):
return "invalid argument '-D\(name)'; did you provide a redundant '-D' in your build settings?"
case .conditionalCompilationFlagIsNotValidIdentifier(let name):
return "conditional compilation flags must be valid Swift identifiers (rather than '\(name)')"
// Explicit Module Build Failures
case .malformedModuleDependency(let moduleName, let errorDescription):
return "Malformed Module Dependency: \(moduleName), \(errorDescription)"
case .missingPCMArguments(let moduleName):
return "Missing extraPcmArgs to build Clang module: \(moduleName)"
case .missingModuleDependency(let moduleName):
return "Missing Module Dependency Info: \(moduleName)"
case .dependencyScanningFailure(let code, let error):
return "Module Dependency Scanner returned with non-zero exit status: \(code), \(error)"
case .unableToLoadOutputFileMap(let path):
return "unable to load output file map '\(path)': no such file or directory"
case .missingExternalDependency(let moduleName):
return "Missing External dependency info for module: \(moduleName)"
}
}
}
/// The set of environment variables that are visible to the driver and
/// processes it launches. This is a hook for testing; in actual use
/// it should be identical to the real environment.
public let env: [String: String]
/// The file system which we should interact with.
let fileSystem: FileSystem
/// Diagnostic engine for emitting warnings, errors, etc.
public let diagnosticEngine: DiagnosticsEngine
/// The executor the driver uses to run jobs.
let executor: DriverExecutor
/// The toolchain to use for resolution.
@_spi(Testing) public let toolchain: Toolchain
/// Information about the target, as reported by the Swift frontend.
@_spi(Testing) public let frontendTargetInfo: FrontendTargetInfo
/// The target triple.
@_spi(Testing) public var targetTriple: Triple { frontendTargetInfo.target.triple }
/// The variant target triple.
var targetVariantTriple: Triple? {
frontendTargetInfo.targetVariant?.triple
}
/// The kind of driver.
let driverKind: DriverKind
/// The option table we're using.
let optionTable: OptionTable
/// The set of parsed options.
var parsedOptions: ParsedOptions
/// Whether to print out extra info regarding jobs
let showJobLifecycle: Bool
/// Extra command-line arguments to pass to the Swift compiler.
let swiftCompilerPrefixArgs: [String]
/// The working directory for the driver, if there is one.
let workingDirectory: AbsolutePath?
/// The set of input files
@_spi(Testing) public let inputFiles: [TypedVirtualPath]
/// The last time each input file was modified, recorded at the start of the build.
@_spi(Testing) public let recordedInputModificationDates: [TypedVirtualPath: Date]
/// The mapping from input files to output files for each kind.
let outputFileMap: OutputFileMap?
/// The number of files required before making a file list.
let fileListThreshold: Int
/// Should use file lists for inputs (number of inputs exceeds `fileListThreshold`).
let shouldUseInputFileList: Bool
/// VirtualPath for shared all sources file list. `nil` if unused.
let allSourcesFileList: VirtualPath?
/// The mode in which the compiler will execute.
@_spi(Testing) public let compilerMode: CompilerMode
/// The type of the primary output generated by the compiler.
@_spi(Testing) public let compilerOutputType: FileType?
/// The type of the link-time-optimization we expect to perform.
@_spi(Testing) public let lto: LTOKind?
/// The type of the primary output generated by the linker.
@_spi(Testing) public let linkerOutputType: LinkOutputType?
/// When > 0, the number of threads to use in a multithreaded build.
@_spi(Testing) public let numThreads: Int
/// The specified maximum number of parallel jobs to execute.
@_spi(Testing) public let numParallelJobs: Int?
/// The set of sanitizers that were requested
let enabledSanitizers: Set<Sanitizer>
/// The debug information to produce.
@_spi(Testing) public let debugInfo: DebugInfo
// The information about the module to produce.
@_spi(Testing) public let moduleOutputInfo: ModuleOutputInfo
/// Info needed to write and maybe read the build record.
/// Only present when the driver will be writing the record.
/// Only used for reading when compiling incrementally.
@_spi(Testing) public let buildRecordInfo: BuildRecordInfo?
/// Code & data for incremental compilation. Nil if not running in incremental mode
@_spi(Testing) public let incrementalCompilationState: IncrementalCompilationState?
/// The path of the SDK.
public var absoluteSDKPath: AbsolutePath? {
switch frontendTargetInfo.sdkPath?.path {
case .absolute(let path):
return path
case .relative(let path):
let cwd = workingDirectory ?? fileSystem.currentWorkingDirectory
return cwd.map { AbsolutePath($0, path) }
case nil:
return nil
case .standardInput, .standardOutput, .temporary, .temporaryWithKnownContents, .fileList:
fatalError("Frontend target information will never include a path of this type.")
}
}
/// The path to the imported Objective-C header.
let importedObjCHeader: VirtualPath?
/// The path to the pch for the imported Objective-C header.
let bridgingPrecompiledHeader: VirtualPath?
/// Path to the dependencies file.
let dependenciesFilePath: VirtualPath?
/// Path to the serialized diagnostics file.
let serializedDiagnosticsFilePath: VirtualPath?
/// Path to the Objective-C generated header.
let objcGeneratedHeaderPath: VirtualPath?
/// Path to the loaded module trace file.
let loadedModuleTracePath: VirtualPath?
/// Path to the TBD file (text-based dylib).
let tbdPath: VirtualPath?
/// Path to the module documentation file.
let moduleDocOutputPath: VirtualPath?
/// Path to the Swift interface file.
let swiftInterfacePath: VirtualPath?
/// Path to the optimization record.
let optimizationRecordPath: VirtualPath?
/// Path to the Swift module source information file.
let moduleSourceInfoPath: VirtualPath?
/// If the driver should force emit module in a single invocation.
///
/// This will force the driver to first emit the module and then run compile jobs.
var forceEmitModuleInSingleInvocation: Bool = false
/// Handler for constructing module build jobs using Explicit Module Builds.
/// Constructed during the planning phase only when all modules will be prebuilt and treated
/// as explicit by the various compilation jobs.
@_spi(Testing) public var explicitModuleBuildHandler: ExplicitModuleBuildHandler? = nil
/// All external artifacts a build system (e.g. SwiftPM) may pass in as input to the explicit
/// build of the current module. Consists of a map of externally-built targets, and a map of all previously
/// discovered/scanned modules and their infos.
@_spi(Testing) public var externalBuildArtifacts: ExternalBuildArtifacts? = nil
/// Handler for emitting diagnostics to stderr.
public static let stderrDiagnosticsHandler: DiagnosticsEngine.DiagnosticsHandler = { diagnostic in
let stream = stderrStream
if !(diagnostic.location is UnknownLocation) {
stream <<< diagnostic.location.description <<< ": "
}
switch diagnostic.message.behavior {
case .error:
stream <<< "error: "
case .warning:
stream <<< "warning: "
case .note:
stream <<< "note: "
case .remark:
stream <<< "remark: "
case .ignored:
break
}
stream <<< diagnostic.localizedDescription <<< "\n"
stream.flush()
}
/// Create the driver with the given arguments.
///
/// - Parameter args: The command-line arguments, including the "swift" or "swiftc"
/// at the beginning.
/// - Parameter env: The environment variables to use. This is a hook for testing;
/// in production, you should use the default argument, which copies the current environment.
/// - Parameter diagnosticsEngine: The diagnotic engine used by the driver to emit errors
/// and warnings.
/// - Parameter fileSystem: The filesystem used by the driver to find resources/SDKs,
/// expand response files, etc. By default this is the local filesystem.
/// - Parameter executor: Used by the driver to execute jobs. The default argument
/// is present to streamline testing, it shouldn't be used in production.
/// - Parameter externalBuildArtifacts: All external artifacts a build system may pass in as input to the explicit
/// build of the current module. Consists of a map of externally-built targets, and a map of all previously
/// discovered/scanned modules.
public init(
args: [String],
env: [String: String] = ProcessEnv.vars,
diagnosticsEngine: DiagnosticsEngine = DiagnosticsEngine(handlers: [Driver.stderrDiagnosticsHandler]),
fileSystem: FileSystem = localFileSystem,
executor: DriverExecutor,
externalBuildArtifacts: ExternalBuildArtifacts? = nil
) throws {
self.env = env
self.fileSystem = fileSystem
self.diagnosticEngine = diagnosticsEngine
self.executor = executor
self.externalBuildArtifacts = externalBuildArtifacts
if case .subcommand = try Self.invocationRunMode(forArgs: args).mode {
throw Error.subcommandPassedToDriver
}
var args = try Self.expandResponseFiles(args, fileSystem: fileSystem, diagnosticsEngine: self.diagnosticEngine)
self.driverKind = try Self.determineDriverKind(args: &args)
self.optionTable = OptionTable()
self.parsedOptions = try optionTable.parse(Array(args), for: self.driverKind)
self.showJobLifecycle = parsedOptions.contains(.driverShowJobLifecycle)
// Determine the compilation mode.
self.compilerMode = try Self.computeCompilerMode(&parsedOptions, driverKind: driverKind, diagnosticsEngine: diagnosticEngine)
// Compute the working directory.
workingDirectory = try parsedOptions.getLastArgument(.workingDirectory).map { workingDirectoryArg in
let cwd = fileSystem.currentWorkingDirectory
return try cwd.map{ AbsolutePath(workingDirectoryArg.asSingle, relativeTo: $0) } ?? AbsolutePath(validating: workingDirectoryArg.asSingle)
}
// Apply the working directory to the parsed options.
if let workingDirectory = self.workingDirectory {
try Self.applyWorkingDirectory(workingDirectory, to: &self.parsedOptions)
}
// Build the toolchain and determine target information.
(self.toolchain, self.frontendTargetInfo, self.swiftCompilerPrefixArgs) =
try Self.computeToolchain(
&self.parsedOptions, diagnosticsEngine: diagnosticEngine,
compilerMode: self.compilerMode, env: env,
executor: self.executor, fileSystem: fileSystem)
// Classify and collect all of the input files.
let inputFiles = try Self.collectInputFiles(&self.parsedOptions)
self.inputFiles = inputFiles
self.recordedInputModificationDates = .init(uniqueKeysWithValues:
Set(inputFiles).compactMap {
guard let modTime = try? fileSystem
.getFileInfo($0.file).modTime else { return nil }
return ($0, modTime)
})
let outputFileMap: OutputFileMap?
// Initialize an empty output file map, which will be populated when we start creating jobs.
if let outputFileMapArg = parsedOptions.getLastArgument(.outputFileMap)?.asSingle {
do {
let path = try VirtualPath(path: outputFileMapArg)
outputFileMap = try .load(fileSystem: fileSystem, file: path, diagnosticEngine: diagnosticEngine)
} catch {
throw Error.unableToLoadOutputFileMap(outputFileMapArg)
}
} else {
outputFileMap = nil
}
if let workingDirectory = self.workingDirectory {
self.outputFileMap = outputFileMap?.resolveRelativePaths(relativeTo: workingDirectory)
} else {
self.outputFileMap = outputFileMap
}
// If requested, print the output file map
if parsedOptions.contains(.driverPrintOutputFileMap) {
if let outputFileMap = self.outputFileMap {
stderrStream <<< outputFileMap.description
stderrStream.flush()
} else {
diagnosticsEngine.emit(.error_no_output_file_map_specified)
}
}
self.fileListThreshold = try Self.computeFileListThreshold(&self.parsedOptions, diagnosticsEngine: diagnosticsEngine)
self.shouldUseInputFileList = inputFiles.count > fileListThreshold
if shouldUseInputFileList {
let swiftInputs = inputFiles.filter(\.type.isPartOfSwiftCompilation)
let path = RelativePath(createTemporaryFileName(prefix: "sources"))
self.allSourcesFileList = .fileList(path, .list(swiftInputs.map(\.file)))
} else {
self.allSourcesFileList = nil
}
self.lto = Self.ltoKind(&parsedOptions, diagnosticsEngine: diagnosticsEngine)
// Figure out the primary outputs from the driver.
(self.compilerOutputType, self.linkerOutputType) = Self.determinePrimaryOutputs(&parsedOptions, driverKind: driverKind, diagnosticsEngine: diagnosticEngine)
// Multithreading.
self.numThreads = Self.determineNumThreads(&parsedOptions, compilerMode: compilerMode, diagnosticsEngine: diagnosticEngine)
self.numParallelJobs = Self.determineNumParallelJobs(&parsedOptions, diagnosticsEngine: diagnosticEngine, env: env)
Self.validateWarningControlArgs(&parsedOptions, diagnosticEngine: diagnosticEngine)
Self.validateProfilingArgs(&parsedOptions,
fileSystem: fileSystem,
workingDirectory: workingDirectory,
diagnosticEngine: diagnosticEngine)
Self.validateCompilationConditionArgs(&parsedOptions, diagnosticEngine: diagnosticEngine)
Self.validateFrameworkSearchPathArgs(&parsedOptions, diagnosticEngine: diagnosticEngine)
Self.validateCoverageArgs(&parsedOptions, diagnosticsEngine: diagnosticEngine)
try toolchain.validateArgs(&parsedOptions,
targetTriple: self.frontendTargetInfo.target.triple,
targetVariantTriple: self.frontendTargetInfo.targetVariant?.triple,
diagnosticsEngine: diagnosticEngine)
// Compute debug information output.
self.debugInfo = Self.computeDebugInfo(&parsedOptions, diagnosticsEngine: diagnosticEngine)
// Determine the module we're building and whether/how the module file itself will be emitted.
self.moduleOutputInfo = try Self.computeModuleInfo(
&parsedOptions, compilerOutputType: compilerOutputType, compilerMode: compilerMode, linkerOutputType: linkerOutputType,
debugInfoLevel: debugInfo.level, diagnosticsEngine: diagnosticEngine,
workingDirectory: self.workingDirectory)
self.buildRecordInfo = BuildRecordInfo(
actualSwiftVersion: self.frontendTargetInfo.compilerVersion,
compilerOutputType: compilerOutputType,
diagnosticEngine: diagnosticEngine,
fileSystem: fileSystem,
moduleOutputInfo: moduleOutputInfo,
outputFileMap: outputFileMap,
parsedOptions: parsedOptions,
recordedInputModificationDates: recordedInputModificationDates)
// Determine the state for incremental compilation
self.incrementalCompilationState = IncrementalCompilationState(
buildRecordInfo: buildRecordInfo,
compilerMode: compilerMode,
diagnosticEngine: diagnosticEngine,
fileSystem: fileSystem,
inputFiles: inputFiles,
outputFileMap: outputFileMap,
parsedOptions: &parsedOptions,
showJobLifecycle: showJobLifecycle)
// Local variable to alias the target triple, because self.targetTriple
// is not available until the end of this initializer.
let targetTriple = self.frontendTargetInfo.target.triple
self.importedObjCHeader = try Self.computeImportedObjCHeader(&parsedOptions, compilerMode: compilerMode, diagnosticEngine: diagnosticEngine)
self.bridgingPrecompiledHeader = try Self.computeBridgingPrecompiledHeader(&parsedOptions,
compilerMode: compilerMode,
importedObjCHeader: importedObjCHeader,
outputFileMap: outputFileMap)
self.enabledSanitizers = try Self.parseSanitizerArgValues(
&parsedOptions,
diagnosticEngine: diagnosticEngine,
toolchain: toolchain,
targetTriple: targetTriple)
// Supplemental outputs.
self.dependenciesFilePath = try Self.computeSupplementaryOutputPath(
&parsedOptions, type: .dependencies, isOutputOptions: [.emitDependencies],
outputPath: .emitDependenciesPath,
compilerOutputType: compilerOutputType,
compilerMode: compilerMode,
outputFileMap: self.outputFileMap,
moduleName: moduleOutputInfo.name)
self.serializedDiagnosticsFilePath = try Self.computeSupplementaryOutputPath(
&parsedOptions, type: .diagnostics, isOutputOptions: [.serializeDiagnostics],
outputPath: .serializeDiagnosticsPath,
compilerOutputType: compilerOutputType,
compilerMode: compilerMode,
outputFileMap: self.outputFileMap,
moduleName: moduleOutputInfo.name)
// FIXME: -fixits-output-path
self.objcGeneratedHeaderPath = try Self.computeSupplementaryOutputPath(
&parsedOptions, type: .objcHeader, isOutputOptions: [.emitObjcHeader],
outputPath: .emitObjcHeaderPath,
compilerOutputType: compilerOutputType,
compilerMode: compilerMode,
outputFileMap: self.outputFileMap,
moduleName: moduleOutputInfo.name)
if let loadedModuleTraceEnvVar = env["SWIFT_LOADED_MODULE_TRACE_FILE"] {
self.loadedModuleTracePath = try VirtualPath(path: loadedModuleTraceEnvVar)
} else {
self.loadedModuleTracePath = try Self.computeSupplementaryOutputPath(
&parsedOptions, type: .moduleTrace, isOutputOptions: [.emitLoadedModuleTrace],
outputPath: .emitLoadedModuleTracePath,
compilerOutputType: compilerOutputType,
compilerMode: compilerMode,
outputFileMap: self.outputFileMap,
moduleName: moduleOutputInfo.name)
}
self.tbdPath = try Self.computeSupplementaryOutputPath(
&parsedOptions, type: .tbd, isOutputOptions: [.emitTbd],
outputPath: .emitTbdPath,
compilerOutputType: compilerOutputType,
compilerMode: compilerMode,
outputFileMap: self.outputFileMap,
moduleName: moduleOutputInfo.name)
self.moduleDocOutputPath = try Self.computeModuleDocOutputPath(
&parsedOptions, moduleOutputPath: self.moduleOutputInfo.output?.outputPath,
compilerOutputType: compilerOutputType,
compilerMode: compilerMode,
outputFileMap: self.outputFileMap,
moduleName: moduleOutputInfo.name)
let projectDirectory = Self.computeProjectDirectoryPath(
moduleOutputPath: self.moduleOutputInfo.output?.outputPath,
fileSystem: self.fileSystem)
self.moduleSourceInfoPath = try Self.computeModuleSourceInfoOutputPath(
&parsedOptions,
moduleOutputPath: self.moduleOutputInfo.output?.outputPath,
compilerOutputType: compilerOutputType,
compilerMode: compilerMode,
outputFileMap: self.outputFileMap,
moduleName: moduleOutputInfo.name,
projectDirectory: projectDirectory)
self.swiftInterfacePath = try Self.computeSupplementaryOutputPath(
&parsedOptions, type: .swiftInterface, isOutputOptions: [.emitModuleInterface],
outputPath: .emitModuleInterfacePath,
compilerOutputType: compilerOutputType,
compilerMode: compilerMode,
outputFileMap: self.outputFileMap,
moduleName: moduleOutputInfo.name)
var optimizationRecordFileType = FileType.yamlOptimizationRecord
if let argument = parsedOptions.getLastArgument(.saveOptimizationRecordEQ)?.asSingle {
switch argument {
case "yaml":
optimizationRecordFileType = .yamlOptimizationRecord
case "bitstream":
optimizationRecordFileType = .bitstreamOptimizationRecord
default:
// Don't report an error here, it will be emitted by the frontend.
break
}
}
self.optimizationRecordPath = try Self.computeSupplementaryOutputPath(
&parsedOptions, type: optimizationRecordFileType,
isOutputOptions: [.saveOptimizationRecord, .saveOptimizationRecordEQ],
outputPath: .saveOptimizationRecordPath,
compilerOutputType: compilerOutputType,
compilerMode: compilerMode,
outputFileMap: self.outputFileMap,
moduleName: moduleOutputInfo.name)
}
}
extension Driver {
public enum InvocationRunMode: Equatable {
case normal(isRepl: Bool)
case subcommand(String)
}
/// Determines whether the given arguments constitute a normal invocation,
/// or whether they invoke a subcommand.
///
/// - Returns: the invocation mode along with the arguments modified for that mode.
public static func invocationRunMode(
forArgs args: [String]
) throws -> (mode: InvocationRunMode, args: [String]) {
assert(!args.isEmpty)
let execName = try VirtualPath(path: args[0]).basenameWithoutExt
// If we are not run as 'swift' or 'swiftc' or there are no program arguments, always invoke as normal.
guard execName == "swift" || execName == "swiftc", args.count > 1 else {
return (.normal(isRepl: false), args)
}
// Otherwise, we have a program argument.
let firstArg = args[1]
var updatedArgs = args
// Check for flags associated with frontend tools.
if firstArg == "-frontend" {
updatedArgs.replaceSubrange(0...1, with: ["swift-frontend"])
return (.subcommand("swift-frontend"), updatedArgs)
}
if firstArg == "-modulewrap" {
updatedArgs[0] = "swift-frontend"
return (.subcommand("swift-frontend"), updatedArgs)
}
// Only 'swift' supports subcommands.
guard execName == "swift" else {
return (.normal(isRepl: false), args)
}
// If it looks like an option or a path, then invoke in interactive mode with the arguments as given.
if firstArg.hasPrefix("-") || firstArg.hasPrefix("/") || firstArg.contains(".") {
return (.normal(isRepl: false), args)
}
// Otherwise, we should have some sort of subcommand.
// If it is the "built-in" 'repl', then use the normal driver.
if firstArg == "repl" {
updatedArgs.remove(at: 1)
return (.normal(isRepl: true), updatedArgs)
}
let subcommand = "swift-\(firstArg)"
updatedArgs.replaceSubrange(0...1, with: [subcommand])
return (.subcommand(subcommand), updatedArgs)
}
}
extension Driver {
private static func ltoKind(_ parsedOptions: inout ParsedOptions,
diagnosticsEngine: DiagnosticsEngine) -> LTOKind? {
guard let arg = parsedOptions.getLastArgument(.lto)?.asSingle else { return nil }
guard let kind = LTOKind(rawValue: arg) else {
diagnosticsEngine.emit(.error_invalid_arg_value(arg: .lto, value: arg))
return nil
}
return kind
}
}
// MARK: - Response files.
extension Driver {
/// Tokenize a single line in a response file.
///
/// This method supports response files with:
/// 1. Double slash comments at the beginning of a line.
/// 2. Backslash escaping.
/// 3. Shell Quoting
///
/// - Returns: An array of 0 or more command line arguments
///
/// - Complexity: O(*n*), where *n* is the length of the line.
private static func tokenizeResponseFileLine<S: StringProtocol>(_ line: S) -> [String] {
// Support double dash comments only if they start at the beginning of a line.
if line.hasPrefix("//") { return [] }
var tokens: [String] = []
var token: String = ""
// Conservatively assume ~1 token per line.
token.reserveCapacity(line.count)
// Indicates if we just parsed an escaping backslash.
var isEscaping = false
// Indicates if we are currently parsing quoted text.
var quoted = false
for char in line {
// Backslash escapes to the next character.
if char == #"\"#, !isEscaping {
isEscaping = true
continue
} else if isEscaping {
// Disable escaping and keep parsing.
isEscaping = false
} else if char.isShellQuote {
// If an unescaped shell quote appears, begin or end quoting.
quoted.toggle()
continue
} else if char.isWhitespace && !quoted {
// This is unquoted, unescaped whitespace, start a new token.
if !token.isEmpty {
tokens.append(token)
token = ""
}
continue
}
token.append(char)
}
// Add the final token
if !token.isEmpty {
tokens.append(token)
}
return tokens
}
/// Tokenize each line of the response file, omitting empty lines.
///
/// - Parameter content: response file's content to be tokenized.
private static func tokenizeResponseFile(_ content: String) -> [String] {
#if !os(macOS) && !os(Linux) && !os(Android)
#warning("Response file tokenization unimplemented for platform; behavior may be incorrect")
#endif
return content.split { $0 == "\n" || $0 == "\r\n" }
.flatMap { tokenizeResponseFileLine($0) }
}
/// Recursively expands the response files.
/// - Parameter visitedResponseFiles: Set containing visited response files to detect recursive parsing.
private static func expandResponseFiles(
_ args: [String],
fileSystem: FileSystem,
diagnosticsEngine: DiagnosticsEngine,
visitedResponseFiles: inout Set<AbsolutePath>
) throws -> [String] {
var result: [String] = []
// Go through each arg and add arguments from response files.
for arg in args {
if arg.first == "@", let responseFile = try? AbsolutePath(validating: String(arg.dropFirst())) {
// Guard against infinite parsing loop.
guard visitedResponseFiles.insert(responseFile).inserted else {
diagnosticsEngine.emit(.warn_recursive_response_file(responseFile))
continue
}
defer {
visitedResponseFiles.remove(responseFile)
}
let contents = try fileSystem.readFileContents(responseFile).cString
let lines = tokenizeResponseFile(contents)
result.append(contentsOf: try expandResponseFiles(lines, fileSystem: fileSystem, diagnosticsEngine: diagnosticsEngine, visitedResponseFiles: &visitedResponseFiles))
} else {
result.append(arg)
}
}
return result
}
/// Expand response files in the input arguments and return a new argument list.
@_spi(Testing) public static func expandResponseFiles(
_ args: [String],
fileSystem: FileSystem,
diagnosticsEngine: DiagnosticsEngine
) throws -> [String] {
var visitedResponseFiles = Set<AbsolutePath>()
return try expandResponseFiles(args, fileSystem: fileSystem, diagnosticsEngine: diagnosticsEngine, visitedResponseFiles: &visitedResponseFiles)
}
}
extension Diagnostic.Message {
static func warn_unused_option(_ option: ParsedOption) -> Diagnostic.Message {
.warning("Unused option: \(option)")
}
}
extension Driver {
/// Determine the driver kind based on the command-line arguments, consuming the arguments
/// conveying this information.
@_spi(Testing) public static func determineDriverKind(
args: inout [String]
) throws -> DriverKind {
// Get the basename of the driver executable.
let execRelPath = args.removeFirst()
var driverName = try VirtualPath(path: execRelPath).basenameWithoutExt
// Determine if the driver kind is being overriden.
let driverModeOption = "--driver-mode="
if let firstArg = args.first, firstArg.hasPrefix(driverModeOption) {
args.removeFirst()
driverName = String(firstArg.dropFirst(driverModeOption.count))
}
switch driverName {
case "swift":
return .interactive
case "swiftc":
return .batch
default:
throw Error.invalidDriverName(driverName)
}
}
/// Run the driver.
public mutating func run(
jobs: [Job]
) throws {
if parsedOptions.hasArgument(.v) {
try printVersion(outputStream: &stderrStream)
}
let forceResponseFiles = parsedOptions.contains(.driverForceResponseFiles)
// If we're only supposed to print the jobs, do so now.
if parsedOptions.contains(.driverPrintJobs) {
for job in jobs {
print(try executor.description(of: job, forceResponseFiles: forceResponseFiles))
}
return
}
if parsedOptions.contains(.driverPrintBindings) {
for job in jobs {
printBindings(job)
}
return
}
if parsedOptions.contains(.driverPrintActions) {
// Print actions using the same style as the old C++ driver
// This is mostly for testing purposes. We should print semantically
// equivalent actions as the old driver.
Driver.printActions(jobs)
return
}
if parsedOptions.contains(.driverPrintGraphviz) {
var serializer = DOTJobGraphSerializer(jobs: jobs)
serializer.writeDOT(to: &stdoutStream)
stdoutStream.flush()
return
}
if jobs.contains(where: { $0.requiresInPlaceExecution })
// Only one job and no cleanup required
|| (jobs.count == 1 && !parsedOptions.hasArgument(.parseableOutput)) {
assert(jobs.count == 1, "Cannot execute in place for multi-job build plans")
var job = jobs[0]
// Require in-place execution for all single job plans.
job.requiresInPlaceExecution = true
try executor.execute(job: job,
forceResponseFiles: forceResponseFiles,
recordedInputModificationDates: recordedInputModificationDates)
return
}
// Create and use the tool execution delegate if one is not provided explicitly.
let executorDelegate = createToolExecutionDelegate()
// Perform the build
try executor.execute(jobs: jobs,
delegate: executorDelegate,
numParallelJobs: numParallelJobs ?? 1,
forceResponseFiles: forceResponseFiles,
recordedInputModificationDates: recordedInputModificationDates)
buildRecordInfo?.writeBuildRecord( jobs, incrementalCompilationState?.skippedInputs)
// If requested, warn for options that weren't used by the driver after the build is finished.
if parsedOptions.hasArgument(.driverWarnUnusedOptions) {
for option in parsedOptions.unconsumedOptions {
diagnosticEngine.emit(.warn_unused_option(option))
}
}
}
mutating func createToolExecutionDelegate() -> ToolExecutionDelegate {
var mode: ToolExecutionDelegate.Mode = .regular
// FIXME: Old driver does _something_ if both are passed. Not sure if we want to support that.
if parsedOptions.contains(.parseableOutput) {
mode = .parsableOutput
} else if parsedOptions.contains(.v) {
mode = .verbose
}
return ToolExecutionDelegate(
mode: mode,
buildRecordInfo: buildRecordInfo,
incrementalCompilationState: incrementalCompilationState,
showJobLifecycle: showJobLifecycle,
diagnosticEngine: diagnosticEngine)
}
private func printBindings(_ job: Job) {
stdoutStream <<< #"# ""# <<< targetTriple.triple
stdoutStream <<< #"" - ""# <<< job.tool.basename
stdoutStream <<< #"", inputs: ["#
stdoutStream <<< job.inputs.map { "\"" + $0.file.name + "\"" }.joined(separator: ", ")
stdoutStream <<< "], output: {"
stdoutStream <<< job.outputs.map { $0.type.name + ": \"" + $0.file.name + "\"" }.joined(separator: ", ")
stdoutStream <<< "}"
stdoutStream <<< "\n"
stdoutStream.flush()
}
private static func printActions(_ jobs: [Job]) {
defer {
stdoutStream.flush()
}
var jobIdMap = Dictionary<Job, UInt>()
// The C++ driver treats each input as an action, we should print them as
// an action too for testing purposes.
var inputIdMap = Dictionary<TypedVirtualPath, UInt>()
var nextId: UInt = 0
for job in jobs {
// All input action IDs for this action.
var inputIds = Set<UInt>()
// Collect input job IDs.
for input in job.displayInputs.isEmpty ? job.inputs : job.displayInputs {
var foundInput = false
for (prevJob, id) in jobIdMap {
if prevJob.outputs.contains(input) {
foundInput = true
inputIds.insert(id)
}
}
if (!foundInput) {
if inputIdMap[input] == nil {
stdoutStream <<< nextId <<< ": " <<< "input, "
stdoutStream <<< "\"" <<< input.file <<< "\", " <<< input.type <<< "\n"
inputIdMap[input] = nextId
nextId += 1
}
inputIds.insert(inputIdMap[input]!)
}
}
// Print current Job
stdoutStream <<< nextId <<< ": " <<< job.kind.rawValue <<< ", {"
stdoutStream <<< inputIds.sorted().map({ $0.description })
.joined(separator: ", ")
var typeName = job.outputs.first?.type.name
if typeName == nil {
typeName = "none"
}
stdoutStream <<< "}, " <<< typeName! <<< "\n"
jobIdMap[job] = nextId
nextId += 1
}
}
private func printVersion<S: OutputByteStream>(outputStream: inout S) throws {
outputStream <<< frontendTargetInfo.compilerVersion <<< "\n"
outputStream <<< "Target: \(frontendTargetInfo.target.triple.triple)\n"
outputStream.flush()
}
}
extension Diagnostic.Message {
static func warn_recursive_response_file(_ path: AbsolutePath) -> Diagnostic.Message {
.warning("response file '\(path)' is recursively expanded")
}
static var error_no_swift_frontend: Diagnostic.Message {
.error("-driver-use-frontend-path requires a Swift compiler executable argument")
}
static var warning_cannot_multithread_batch_mode: Diagnostic.Message {
.warning("ignoring -num-threads argument; cannot multithread batch mode")
}
static var error_no_output_file_map_specified: Diagnostic.Message {
.error("no output file map specified")
}
}
extension Driver {
/// Parse an option's value into an `Int`.
///
/// If the parsed options don't contain an option with this value, returns
/// `nil`.
/// If the parsed option does contain an option with this value, but the
/// value is not parsable as an `Int`, emits an error and returns `nil`.
/// Otherwise, returns the parsed value.
private static func parseIntOption(
_ parsedOptions: inout ParsedOptions,
option: Option,
diagnosticsEngine: DiagnosticsEngine
) -> Int? {
guard let argument = parsedOptions.getLastArgument(option) else {
return nil
}
guard let value = Int(argument.asSingle) else {
diagnosticsEngine.emit(.error_invalid_arg_value(arg: option, value: argument.asSingle))
return nil
}
return value
}
}
extension Driver {
private static func computeFileListThreshold(
_ parsedOptions: inout ParsedOptions,
diagnosticsEngine: DiagnosticsEngine
) throws -> Int {
let hasUseFileLists = parsedOptions.hasArgument(.driverUseFilelists)
if hasUseFileLists {
diagnosticsEngine.emit(.warn_use_filelists_deprecated)
}
if let threshold = parsedOptions.getLastArgument(.driverFilelistThreshold)?.asSingle {
if let thresholdInt = Int(threshold) {
return thresholdInt
} else {
throw Error.invalidArgumentValue(Option.driverFilelistThreshold.spelling, threshold)
}
} else if hasUseFileLists {
return 0
}
return 128