forked from apple/swift-driver
-
Notifications
You must be signed in to change notification settings - Fork 0
/
IncrementalCompilationTests.swift
2018 lines (1846 loc) · 77.8 KB
/
IncrementalCompilationTests.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
//===--------------- IncrementalCompilationTests.swift - Swift Testing ----===//
//
// 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 XCTest
import TSCBasic
import Foundation
@_spi(Testing) import SwiftDriver
import SwiftOptions
import TestUtilities
// MARK: - Instance variables and initialization
final class IncrementalCompilationTests: XCTestCase {
var tempDir: AbsolutePath = AbsolutePath("/tmp")
var explicitModuleCacheDir: AbsolutePath = AbsolutePath("/tmp/ModuleCache")
var derivedDataDir: AbsolutePath {
tempDir.appending(component: "derivedData")
}
let module = "theModule"
var OFM: AbsolutePath {
tempDir.appending(component: "OFM.json")
}
let baseNamesAndContents = [
"main": "let foo = 1",
"other": "let bar = foo"
]
func inputPath(basename: String) -> AbsolutePath {
tempDir.appending(component: basename + ".swift")
}
var inputPathsAndContents: [(AbsolutePath, String)] {
baseNamesAndContents.map {
(inputPath(basename: $0.key), $0.value)
}
}
var derivedDataPath: AbsolutePath {
tempDir.appending(component: "derivedData")
}
var masterSwiftDepsPath: AbsolutePath {
derivedDataPath.appending(component: "\(module)-master.swiftdeps")
}
var priorsPath: AbsolutePath {
derivedDataPath.appending(component: "\(module)-master.priors")
}
func swiftDepsPath(basename: String) -> AbsolutePath {
derivedDataPath.appending(component: "\(basename).swiftdeps")
}
fileprivate var autolinkIncrementalExpectedDiags: [Diagnostic.Message] {
queuingExtractingAutolink(module)
}
fileprivate var autolinkLifecycleExpectedDiags: [Diagnostic.Message] {
extractingAutolink(module)
}
var commonArgs: [String] {
[
"swiftc",
"-module-name", module,
"-o", derivedDataPath.appending(component: module + ".o").nativePathString(escaped: true),
"-output-file-map", OFM.nativePathString(escaped: true),
"-driver-show-incremental",
"-driver-show-job-lifecycle",
"-enable-batch-mode",
// "-v",
"-save-temps",
"-incremental",
"-no-color-diagnostics",
]
+ inputPathsAndContents.map {$0.0.nativePathString(escaped: true)} .sorted()
}
var explicitBuildArgs: [String] {
["-explicit-module-build",
"-module-cache-path", explicitModuleCacheDir.nativePathString(escaped: true),
// Disable implicit imports to keep tests simpler
"-Xfrontend", "-disable-implicit-concurrency-module-import",
"-Xfrontend", "-disable-implicit-string-processing-module-import",
"-I", explicitCDependenciesPath.nativePathString(escaped: true),
"-I", explicitSwiftDependenciesPath.nativePathString(escaped: true)]
}
override func setUp() {
self.tempDir = try! withTemporaryDirectory(removeTreeOnDeinit: false) {$0}
self.explicitModuleCacheDir = tempDir.appending(component: "ModuleCache")
try! localFileSystem.createDirectory(derivedDataPath)
OutputFileMapCreator.write(module: module,
inputPaths: inputPathsAndContents.map {$0.0},
derivedData: derivedDataPath,
to: OFM)
for (base, contents) in baseNamesAndContents {
write(contents, to: base)
}
}
deinit {
try? localFileSystem.removeFileTree(tempDir)
}
}
// MARK: - Misc. tests
extension IncrementalCompilationTests {
func testOptionsParsing() throws {
let optionPairs: [(
Option, (IncrementalCompilationState.IncrementalDependencyAndInputSetup) -> Bool
)] = [
(.driverAlwaysRebuildDependents, {$0.alwaysRebuildDependents}),
(.driverShowIncremental, {$0.reporter != nil}),
(.driverEmitFineGrainedDependencyDotFileAfterEveryImport, {$0.emitDependencyDotFileAfterEveryImport}),
(.driverVerifyFineGrainedDependencyGraphAfterEveryImport, {$0.verifyDependencyGraphAfterEveryImport}),
(.enableIncrementalImports, {$0.isCrossModuleIncrementalBuildEnabled}),
(.disableIncrementalImports, {!$0.isCrossModuleIncrementalBuildEnabled}),
]
for (driverOption, stateOptionFn) in optionPairs {
try doABuild(
"initial",
checkDiagnostics: false,
extraArguments: [ driverOption.spelling ],
whenAutolinking: []
) {}
guard let sdkArgumentsForTesting = try Driver.sdkArgumentsForTesting()
else {
throw XCTSkip("Cannot perform this test on this host")
}
var driver = try Driver(args: self.commonArgs + [
driverOption.spelling,
] + sdkArgumentsForTesting)
_ = try driver.planBuild()
XCTAssertFalse(driver.diagnosticEngine.hasErrors)
let state = try XCTUnwrap(driver.incrementalCompilationState)
XCTAssertTrue(stateOptionFn(state.info))
}
}
/// Ensure that autolink output file goes with .o directory, to not prevent incremental omission of
/// autolink job.
/// Much of the code below is taking from testLinking(), but uses the output file map code here.
func testAutolinkOutputPath() throws {
var env = ProcessEnv.vars
env["SWIFT_DRIVER_TESTS_ENABLE_EXEC_PATH_FALLBACK"] = "1"
env["SWIFT_DRIVER_SWIFT_AUTOLINK_EXTRACT_EXEC"] = "/garbage/swift-autolink-extract"
env["SWIFT_DRIVER_DSYMUTIL_EXEC"] = "/garbage/dsymutil"
var driver = try Driver(
args: commonArgs
+ ["-emit-library", "-target", "x86_64-unknown-linux"],
env: env)
let plannedJobs = try driver.planBuild()
let autolinkExtractJob = try XCTUnwrap(
plannedJobs
.filter { $0.kind == .autolinkExtract }
.first)
let autoOuts = autolinkExtractJob.outputs.filter {$0.type == .autolink}
XCTAssertEqual(autoOuts.count, 1)
let autoOut = autoOuts[0]
let expected = AbsolutePath(derivedDataPath, "\(module).autolink")
XCTAssertEqual(autoOut.file.absolutePath, expected)
}
}
// MARK: - Dot file tests
extension IncrementalCompilationTests {
func testDependencyDotFiles() throws {
expectNoDotFiles()
try buildInitialState(extraArguments: ["-driver-emit-fine-grained-dependency-dot-file-after-every-import"])
expect(dotFilesFor: [
"main.swift",
DependencyGraphDotFileWriter.moduleDependencyGraphBasename,
"other.swift",
DependencyGraphDotFileWriter.moduleDependencyGraphBasename,
])
}
func testDependencyDotFilesCross() throws {
expectNoDotFiles()
try buildInitialState(extraArguments: [
"-driver-emit-fine-grained-dependency-dot-file-after-every-import",
])
removeDotFiles()
try checkNoPropagation(extraArguments: [
"-driver-emit-fine-grained-dependency-dot-file-after-every-import",
])
expect(dotFilesFor: [
DependencyGraphDotFileWriter.moduleDependencyGraphBasename,
"other.swift",
DependencyGraphDotFileWriter.moduleDependencyGraphBasename,
])
}
func expectNoDotFiles() {
guard localFileSystem.exists(derivedDataDir) else { return }
try! localFileSystem.getDirectoryContents(derivedDataDir)
.forEach {derivedFile in
XCTAssertFalse(derivedFile.hasSuffix("dot"))
}
}
func removeDotFiles() {
try! localFileSystem.getDirectoryContents(derivedDataDir)
.filter {$0.hasSuffix(".dot")}
.map {derivedDataDir.appending(component: $0)}
.forEach {try! localFileSystem.removeFileTree($0)}
}
private func expect(dotFilesFor importedFiles: [String]) {
let expectedDotFiles = Set(
importedFiles.enumerated()
.map { offset, element in "\(element).\(offset).dot" })
let actualDotFiles = Set(
try! localFileSystem.getDirectoryContents(derivedDataDir)
.filter {$0.hasSuffix(".dot")})
let missingDotFiles = expectedDotFiles.subtracting(actualDotFiles)
.sortedByDotFileSequenceNumbers()
let extraDotFiles = actualDotFiles.subtracting(expectedDotFiles)
.sortedByDotFileSequenceNumbers()
XCTAssertEqual(missingDotFiles, [])
XCTAssertEqual(extraDotFiles, [])
}
}
// MARK: - Post-compile jobs
extension IncrementalCompilationTests {
/// Ensure that if an output of post-compile job is missing, the job gets rerun.
func testIncrementalPostCompileJob() throws {
#if !os(Linux)
let driver = try XCTUnwrap(buildInitialState(checkDiagnostics: true))
for postCompileOutput in try driver.postCompileOutputs() {
let absPostCompileOutput = try XCTUnwrap(postCompileOutput.file.absolutePath)
try localFileSystem.removeFileTree(absPostCompileOutput)
XCTAssertFalse(localFileSystem.exists(absPostCompileOutput))
try checkNullBuild()
XCTAssertTrue(localFileSystem.exists(absPostCompileOutput))
}
#endif
}
}
fileprivate extension Driver {
func postCompileOutputs() throws -> [TypedVirtualPath] {
try XCTUnwrap(incrementalCompilationState).jobsAfterCompiles.flatMap {$0.outputs}
}
}
// MARK: - Explicit Module Build incremental tests
extension IncrementalCompilationTests {
private var testExplicitDependencyInputsPath: AbsolutePath {
var root: AbsolutePath = try! AbsolutePath(validating: #file)
while root.basename != "Tests" {
root = root.parentDirectory
}
return root.parentDirectory.appending(component: "TestInputs")
}
private var explicitCDependenciesPath: AbsolutePath {
testExplicitDependencyInputsPath.appending(component: "ExplicitModuleBuilds")
.appending(component: "CHeaders")
}
private var explicitSwiftDependenciesPath: AbsolutePath {
testExplicitDependencyInputsPath.appending(component: "ExplicitModuleBuilds")
.appending(component: "Swift")
}
func testExplicitIncrementalSimpleBuild() throws {
try buildInitialState(explicitModuleBuild: true)
try checkNullBuild(explicitModuleBuild: true)
}
// Simple re-use of a prior inter-module dependency graph on a null build
func testExplicitIncrementalSimpleBuildCheckDiagnostics() throws {
try buildInitialState(checkDiagnostics: true, explicitModuleBuild: true)
try checkNullBuild(checkDiagnostics: true, explicitModuleBuild: true)
}
// Source files have changed but the inter-module dependency graph still up-to-date
func testExplicitIncrementalBuildCheckGraphReuseOnChange() throws {
try buildInitialState(checkDiagnostics: true, explicitModuleBuild: true)
try checkReactionToTouchingAll(checkDiagnostics: true, explicitModuleBuild: true)
}
// Adding an import invalidates prior inter-module dependency graph.
func testExplicitIncrementalBuildNewImport() throws {
try buildInitialState(checkDiagnostics: true, explicitModuleBuild: true)
// Introduce a new import. This will cause a re-scan and a re-build of 'other.swift'
replace(contentsOf: "other", with: "import E;let bar = foo")
try doABuild(
"add import to 'other'",
checkDiagnostics: true,
extraArguments: explicitBuildArgs,
whenAutolinking: autolinkLifecycleExpectedDiags
) {
readGraph
enablingCrossModule
readInterModuleGraph
// Ensure a re-scan was performed
explicitMustReScanDueToChangedImports
maySkip("main")
schedulingChangedInitialQueuing("other")
skipping("main")
findingBatchingCompiling("other")
reading(deps: "other")
fingerprintsChanged("other")
fingerprintsMissingOfTopLevelName(name: "bar", "other")
moduleOutputNotFound("E")
moduleWillBeRebuiltOutOfDate("E")
explicitModulesWillBeRebuilt(["E"])
compilingExplicitSwiftDependency("E")
skipped("main")
schedLinking
}
}
// A dependency has changed one of its inputs
func testExplicitIncrementalBuildChangedDependency() throws {
// Add an import of 'E' to make sure followup changes has consistent inputs
replace(contentsOf: "other", with: "import E;let bar = foo")
try buildInitialState(checkDiagnostics: false, explicitModuleBuild: true)
// Just update the time-stamp of one of the module dependencies and use a value
// it is defined in.
touch(try AbsolutePath(validating: explicitSwiftDependenciesPath.appending(component: "E.swiftinterface").pathString))
replace(contentsOf: "other", with: "import E;let bar = foo + moduleEValue")
// Changing a dependency will mean that we both re-run the dependency scan,
// and also ensure that all source-files are re-built with a non-cascading build
// since the source files themselves have not changed.
try doABuild(
"update dependency (E) interface timestamp",
checkDiagnostics: true,
extraArguments: explicitBuildArgs,
whenAutolinking: autolinkLifecycleExpectedDiags
) {
readGraph
enablingCrossModule
readInterModuleGraph
// Ensure the above 'touch' is detected and causes a re-scan
explicitDependencyModuleOlderThanInput("E")
explicitMustReScanDueToChangedDependencyInput
noFingerprintInSwiftModule("E.swiftinterface")
dependencyNewerThanNode("E.swiftinterface")
dependencyNewerThanNode("E.swiftinterface") // FIXME: Why do we see this twice?
maySkip("main")
schedulingChanged("other")
invalidatedExternally("main", "other")
queuingInitial("main", "other")
notSchedulingDependentsUnknownChanges("other")
findingBatchingCompiling("main", "other")
explicitDependencyModuleOlderThanInput("E")
moduleWillBeRebuiltOutOfDate("E")
explicitModulesWillBeRebuilt(["E"])
compilingExplicitSwiftDependency("E")
}
}
// A dependency has changed one of its inputs, ensure
// other modules that depend on it are invalidated also.
//
// test
// / \
// Y T
// / \ / \
// H R J
// \ \
// \-------G
//
// On this graph, inputs of 'G' are updated, causing it to be re-built
// as well as all modules on paths from root to it: 'Y', 'H', 'T','J'
func testExplicitIncrementalBuildChangedDependencyInvalidatesUpstreamDependencies() throws {
// Add an import of 'B', 'C' to make sure followup changes has consistent inputs
replace(contentsOf: "other", with: "import Y;import T")
try buildInitialState(checkDiagnostics: false, explicitModuleBuild: true)
// Just update the time-stamp of one of the module dependencies
touch(try AbsolutePath(validating: explicitSwiftDependenciesPath.appending(component: "G.swiftinterface").pathString))
// Changing a dependency will mean that we both re-run the dependency scan,
// and also ensure that all source-files are re-built with a non-cascading build
// since the source files themselves have not changed.
try doABuild(
"update dependency (G) interface timestamp",
checkDiagnostics: true,
extraArguments: explicitBuildArgs,
whenAutolinking: autolinkLifecycleExpectedDiags
) {
readGraph
enablingCrossModule
readInterModuleGraph
// Ensure the above 'touch' is detected and causes a re-scan
explicitDependencyModuleOlderThanInput("G")
explicitMustReScanDueToChangedDependencyInput
noFingerprintInSwiftModule("G.swiftinterface")
dependencyNewerThanNode("G.swiftinterface")
dependencyNewerThanNode("G.swiftinterface") // FIXME: Why do we see this twice?
reading(deps: "main")
reading(deps: "other")
fingerprintsMissingOfTopLevelName(name: "foo", "main")
maySkip("main")
maySkip("other")
invalidatedExternally("main", "other")
queuingInitial("main", "other")
findingBatchingCompiling("main", "other")
explicitDependencyModuleOlderThanInput("G")
explicitDependencyInvalidatedDownstream("J")
explicitDependencyInvalidatedDownstream("T")
explicitDependencyInvalidatedDownstream("Y")
explicitDependencyInvalidatedDownstream("H")
explicitModulesWillBeRebuilt(["G", "H", "J", "T", "Y"])
moduleWillBeRebuiltOutOfDate("G")
compilingExplicitSwiftDependency("G")
compilingExplicitSwiftDependency("J")
compilingExplicitSwiftDependency("T")
compilingExplicitSwiftDependency("Y")
compilingExplicitSwiftDependency("H")
schedulingPostCompileJobs
linking
}
}
}
extension IncrementalCompilationTests {
// A dependency has changed one of its inputs
func testIncrementalImplicitBuildChangedDependency() throws {
let extraAruments = ["-I", explicitCDependenciesPath.nativePathString(escaped: true),
"-I", explicitSwiftDependenciesPath.nativePathString(escaped: true)]
replace(contentsOf: "other", with: "import E;let bar = foo")
try buildInitialState(checkDiagnostics: false, extraArguments: extraAruments)
touch(try AbsolutePath(validating: explicitSwiftDependenciesPath.appending(component: "E.swiftinterface").pathString))
replace(contentsOf: "other", with: "import E;let bar = foo + moduleEValue")
// Changing a dependency will mean that we both re-run the dependency scan,
// and also ensure that all source-files are re-built with a non-cascading build
// since the source files themselves have not changed.
try doABuild(
"update dependency (E) interface timestamp",
checkDiagnostics: false,
extraArguments: extraAruments,
whenAutolinking: autolinkLifecycleExpectedDiags
) {
readGraph
enablingCrossModule
schedulingNoncascading("main", "other")
missing("main")
missing("other")
queuingInitial("main", "other")
notSchedulingDependentsDoNotNeedCascading("main", "other")
findingBatchingCompiling("main", "other")
}
}
}
// MARK: - Simpler incremental tests
extension IncrementalCompilationTests {
// FIXME: why does it fail on Linux in CI?
func testIncrementalDiagnostics() throws {
#if !os(Linux)
try testIncremental(checkDiagnostics: true)
#endif
}
func testIncremental() throws {
try testIncremental(checkDiagnostics: false)
}
func testIncremental(checkDiagnostics: Bool) throws {
try buildInitialState(checkDiagnostics: checkDiagnostics)
#if true // sometimes want to skip for debugging
try checkNullBuild(checkDiagnostics: checkDiagnostics)
try checkNoPropagation(checkDiagnostics: checkDiagnostics)
try checkReactionToTouchingAll(checkDiagnostics: checkDiagnostics)
#endif
try checkPropagationOfTopLevelChange(checkDiagnostics: checkDiagnostics)
}
func testFileMapMissingMainEntry() throws {
try buildInitialState(checkDiagnostics: true)
OutputFileMapCreator.write(
module: module, inputPaths: inputPathsAndContents.map {$0.0},
derivedData: derivedDataPath, to: OFM, excludeMainEntry: true)
try doABuild("output file map missing main entry", checkDiagnostics: true, extraArguments: [], whenAutolinking: []) {
missingMainDependencyEntry
disablingIncremental
foundBatchableJobs(2)
formingOneBatch
addingToBatchThenForming("main", "other")
compiling("main", "other")
startingLinking
finishedLinking
}
}
func testFileMapMissingMainEntryWMO() throws {
try buildInitialState(checkDiagnostics: true)
guard let sdkArgumentsForTesting = try Driver.sdkArgumentsForTesting()
else {
throw XCTSkip("Cannot perform this test on this host")
}
OutputFileMapCreator.write(
module: module, inputPaths: inputPathsAndContents.map {$0.0},
derivedData: derivedDataPath, to: OFM, excludeMainEntry: true)
let args = [
"swiftc",
"-module-name", module,
"-o", derivedDataPath.appending(component: module + ".o").pathString,
"-output-file-map", OFM.pathString,
"-incremental",
"-whole-module-optimization",
"-no-color-diagnostics",
] + inputPathsAndContents.map {$0.0.pathString}.sorted() + sdkArgumentsForTesting
_ = try doABuild(whenAutolinking: [], expecting: disabledForWMO, arguments: args)
}
// FIXME: Expect failure in Linux in CI just as testIncrementalDiagnostics
func testAlwaysRebuildDependents() throws {
#if !os(Linux)
try buildInitialState(checkDiagnostics: true)
try checkAlwaysRebuildDependents(checkDiagnostics: true)
#endif
}
/// Ensure that the mod date of the input comes back exactly the same via the build-record.
/// Otherwise the up-to-date calculation in `IncrementalCompilationState` will fail.
func testBuildRecordDateAccuracy() throws {
try buildInitialState()
try (1...10).forEach { n in
try checkNullBuild(checkDiagnostics: true)
}
}
func testNullBuildNoEmitModule() throws {
let extraArguments = ["-experimental-emit-module-separately", "-emit-module"]
try buildInitialState(extraArguments: extraArguments)
let driver = try checkNullBuild(extraArguments: extraArguments)
let mandatoryJobs = try XCTUnwrap(driver.incrementalCompilationState?.mandatoryJobsInOrder)
XCTAssertTrue(mandatoryJobs.isEmpty)
}
func testNullBuildNoVerify() throws {
let extraArguments = ["-experimental-emit-module-separately", "-emit-module", "-emit-module-interface", "-enable-library-evolution", "-verify-emitted-module-interface"]
try buildInitialState(extraArguments: extraArguments)
let driver = try checkNullBuild(extraArguments: extraArguments)
let mandatoryJobs = try XCTUnwrap(driver.incrementalCompilationState?.mandatoryJobsInOrder)
XCTAssertTrue(mandatoryJobs.isEmpty)
}
func testSymlinkModification() throws {
// Remap
// main.swift -> links/main.swift
// other.swift -> links/other.swift
for (file, _) in self.inputPathsAndContents {
try localFileSystem.createDirectory(tempDir.appending(component: "links"))
let linkTarget = tempDir.appending(component: "links").appending(component: file.basename)
try localFileSystem.move(from: file, to: linkTarget)
try localFileSystem.removeFileTree(file)
try localFileSystem.createSymbolicLink(file, pointingAt: linkTarget, relative: false)
}
try buildInitialState()
try checkReactionToTouchingSymlinks(checkDiagnostics: true)
try checkReactionToTouchingSymlinkTargets(checkDiagnostics: true)
}
/// Ensure that the driver can detect and then recover from a priors version mismatch
func testPriorsVersionDetectionAndRecovery() throws {
#if _runtime(_ObjC)
// create a baseline priors
try buildInitialState(checkDiagnostics: true)
let driver = try checkNullBuild(checkDiagnostics: true)
// Read the priors, change the minor version, and write it back out
let outputFileMap = try XCTUnwrap(driver.incrementalCompilationState).info.outputFileMap
let info = IncrementalCompilationState.IncrementalDependencyAndInputSetup
.mock(outputFileMap: outputFileMap)
let priorsModTime = try info.blockingConcurrentAccessOrMutation {
() -> Date in
let priorsWithOldVersion = try XCTUnwrap(ModuleDependencyGraph.read(
from: .absolute(priorsPath),
info: info))
let priorsModTime = try localFileSystem.getFileInfo(priorsPath).modTime
let incrementedVersion = ModuleDependencyGraph.serializedGraphVersion.withAlteredMinor
try priorsWithOldVersion.write(to: .absolute(priorsPath),
on: localFileSystem,
buildRecord: priorsWithOldVersion.buildRecord,
mockSerializedGraphVersion: incrementedVersion)
return priorsModTime
}
try setModTime(of: .absolute(priorsPath), to: priorsModTime)
try checkReactionToObsoletePriors()
try checkNullBuild(checkDiagnostics: true)
#endif
}
}
// MARK: - Test adding an input
extension IncrementalCompilationTests {
func testAddingInput() throws {
#if !os(Linux)
try testAddingInput(newInput: "another", defining: "nameInAnother")
#endif
}
/// Test the addition of an input file
///
/// - Parameters:
/// - newInput: basename without extension of new input file
/// - topLevelName: a new top level name defined in the new input
private func testAddingInput(newInput: String, defining topLevelName: String
) throws {
try buildInitialState(checkDiagnostics: true).withModuleDependencyGraph { initial in
initial.ensureOmits(sourceBasenameWithoutExt: newInput)
initial.ensureOmits(name: topLevelName)
}
write("let \(topLevelName) = foo", to: newInput)
let newInputsPath = inputPath(basename: newInput)
OutputFileMapCreator.write(module: module,
inputPaths: inputPathsAndContents.map {$0.0} + [newInputsPath],
derivedData: derivedDataPath,
to: OFM)
try checkReactionToAddingInput(newInput: newInput, definingTopLevel: topLevelName)
try checkRestorationOfIncrementalityAfterAddition(newInput: newInput, definingTopLevel: topLevelName)
}
}
// MARK: - Incremental file removal tests
/// In order to ensure robustness, test what happens under various conditions when a source file is
/// removed.
/// The following is a lot of work to get something that prints nicely. Need an enum with both a string and an int value.
fileprivate enum RemovalTestOption: String, CaseIterable, Comparable, Hashable, CustomStringConvertible {
case
removeInputFromInvocation,
removeSwiftDepsOfRemovedInput,
removedFileDependsOnChangedFile
private static let byInt = [Int: Self](uniqueKeysWithValues: allCases.enumerated().map{($0, $1)})
private static let intFor = [Self: Int](uniqueKeysWithValues: allCases.enumerated().map{($1, $0)})
var intValue: Int {Self.intFor[self]!}
init(fromInt i: Int) {self = Self.byInt[i]!}
static func < (lhs: RemovalTestOption, rhs: RemovalTestOption) -> Bool {
lhs.intValue < rhs.intValue
}
var mask: Int { 1 << intValue}
static let maxIntValue = allCases.map {$0.intValue} .max()!
static let maxCombinedValue = (1 << (maxIntValue + 1)) - 1
var description: String { rawValue }
}
/// Only 5 elements, an array is fine
fileprivate typealias RemovalTestOptions = [RemovalTestOption]
extension RemovalTestOptions {
fileprivate static let allCombinations: [RemovalTestOptions] =
(0...RemovalTestOption.maxCombinedValue) .map(decoding)
fileprivate static func decoding(_ bits: Int) -> Self {
RemovalTestOption.allCases.filter { opt in
(1 << opt.intValue) & bits != 0
}
}
}
extension IncrementalCompilationTests {
func testRemoval() throws {
#if _runtime(_ObjC)
for optionsToTest in RemovalTestOptions.allCombinations {
try testRemoval(optionsToTest)
}
#endif
}
private func testRemoval(_ options: RemovalTestOptions) throws {
setUp() // clear derived data, restore output file map
print("\n*** testRemoval \(options) ***", to: &stderrStream); stderrStream.flush()
let newInput = "another"
let topLevelName = "nameInAnother"
try testAddingInput(newInput: newInput, defining: topLevelName)
let removeInputFromInvocation = options.contains(.removeInputFromInvocation)
let removeSwiftDepsOfRemovedInput = options.contains(.removeSwiftDepsOfRemovedInput)
let removedFileDependsOnChangedFileAndMainWasChanged = options.contains(.removedFileDependsOnChangedFile)
_ = try self.checkNonincrementalAfterRemoving(
removedInput: newInput,
defining: topLevelName,
removeInputFromInvocation: removeInputFromInvocation,
removeSwiftDepsOfRemovedInput: removeSwiftDepsOfRemovedInput)
if removedFileDependsOnChangedFileAndMainWasChanged {
replace(contentsOf: "main", with: "let foo = \"hello\"")
}
try checkRestorationOfIncrementalityAfterRemoval(
removedInput: newInput,
defining: topLevelName,
removeInputFromInvocation: removeInputFromInvocation,
removeSwiftDepsOfRemovedInput: removeSwiftDepsOfRemovedInput,
removedFileDependsOnChangedFileAndMainWasChanged: removedFileDependsOnChangedFileAndMainWasChanged)
}
}
// MARK: - Incremental argument hashing tests
extension IncrementalCompilationTests {
func testNullBuildWhenAddingAndRemovingArgumentsNotAffectingIncrementalBuilds() throws {
// Adding, removing, or changing the arguments of options which don't affect incremental builds should result in a null build.
try buildInitialState(extraArguments: ["-driver-batch-size-limit", "5", "-debug-diagnostic-names"])
let driver = try checkNullBuild(extraArguments: ["-driver-batch-size-limit", "10", "-diagnostic-style", "swift"])
let mandatoryJobs = try XCTUnwrap(driver.incrementalCompilationState?.mandatoryJobsInOrder)
XCTAssertTrue(mandatoryJobs.isEmpty)
}
func testChangingOptionArgumentLeadsToRecompile() throws {
// If an option affects incremental builds, changing only the argument should trigger a full recompile.
try buildInitialState(extraArguments: ["-user-module-version", "1.0"])
try doABuild(
"change user module version",
checkDiagnostics: true,
extraArguments: ["-user-module-version", "1.1"],
whenAutolinking: autolinkLifecycleExpectedDiags
) {
enablingCrossModule
readGraph
differentArgsPassed
disablingIncrementalDifferentArgsPassed
findingBatchingCompiling("main", "other")
reading(deps: "main", "other")
schedLinking
}
}
func testOptionReorderingLeadsToRecompile() throws {
// Reordering options which affect incremental builds should trigger a full recompile.
try buildInitialState(extraArguments: ["-warnings-as-errors", "-no-warnings-as-errors"])
try doABuild(
"change user module version",
checkDiagnostics: true,
extraArguments: ["-no-warnings-as-errors", "-warnings-as-errors"],
whenAutolinking: autolinkLifecycleExpectedDiags
) {
enablingCrossModule
readGraph
differentArgsPassed
disablingIncrementalDifferentArgsPassed
findingBatchingCompiling("main", "other")
reading(deps: "main", "other")
schedLinking
}
}
func testArgumentReorderingLeadsToRecompile() throws {
// Reordering the arguments of an option which affect incremental builds should trigger a full recompile.
try buildInitialState(extraArguments: ["-Ifoo", "-Ibar"])
try doABuild(
"change user module version",
checkDiagnostics: true,
extraArguments: ["-Ibar", "-Ifoo"],
whenAutolinking: autolinkLifecycleExpectedDiags
) {
enablingCrossModule
readGraph
differentArgsPassed
disablingIncrementalDifferentArgsPassed
findingBatchingCompiling("main", "other")
reading(deps: "main", "other")
schedLinking
}
}
}
// MARK: - Incremental test stages
extension IncrementalCompilationTests {
/// Setup the initial post-build state.
///
/// - Parameters:
/// - checkDiagnostics: If true verify the diagnostics
/// - extraArguments: Additional command-line arguments
/// - Returns: The `Driver` object
@discardableResult
private func buildInitialState(
checkDiagnostics: Bool = false,
extraArguments: [String] = [],
explicitModuleBuild: Bool = false
) throws -> Driver {
@DiagsBuilder var implicitBuildInitialRemarks: [Diagnostic.Message] {
// Leave off the part after the colon because it varies on Linux:
// MacOS: The operation could not be completed. (TSCBasic.FileSystemError error 3.).
// Linux: The operation couldn’t be completed. (TSCBasic.FileSystemError error 3.)
enablingCrossModule
findingBatchingCompiling("main", "other")
reading(deps: "main", "other")
schedLinking
}
@DiagsBuilder var explicitBuildInitialRemarks: [Diagnostic.Message] {
implicitBuildInitialRemarks
explicitDidNotReadInterModuleGraph
compilingExplicitClangDependency("SwiftShims")
compilingExplicitSwiftDependency("Swift")
compilingExplicitSwiftDependency("SwiftOnoneSupport")
}
return try doABuild("initial",
checkDiagnostics: checkDiagnostics,
extraArguments: explicitModuleBuild ? explicitBuildArgs + extraArguments : extraArguments,
whenAutolinking: autolinkLifecycleExpectedDiags
) { explicitModuleBuild ? explicitBuildInitialRemarks : implicitBuildInitialRemarks }
}
/// Try a build with no changes.
///
/// - Parameters:
/// - checkDiagnostics: If true verify the diagnostics
/// - extraArguments: Additional command-line arguments
@discardableResult
private func checkNullBuild(
checkDiagnostics: Bool = false,
extraArguments: [String] = [],
explicitModuleBuild: Bool = false
) throws -> Driver {
@DiagsBuilder var implicitBuildNullRemarks: [Diagnostic.Message] {
enablingCrossModule
readGraph
maySkip("main", "other")
skipping("main", "other")
skipped("main", "other")
skippingLinking
}
@DiagsBuilder var explicitBuildNullRemarks: [Diagnostic.Message] {
implicitBuildNullRemarks
readInterModuleGraph
interModuleDependencyGraphUpToDate
}
return try doABuild(
"as is",
checkDiagnostics: checkDiagnostics,
extraArguments: explicitModuleBuild ? explicitBuildArgs + extraArguments : extraArguments,
whenAutolinking: []
) { explicitModuleBuild ? explicitBuildNullRemarks : implicitBuildNullRemarks }
}
/// Check reaction to touching a non-propagating input.
///
/// - Parameters:
/// - checkDiagnostics: If true verify the diagnostics
/// - extraArguments: Additional command-line arguments
private func checkNoPropagation(
checkDiagnostics: Bool = false,
extraArguments: [String] = []
) throws {
touch("other")
try doABuild(
"touch other; non-propagating",
checkDiagnostics: checkDiagnostics,
extraArguments: extraArguments,
whenAutolinking: autolinkLifecycleExpectedDiags
) {
enablingCrossModule
maySkip("main")
schedulingChangedInitialQueuing("other")
skipping("main")
readGraph
findingBatchingCompiling("other")
reading(deps: "other")
// Since the code is `bar = foo`, there is no fingprint for `bar`
fingerprintsMissingOfTopLevelName(name: "bar", "other")
schedLinking
skipped("main")
}
}
/// Check reaction to touching both inputs.
///
/// - Parameters:
/// - checkDiagnostics: If true verify the diagnostics
/// - extraArguments: Additional command-line arguments
private func checkReactionToTouchingAll(
checkDiagnostics: Bool = false,
extraArguments: [String] = [],
explicitModuleBuild: Bool = false
) throws {
@DiagsBuilder var implicitBuildRemarks: [Diagnostic.Message] {
readGraph
enablingCrossModule
schedulingChangedInitialQueuing("main", "other")
findingBatchingCompiling("main", "other")
reading(deps: "main", "other")
// Because `let foo = 1`, there is no fingerprint
fingerprintsMissingOfTopLevelName(name: "foo", "main")
fingerprintsMissingOfTopLevelName(name: "bar", "other")
schedLinking
}
@DiagsBuilder var explicitBuildRemarks: [Diagnostic.Message] {
implicitBuildRemarks
readInterModuleGraph
interModuleDependencyGraphUpToDate
}
touch("main")
touch("other")
try doABuild(
"touch both; non-propagating",
checkDiagnostics: checkDiagnostics,
extraArguments: explicitModuleBuild ? explicitBuildArgs + extraArguments : extraArguments,
whenAutolinking: autolinkLifecycleExpectedDiags
) { explicitModuleBuild ? explicitBuildRemarks : implicitBuildRemarks }
}
/// Check reaction to changing a top-level declaration.
///
/// - Parameters:
/// - checkDiagnostics: If true verify the diagnostics
/// - extraArguments: Additional command-line arguments
private func checkPropagationOfTopLevelChange(
checkDiagnostics: Bool = false,
extraArguments: [String] = []
) throws {
replace(contentsOf: "main", with: "let foo = \"hello\"")
try doABuild(
"replace contents of main; propagating into 2nd wave",
checkDiagnostics: checkDiagnostics,
extraArguments: extraArguments,
whenAutolinking: autolinkLifecycleExpectedDiags
) {
readGraph
enablingCrossModule
schedulingChanged("main")
maySkip("other")
queuingInitial("main")
notSchedulingDependentsUnknownChanges("main")
skipping("other")
findingBatchingCompiling("main")
reading(deps: "main")
fingerprintsChanged("main")
fingerprintsMissingOfTopLevelName(name: "foo", "main")
trace {
TraceStep(.interface, sourceFileProvide: "main")
TraceStep(.interface, topLevel: "foo", input: "main")
TraceStep(.implementation, sourceFileProvide: "other")
}
queuingLaterSchedInvalBatchLink("other")
findingBatchingCompiling("other")
reading(deps: "other")
fingerprintsMissingOfTopLevelName(name: "bar", "other")
schedLinking
}
}
/// Check functioning of `-driver-always-rebuild-dependents`
///
/// - Parameters:
/// - checkDiagnostics: If true verify the diagnostics
/// - extraArguments: Additional command-line arguments
private func checkAlwaysRebuildDependents(
checkDiagnostics: Bool = false,
extraArguments: [String] = []
) throws {
touch("main")
let extraArgument = "-driver-always-rebuild-dependents"
try doABuild(
"touch main; non-propagating but \(extraArgument)",
checkDiagnostics: checkDiagnostics,
extraArguments: [extraArgument],
whenAutolinking: autolinkLifecycleExpectedDiags
) {
enablingCrossModule
readGraph
maySkip("other")
queuingInitial("main")
schedulingAlwaysRebuild("main")
trace {
TraceStep(.interface, topLevel: "foo", input: "main")
TraceStep(.implementation, sourceFileProvide: "other")
}
foundDependent(of: "main", compiling: "other")
schedulingChanged("main")
schedulingDependent(of: "main", compiling: "other")
queuingBecauseInitial("other")
findingAndFormingBatch(2)
addingToBatchThenForming("main", "other")
schedulingPostCompileJobs
compiling("main", "other")
reading(deps: "main", "other")
fingerprintsMissingOfTopLevelName(name: "foo", "main")