-
Notifications
You must be signed in to change notification settings - Fork 12.7k
/
runtest.rs
4559 lines (3977 loc) · 170 KB
/
runtest.rs
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
// ignore-tidy-filelength
use crate::common::{expected_output_path, UI_EXTENSIONS, UI_FIXED, UI_STDERR, UI_STDOUT};
use crate::common::{incremental_dir, output_base_dir, output_base_name, output_testname_unique};
use crate::common::{Assembly, Incremental, JsDocTest, MirOpt, RunMake, RustdocJson, Ui};
use crate::common::{Codegen, CodegenUnits, DebugInfo, Debugger, Rustdoc};
use crate::common::{CompareMode, FailMode, PassMode};
use crate::common::{Config, TestPaths};
use crate::common::{CoverageMap, Pretty, RunCoverage, RunPassValgrind};
use crate::common::{UI_COVERAGE, UI_COVERAGE_MAP, UI_RUN_STDERR, UI_RUN_STDOUT};
use crate::compute_diff::{write_diff, write_filtered_diff};
use crate::errors::{self, Error, ErrorKind};
use crate::header::TestProps;
use crate::json;
use crate::read2::{read2_abbreviated, Truncated};
use crate::util::{add_dylib_path, dylib_env_var, logv, PathBufExt};
use crate::ColorConfig;
use regex::{Captures, Regex};
use rustfix::{apply_suggestions, get_suggestions_from_json, Filter};
use std::borrow::Cow;
use std::collections::hash_map::DefaultHasher;
use std::collections::{HashMap, HashSet};
use std::env;
use std::ffi::{OsStr, OsString};
use std::fs::{self, create_dir_all, File, OpenOptions};
use std::hash::{Hash, Hasher};
use std::io::prelude::*;
use std::io::{self, BufReader};
use std::iter;
use std::path::{Path, PathBuf};
use std::process::{Child, Command, ExitStatus, Output, Stdio};
use std::str;
use std::sync::Arc;
use anyhow::Context;
use glob::glob;
use once_cell::sync::Lazy;
use tracing::*;
use crate::extract_gdb_version;
use crate::is_android_gdb_target;
mod debugger;
use debugger::DebuggerCommands;
#[cfg(test)]
mod tests;
const FAKE_SRC_BASE: &str = "fake-test-src-base";
#[cfg(windows)]
fn disable_error_reporting<F: FnOnce() -> R, R>(f: F) -> R {
use std::sync::Mutex;
use windows::Win32::System::Diagnostics::Debug::{
SetErrorMode, SEM_NOGPFAULTERRORBOX, THREAD_ERROR_MODE,
};
static LOCK: Mutex<()> = Mutex::new(());
// Error mode is a global variable, so lock it so only one thread will change it
let _lock = LOCK.lock().unwrap();
// Tell Windows to not show any UI on errors (such as terminating abnormally).
// This is important for running tests, since some of them use abnormal
// termination by design. This mode is inherited by all child processes.
unsafe {
let old_mode = SetErrorMode(SEM_NOGPFAULTERRORBOX); // read inherited flags
let old_mode = THREAD_ERROR_MODE(old_mode);
SetErrorMode(old_mode | SEM_NOGPFAULTERRORBOX);
let r = f();
SetErrorMode(old_mode);
r
}
}
#[cfg(not(windows))]
fn disable_error_reporting<F: FnOnce() -> R, R>(f: F) -> R {
f()
}
/// The platform-specific library name
pub fn get_lib_name(lib: &str, dylib: bool) -> String {
// In some casess (e.g. MUSL), we build a static
// library, rather than a dynamic library.
// In this case, the only path we can pass
// with '--extern-meta' is the '.lib' file
if !dylib {
return format!("lib{}.rlib", lib);
}
if cfg!(windows) {
format!("{}.dll", lib)
} else if cfg!(target_os = "macos") {
format!("lib{}.dylib", lib)
} else {
format!("lib{}.so", lib)
}
}
pub fn run(config: Arc<Config>, testpaths: &TestPaths, revision: Option<&str>) {
match &*config.target {
"arm-linux-androideabi"
| "armv7-linux-androideabi"
| "thumbv7neon-linux-androideabi"
| "aarch64-linux-android" => {
if !config.adb_device_status {
panic!("android device not available");
}
}
_ => {
// android has its own gdb handling
if config.debugger == Some(Debugger::Gdb) && config.gdb.is_none() {
panic!("gdb not available but debuginfo gdb debuginfo test requested");
}
}
}
if config.verbose {
// We're going to be dumping a lot of info. Start on a new line.
print!("\n\n");
}
debug!("running {:?}", testpaths.file.display());
let mut props = TestProps::from_file(&testpaths.file, revision, &config);
// For non-incremental (i.e. regular UI) tests, the incremental directory
// takes into account the revision name, since the revisions are independent
// of each other and can race.
if props.incremental {
props.incremental_dir = Some(incremental_dir(&config, testpaths, revision));
}
let cx = TestCx { config: &config, props: &props, testpaths, revision };
create_dir_all(&cx.output_base_dir())
.with_context(|| {
format!("failed to create output base directory {}", cx.output_base_dir().display())
})
.unwrap();
if props.incremental {
cx.init_incremental_test();
}
if config.mode == Incremental {
// Incremental tests are special because they cannot be run in
// parallel.
assert!(!props.revisions.is_empty(), "Incremental tests require revisions.");
for revision in &props.revisions {
let mut revision_props = TestProps::from_file(&testpaths.file, Some(revision), &config);
revision_props.incremental_dir = props.incremental_dir.clone();
let rev_cx = TestCx {
config: &config,
props: &revision_props,
testpaths,
revision: Some(revision),
};
rev_cx.run_revision();
}
} else {
cx.run_revision();
}
cx.create_stamp();
}
pub fn compute_stamp_hash(config: &Config) -> String {
let mut hash = DefaultHasher::new();
config.stage_id.hash(&mut hash);
config.run.hash(&mut hash);
match config.debugger {
Some(Debugger::Cdb) => {
config.cdb.hash(&mut hash);
}
Some(Debugger::Gdb) => {
config.gdb.hash(&mut hash);
env::var_os("PATH").hash(&mut hash);
env::var_os("PYTHONPATH").hash(&mut hash);
}
Some(Debugger::Lldb) => {
config.python.hash(&mut hash);
config.lldb_python_dir.hash(&mut hash);
env::var_os("PATH").hash(&mut hash);
env::var_os("PYTHONPATH").hash(&mut hash);
}
None => {}
}
if let Ui = config.mode {
config.force_pass_mode.hash(&mut hash);
}
format!("{:x}", hash.finish())
}
#[derive(Copy, Clone)]
struct TestCx<'test> {
config: &'test Config,
props: &'test TestProps,
testpaths: &'test TestPaths,
revision: Option<&'test str>,
}
enum ReadFrom {
Path,
Stdin(String),
}
enum TestOutput {
Compile,
Run,
}
/// Will this test be executed? Should we use `make_exe_name`?
#[derive(Copy, Clone, PartialEq)]
enum WillExecute {
Yes,
No,
Disabled,
}
/// What value should be passed to `--emit`?
#[derive(Copy, Clone)]
enum Emit {
None,
Metadata,
LlvmIr,
Asm,
LinkArgsAsm,
}
impl<'test> TestCx<'test> {
/// Code executed for each revision in turn (or, if there are no
/// revisions, exactly once, with revision == None).
fn run_revision(&self) {
if self.props.should_ice && self.config.mode != Incremental {
self.fatal("cannot use should-ice in a test that is not cfail");
}
match self.config.mode {
RunPassValgrind => self.run_valgrind_test(),
Pretty => self.run_pretty_test(),
DebugInfo => self.run_debuginfo_test(),
Codegen => self.run_codegen_test(),
Rustdoc => self.run_rustdoc_test(),
RustdocJson => self.run_rustdoc_json_test(),
CodegenUnits => self.run_codegen_units_test(),
Incremental => self.run_incremental_test(),
RunMake => self.run_rmake_test(),
Ui => self.run_ui_test(),
MirOpt => self.run_mir_opt_test(),
Assembly => self.run_assembly_test(),
JsDocTest => self.run_js_doc_test(),
CoverageMap => self.run_coverage_map_test(),
RunCoverage => self.run_coverage_test(),
}
}
fn pass_mode(&self) -> Option<PassMode> {
self.props.pass_mode(self.config)
}
fn should_run(&self, pm: Option<PassMode>) -> WillExecute {
let test_should_run = match self.config.mode {
Ui if pm == Some(PassMode::Run) || self.props.fail_mode == Some(FailMode::Run) => true,
MirOpt if pm == Some(PassMode::Run) => true,
Ui | MirOpt => false,
mode => panic!("unimplemented for mode {:?}", mode),
};
if test_should_run { self.run_if_enabled() } else { WillExecute::No }
}
fn run_if_enabled(&self) -> WillExecute {
if self.config.run_enabled() { WillExecute::Yes } else { WillExecute::Disabled }
}
fn should_run_successfully(&self, pm: Option<PassMode>) -> bool {
match self.config.mode {
Ui | MirOpt => pm == Some(PassMode::Run),
mode => panic!("unimplemented for mode {:?}", mode),
}
}
fn should_compile_successfully(&self, pm: Option<PassMode>) -> bool {
match self.config.mode {
JsDocTest => true,
Ui => pm.is_some() || self.props.fail_mode > Some(FailMode::Build),
Incremental => {
let revision =
self.revision.expect("incremental tests require a list of revisions");
if revision.starts_with("cpass")
|| revision.starts_with("rpass")
|| revision.starts_with("rfail")
{
true
} else if revision.starts_with("cfail") {
pm.is_some()
} else {
panic!("revision name must begin with cpass, rpass, rfail, or cfail");
}
}
mode => panic!("unimplemented for mode {:?}", mode),
}
}
fn check_if_test_should_compile(&self, proc_res: &ProcRes, pm: Option<PassMode>) {
if self.should_compile_successfully(pm) {
if !proc_res.status.success() {
self.fatal_proc_rec("test compilation failed although it shouldn't!", proc_res);
}
} else {
if proc_res.status.success() {
self.fatal_proc_rec(
&format!("{} test compiled successfully!", self.config.mode)[..],
proc_res,
);
}
if !self.props.dont_check_failure_status {
self.check_correct_failure_status(proc_res);
}
}
}
fn run_cfail_test(&self) {
let pm = self.pass_mode();
let proc_res = self.compile_test(WillExecute::No, self.should_emit_metadata(pm));
self.check_if_test_should_compile(&proc_res, pm);
self.check_no_compiler_crash(&proc_res, self.props.should_ice);
let output_to_check = self.get_output(&proc_res);
let expected_errors = errors::load_errors(&self.testpaths.file, self.revision);
if !expected_errors.is_empty() {
if !self.props.error_patterns.is_empty() || !self.props.regex_error_patterns.is_empty()
{
self.fatal("both error pattern and expected errors specified");
}
self.check_expected_errors(expected_errors, &proc_res);
} else {
self.check_all_error_patterns(&output_to_check, &proc_res, pm);
}
if self.props.should_ice {
match proc_res.status.code() {
Some(101) => (),
_ => self.fatal("expected ICE"),
}
}
self.check_forbid_output(&output_to_check, &proc_res);
}
fn run_rfail_test(&self) {
let pm = self.pass_mode();
let should_run = self.run_if_enabled();
let proc_res = self.compile_test(should_run, self.should_emit_metadata(pm));
if !proc_res.status.success() {
self.fatal_proc_rec("compilation failed!", &proc_res);
}
if let WillExecute::Disabled = should_run {
return;
}
let proc_res = self.exec_compiled_test();
// The value our Makefile configures valgrind to return on failure
const VALGRIND_ERR: i32 = 100;
if proc_res.status.code() == Some(VALGRIND_ERR) {
self.fatal_proc_rec("run-fail test isn't valgrind-clean!", &proc_res);
}
let output_to_check = self.get_output(&proc_res);
self.check_correct_failure_status(&proc_res);
self.check_all_error_patterns(&output_to_check, &proc_res, pm);
}
fn get_output(&self, proc_res: &ProcRes) -> String {
if self.props.check_stdout {
format!("{}{}", proc_res.stdout, proc_res.stderr)
} else {
proc_res.stderr.clone()
}
}
fn check_correct_failure_status(&self, proc_res: &ProcRes) {
let expected_status = Some(self.props.failure_status.unwrap_or(1));
let received_status = proc_res.status.code();
if expected_status != received_status {
self.fatal_proc_rec(
&format!(
"Error: expected failure status ({:?}) but received status {:?}.",
expected_status, received_status
),
proc_res,
);
}
}
fn run_cpass_test(&self) {
let emit_metadata = self.should_emit_metadata(self.pass_mode());
let proc_res = self.compile_test(WillExecute::No, emit_metadata);
if !proc_res.status.success() {
self.fatal_proc_rec("compilation failed!", &proc_res);
}
// FIXME(#41968): Move this check to tidy?
if !errors::load_errors(&self.testpaths.file, self.revision).is_empty() {
self.fatal("compile-pass tests with expected warnings should be moved to ui/");
}
}
fn run_rpass_test(&self) {
let emit_metadata = self.should_emit_metadata(self.pass_mode());
let should_run = self.run_if_enabled();
let proc_res = self.compile_test(should_run, emit_metadata);
if !proc_res.status.success() {
self.fatal_proc_rec("compilation failed!", &proc_res);
}
// FIXME(#41968): Move this check to tidy?
if !errors::load_errors(&self.testpaths.file, self.revision).is_empty() {
self.fatal("run-pass tests with expected warnings should be moved to ui/");
}
if let WillExecute::Disabled = should_run {
return;
}
let proc_res = self.exec_compiled_test();
if !proc_res.status.success() {
self.fatal_proc_rec("test run failed!", &proc_res);
}
}
fn run_valgrind_test(&self) {
assert!(self.revision.is_none(), "revisions not relevant here");
if self.config.valgrind_path.is_none() {
assert!(!self.config.force_valgrind);
return self.run_rpass_test();
}
let should_run = self.run_if_enabled();
let mut proc_res = self.compile_test(should_run, Emit::None);
if !proc_res.status.success() {
self.fatal_proc_rec("compilation failed!", &proc_res);
}
if let WillExecute::Disabled = should_run {
return;
}
let mut new_config = self.config.clone();
new_config.runtool = new_config.valgrind_path.clone();
let new_cx = TestCx { config: &new_config, ..*self };
proc_res = new_cx.exec_compiled_test();
if !proc_res.status.success() {
self.fatal_proc_rec("test run failed!", &proc_res);
}
}
fn run_coverage_map_test(&self) {
let Some(coverage_dump_path) = &self.config.coverage_dump_path else {
self.fatal("missing --coverage-dump");
};
let proc_res = self.compile_test_and_save_ir();
if !proc_res.status.success() {
self.fatal_proc_rec("compilation failed!", &proc_res);
}
drop(proc_res);
let llvm_ir_path = self.output_base_name().with_extension("ll");
let mut dump_command = Command::new(coverage_dump_path);
dump_command.arg(llvm_ir_path);
let proc_res = self.run_command_to_procres(&mut dump_command);
if !proc_res.status.success() {
self.fatal_proc_rec("coverage-dump failed!", &proc_res);
}
let kind = UI_COVERAGE_MAP;
let expected_coverage_dump = self.load_expected_output(kind);
let actual_coverage_dump = self.normalize_output(&proc_res.stdout, &[]);
let coverage_dump_errors = self.compare_output(
kind,
&actual_coverage_dump,
&expected_coverage_dump,
self.props.compare_output_lines_by_subset,
);
if coverage_dump_errors > 0 {
self.fatal_proc_rec(
&format!("{coverage_dump_errors} errors occurred comparing coverage output."),
&proc_res,
);
}
}
fn run_coverage_test(&self) {
let should_run = self.run_if_enabled();
let proc_res = self.compile_test(should_run, Emit::None);
if !proc_res.status.success() {
self.fatal_proc_rec("compilation failed!", &proc_res);
}
drop(proc_res);
if let WillExecute::Disabled = should_run {
return;
}
let profraw_path = self.output_base_dir().join("default.profraw");
let profdata_path = self.output_base_dir().join("default.profdata");
// Delete any existing profraw/profdata files to rule out unintended
// interference between repeated test runs.
if profraw_path.exists() {
std::fs::remove_file(&profraw_path).unwrap();
}
if profdata_path.exists() {
std::fs::remove_file(&profdata_path).unwrap();
}
let proc_res = self.exec_compiled_test_general(
&[("LLVM_PROFILE_FILE", &profraw_path.to_str().unwrap())],
false,
);
if self.props.failure_status.is_some() {
self.check_correct_failure_status(&proc_res);
} else if !proc_res.status.success() {
self.fatal_proc_rec("test run failed!", &proc_res);
}
drop(proc_res);
let mut profraw_paths = vec![profraw_path];
let mut bin_paths = vec![self.make_exe_name()];
if self.config.suite == "run-coverage-rustdoc" {
self.run_doctests_for_coverage(&mut profraw_paths, &mut bin_paths);
}
// Run `llvm-profdata merge` to index the raw coverage output.
let proc_res = self.run_llvm_tool("llvm-profdata", |cmd| {
cmd.args(["merge", "--sparse", "--output"]);
cmd.arg(&profdata_path);
cmd.args(&profraw_paths);
});
if !proc_res.status.success() {
self.fatal_proc_rec("llvm-profdata merge failed!", &proc_res);
}
drop(proc_res);
// Run `llvm-cov show` to produce a coverage report in text format.
let proc_res = self.run_llvm_tool("llvm-cov", |cmd| {
cmd.args(["show", "--format=text", "--show-line-counts-or-regions"]);
cmd.arg("--Xdemangler");
cmd.arg(self.config.rust_demangler_path.as_ref().unwrap());
cmd.arg("--instr-profile");
cmd.arg(&profdata_path);
for bin in &bin_paths {
cmd.arg("--object");
cmd.arg(bin);
}
});
if !proc_res.status.success() {
self.fatal_proc_rec("llvm-cov show failed!", &proc_res);
}
let kind = UI_COVERAGE;
let expected_coverage = self.load_expected_output(kind);
let normalized_actual_coverage =
self.normalize_coverage_output(&proc_res.stdout).unwrap_or_else(|err| {
self.fatal_proc_rec(&err, &proc_res);
});
let coverage_errors = self.compare_output(
kind,
&normalized_actual_coverage,
&expected_coverage,
self.props.compare_output_lines_by_subset,
);
if coverage_errors > 0 {
self.fatal_proc_rec(
&format!("{} errors occurred comparing coverage output.", coverage_errors),
&proc_res,
);
}
}
/// Run any doctests embedded in this test file, and add any resulting
/// `.profraw` files and doctest executables to the given vectors.
fn run_doctests_for_coverage(
&self,
profraw_paths: &mut Vec<PathBuf>,
bin_paths: &mut Vec<PathBuf>,
) {
// Put .profraw files and doctest executables in dedicated directories,
// to make it easier to glob them all later.
let profraws_dir = self.output_base_dir().join("doc_profraws");
let bins_dir = self.output_base_dir().join("doc_bins");
// Remove existing directories to prevent cross-run interference.
if profraws_dir.try_exists().unwrap() {
std::fs::remove_dir_all(&profraws_dir).unwrap();
}
if bins_dir.try_exists().unwrap() {
std::fs::remove_dir_all(&bins_dir).unwrap();
}
let mut rustdoc_cmd =
Command::new(self.config.rustdoc_path.as_ref().expect("--rustdoc-path not passed"));
// In general there will be multiple doctest binaries running, so we
// tell the profiler runtime to write their coverage data into separate
// profraw files.
rustdoc_cmd.env("LLVM_PROFILE_FILE", profraws_dir.join("%p-%m.profraw"));
rustdoc_cmd.args(["--test", "-Cinstrument-coverage"]);
// Without this, the doctests complain about not being able to find
// their enclosing file's crate for some reason.
rustdoc_cmd.args(["--crate-name", "workaround_for_79771"]);
// Persist the doctest binaries so that `llvm-cov show` can read their
// embedded coverage mappings later.
rustdoc_cmd.arg("-Zunstable-options");
rustdoc_cmd.arg("--persist-doctests");
rustdoc_cmd.arg(&bins_dir);
rustdoc_cmd.arg("-L");
rustdoc_cmd.arg(self.aux_output_dir_name());
rustdoc_cmd.arg(&self.testpaths.file);
let proc_res = self.compose_and_run_compiler(rustdoc_cmd, None);
if !proc_res.status.success() {
self.fatal_proc_rec("rustdoc --test failed!", &proc_res)
}
fn glob_iter(path: impl AsRef<Path>) -> impl Iterator<Item = PathBuf> {
let path_str = path.as_ref().to_str().unwrap();
let iter = glob(path_str).unwrap();
iter.map(Result::unwrap)
}
// Find all profraw files in the profraw directory.
for p in glob_iter(profraws_dir.join("*.profraw")) {
profraw_paths.push(p);
}
// Find all executables in the `--persist-doctests` directory, while
// avoiding other file types (e.g. `.pdb` on Windows). This doesn't
// need to be perfect, as long as it can handle the files actually
// produced by `rustdoc --test`.
for p in glob_iter(bins_dir.join("**/*")) {
let is_bin = p.is_file()
&& match p.extension() {
None => true,
Some(ext) => ext == OsStr::new("exe"),
};
if is_bin {
bin_paths.push(p);
}
}
}
fn run_llvm_tool(&self, name: &str, configure_cmd_fn: impl FnOnce(&mut Command)) -> ProcRes {
let tool_path = self
.config
.llvm_bin_dir
.as_ref()
.expect("this test expects the LLVM bin dir to be available")
.join(name);
let mut cmd = Command::new(tool_path);
configure_cmd_fn(&mut cmd);
self.run_command_to_procres(&mut cmd)
}
fn run_command_to_procres(&self, cmd: &mut Command) -> ProcRes {
let output = cmd.output().unwrap_or_else(|e| panic!("failed to exec `{cmd:?}`: {e:?}"));
let proc_res = ProcRes {
status: output.status,
stdout: String::from_utf8(output.stdout).unwrap(),
stderr: String::from_utf8(output.stderr).unwrap(),
truncated: Truncated::No,
cmdline: format!("{cmd:?}"),
};
self.dump_output(&proc_res.stdout, &proc_res.stderr);
proc_res
}
fn normalize_coverage_output(&self, coverage: &str) -> Result<String, String> {
let normalized = self.normalize_output(coverage, &[]);
let normalized = Self::anonymize_coverage_line_numbers(&normalized);
let mut lines = normalized.lines().collect::<Vec<_>>();
Self::sort_coverage_file_sections(&mut lines)?;
Self::sort_coverage_subviews(&mut lines)?;
let joined_lines = lines.iter().flat_map(|line| [line, "\n"]).collect::<String>();
Ok(joined_lines)
}
/// Replace line numbers in coverage reports with the placeholder `LL`,
/// so that the tests are less sensitive to lines being added/removed.
fn anonymize_coverage_line_numbers(coverage: &str) -> Cow<'_, str> {
// The coverage reporter prints line numbers at the start of a line.
// They are truncated or left-padded to occupy exactly 5 columns.
// (`LineNumberColumnWidth` in `SourceCoverageViewText.cpp`.)
// A pipe character `|` appears immediately after the final digit.
//
// Line numbers that appear inside expansion/instantiation subviews
// have an additional prefix of ` |` for each nesting level.
static LINE_NUMBER_RE: Lazy<Regex> =
Lazy::new(|| Regex::new(r"(?m:^)(?<prefix>(?: \|)*) *[0-9]+\|").unwrap());
LINE_NUMBER_RE.replace_all(coverage, "$prefix LL|")
}
/// Coverage reports can describe multiple source files, separated by
/// blank lines. The order of these files is unpredictable (since it
/// depends on implementation details), so we need to sort the file
/// sections into a consistent order before comparing against a snapshot.
fn sort_coverage_file_sections(coverage_lines: &mut Vec<&str>) -> Result<(), String> {
// Group the lines into file sections, separated by blank lines.
let mut sections = coverage_lines.split(|line| line.is_empty()).collect::<Vec<_>>();
// The last section should be empty, representing an extra trailing blank line.
if !sections.last().is_some_and(|last| last.is_empty()) {
return Err("coverage report should end with an extra blank line".to_owned());
}
// Sort the file sections (not including the final empty "section").
let except_last = sections.len() - 1;
(&mut sections[..except_last]).sort();
// Join the file sections back into a flat list of lines, with
// sections separated by blank lines.
let joined = sections.join(&[""] as &[_]);
assert_eq!(joined.len(), coverage_lines.len());
*coverage_lines = joined;
Ok(())
}
fn sort_coverage_subviews(coverage_lines: &mut Vec<&str>) -> Result<(), String> {
let mut output_lines = Vec::new();
// We accumulate a list of zero or more "subviews", where each
// subview is a list of one or more lines.
let mut subviews: Vec<Vec<&str>> = Vec::new();
fn flush<'a>(subviews: &mut Vec<Vec<&'a str>>, output_lines: &mut Vec<&'a str>) {
if subviews.is_empty() {
return;
}
// Take and clear the list of accumulated subviews.
let mut subviews = std::mem::take(subviews);
// The last "subview" should be just a boundary line on its own,
// so exclude it when sorting the other subviews.
let except_last = subviews.len() - 1;
(&mut subviews[..except_last]).sort();
for view in subviews {
for line in view {
output_lines.push(line);
}
}
}
for (line, line_num) in coverage_lines.iter().zip(1..) {
if line.starts_with(" ------------------") {
// This is a subview boundary line, so start a new subview.
subviews.push(vec![line]);
} else if line.starts_with(" |") {
// Add this line to the current subview.
subviews
.last_mut()
.ok_or(format!(
"unexpected subview line outside of a subview on line {line_num}"
))?
.push(line);
} else {
// This line is not part of a subview, so sort and print any
// accumulated subviews, and then print the line as-is.
flush(&mut subviews, &mut output_lines);
output_lines.push(line);
}
}
flush(&mut subviews, &mut output_lines);
assert!(subviews.is_empty());
assert_eq!(output_lines.len(), coverage_lines.len());
*coverage_lines = output_lines;
Ok(())
}
fn run_pretty_test(&self) {
if self.props.pp_exact.is_some() {
logv(self.config, "testing for exact pretty-printing".to_owned());
} else {
logv(self.config, "testing for converging pretty-printing".to_owned());
}
let rounds = match self.props.pp_exact {
Some(_) => 1,
None => 2,
};
let src = fs::read_to_string(&self.testpaths.file).unwrap();
let mut srcs = vec![src];
let mut round = 0;
while round < rounds {
logv(
self.config,
format!("pretty-printing round {} revision {:?}", round, self.revision),
);
let read_from =
if round == 0 { ReadFrom::Path } else { ReadFrom::Stdin(srcs[round].to_owned()) };
let proc_res = self.print_source(read_from, &self.props.pretty_mode);
if !proc_res.status.success() {
self.fatal_proc_rec(
&format!(
"pretty-printing failed in round {} revision {:?}",
round, self.revision
),
&proc_res,
);
}
let ProcRes { stdout, .. } = proc_res;
srcs.push(stdout);
round += 1;
}
let mut expected = match self.props.pp_exact {
Some(ref file) => {
let filepath = self.testpaths.file.parent().unwrap().join(file);
fs::read_to_string(&filepath).unwrap()
}
None => srcs[srcs.len() - 2].clone(),
};
let mut actual = srcs[srcs.len() - 1].clone();
if self.props.pp_exact.is_some() {
// Now we have to care about line endings
let cr = "\r".to_owned();
actual = actual.replace(&cr, "");
expected = expected.replace(&cr, "");
}
if !self.config.bless {
self.compare_source(&expected, &actual);
} else if expected != actual {
let filepath_buf;
let filepath = match &self.props.pp_exact {
Some(file) => {
filepath_buf = self.testpaths.file.parent().unwrap().join(file);
&filepath_buf
}
None => &self.testpaths.file,
};
fs::write(filepath, &actual).unwrap();
}
// If we're only making sure that the output matches then just stop here
if self.props.pretty_compare_only {
return;
}
// Finally, let's make sure it actually appears to remain valid code
let proc_res = self.typecheck_source(actual);
if !proc_res.status.success() {
self.fatal_proc_rec("pretty-printed source does not typecheck", &proc_res);
}
if !self.props.pretty_expanded {
return;
}
// additionally, run `-Zunpretty=expanded` and try to build it.
let proc_res = self.print_source(ReadFrom::Path, "expanded");
if !proc_res.status.success() {
self.fatal_proc_rec("pretty-printing (expanded) failed", &proc_res);
}
let ProcRes { stdout: expanded_src, .. } = proc_res;
let proc_res = self.typecheck_source(expanded_src);
if !proc_res.status.success() {
self.fatal_proc_rec("pretty-printed source (expanded) does not typecheck", &proc_res);
}
}
fn print_source(&self, read_from: ReadFrom, pretty_type: &str) -> ProcRes {
let aux_dir = self.aux_output_dir_name();
let input: &str = match read_from {
ReadFrom::Stdin(_) => "-",
ReadFrom::Path => self.testpaths.file.to_str().unwrap(),
};
let mut rustc = Command::new(&self.config.rustc_path);
rustc
.arg(input)
.args(&["-Z", &format!("unpretty={}", pretty_type)])
.args(&["--target", &self.config.target])
.arg("-L")
.arg(&aux_dir)
.arg("-A")
.arg("internal_features")
.args(&self.props.compile_flags)
.envs(self.props.rustc_env.clone());
self.maybe_add_external_args(&mut rustc, &self.config.target_rustcflags);
let src = match read_from {
ReadFrom::Stdin(src) => Some(src),
ReadFrom::Path => None,
};
self.compose_and_run(
rustc,
self.config.compile_lib_path.to_str().unwrap(),
Some(aux_dir.to_str().unwrap()),
src,
)
}
fn compare_source(&self, expected: &str, actual: &str) {
if expected != actual {
self.fatal(&format!(
"pretty-printed source does not match expected source\n\
expected:\n\
------------------------------------------\n\
{}\n\
------------------------------------------\n\
actual:\n\
------------------------------------------\n\
{}\n\
------------------------------------------\n\
diff:\n\
------------------------------------------\n\
{}\n",
expected,
actual,
write_diff(expected, actual, 3),
));
}
}
fn set_revision_flags(&self, cmd: &mut Command) {
if let Some(revision) = self.revision {
// Normalize revisions to be lowercase and replace `-`s with `_`s.
// Otherwise the `--cfg` flag is not valid.
let normalized_revision = revision.to_lowercase().replace("-", "_");
cmd.args(&["--cfg", &normalized_revision]);
}
}
fn typecheck_source(&self, src: String) -> ProcRes {
let mut rustc = Command::new(&self.config.rustc_path);
let out_dir = self.output_base_name().with_extension("pretty-out");
let _ = fs::remove_dir_all(&out_dir);
create_dir_all(&out_dir).unwrap();
let target = if self.props.force_host { &*self.config.host } else { &*self.config.target };
let aux_dir = self.aux_output_dir_name();
rustc
.arg("-")
.arg("-Zno-codegen")
.arg("--out-dir")
.arg(&out_dir)
.arg(&format!("--target={}", target))