forked from rust-lang/rust
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathruntest.rs
2935 lines (2623 loc) · 110 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
use std::borrow::Cow;
use std::collections::{HashMap, HashSet};
use std::ffi::{OsStr, OsString};
use std::fs::{self, File, create_dir_all};
use std::hash::{DefaultHasher, Hash, Hasher};
use std::io::prelude::*;
use std::io::{self, BufReader};
use std::path::{Path, PathBuf};
use std::process::{Child, Command, ExitStatus, Output, Stdio};
use std::sync::Arc;
use std::{env, iter, str};
use anyhow::Context;
use colored::Colorize;
use regex::{Captures, Regex};
use tracing::*;
use crate::common::{
Assembly, Codegen, CodegenUnits, CompareMode, Config, CoverageMap, CoverageRun, Crashes,
DebugInfo, Debugger, FailMode, Incremental, MirOpt, PassMode, Pretty, RunMake, Rustdoc,
RustdocJs, RustdocJson, TestPaths, UI_EXTENSIONS, UI_FIXED, UI_RUN_STDERR, UI_RUN_STDOUT,
UI_STDERR, UI_STDOUT, UI_SVG, UI_WINDOWS_SVG, Ui, expected_output_path, incremental_dir,
output_base_dir, output_base_name, output_testname_unique,
};
use crate::compute_diff::{DiffLine, make_diff, write_diff, write_filtered_diff};
use crate::errors::{self, Error, ErrorKind};
use crate::header::TestProps;
use crate::read2::{Truncated, read2_abbreviated};
use crate::util::{PathBufExt, add_dylib_path, logv, static_regex};
use crate::{ColorConfig, json, stamp_file_path};
mod debugger;
// Helper modules that implement test running logic for each test suite.
// tidy-alphabetical-start
mod assembly;
mod codegen;
mod codegen_units;
mod coverage;
mod crashes;
mod debuginfo;
mod incremental;
mod js_doc;
mod mir_opt;
mod pretty;
mod run_make;
mod rustdoc;
mod rustdoc_json;
mod ui;
// tidy-alphabetical-end
#[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::{
SEM_FAILCRITICALERRORS, SEM_NOGPFAULTERRORBOX, SetErrorMode,
};
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.
//
// Note that `run-make` tests require `SEM_FAILCRITICALERRORS` in addition to suppress Windows
// Error Reporting (WER) error dialogues that come from "critical failures" such as missing
// DLLs.
//
// See <https://github.com/rust-lang/rust/issues/132092> and
// <https://learn.microsoft.com/en-us/windows/win32/api/errhandlingapi/nf-errhandlingapi-seterrormode?redirectedfrom=MSDN>.
unsafe {
// read inherited flags
let old_mode = SetErrorMode(SEM_NOGPFAULTERRORBOX | SEM_FAILCRITICALERRORS);
SetErrorMode(old_mode | SEM_NOGPFAULTERRORBOX | SEM_FAILCRITICALERRORS);
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
fn get_lib_name(name: &str, aux_type: AuxType) -> Option<String> {
match aux_type {
AuxType::Bin => None,
// In some cases (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 '.rlib' file
AuxType::Lib => Some(format!("lib{name}.rlib")),
AuxType::Dylib | AuxType::ProcMacro => Some(dylib_name(name)),
}
}
fn dylib_name(name: &str) -> String {
format!("{}{name}.{}", std::env::consts::DLL_PREFIX, std::env::consts::DLL_EXTENSION)
}
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())
}
fn remove_and_create_dir_all(path: &Path) {
let _ = fs::remove_dir_all(path);
fs::create_dir_all(path).unwrap();
}
#[derive(Copy, Clone, Debug)]
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,
Mir,
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.config.mode != Crashes {
self.fatal("cannot use should-ice in a test that is not cfail");
}
match self.config.mode {
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(),
RustdocJs => self.run_rustdoc_js_test(),
CoverageMap => self.run_coverage_map_test(), // see self::coverage
CoverageRun => self.run_coverage_run_test(), // see self::coverage
Crashes => self.run_crash_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 {
RustdocJs => true,
Ui => pm.is_some() || self.props.fail_mode > Some(FailMode::Build),
Crashes => false,
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,
fail_mode: Option<FailMode>,
pass_mode: Option<PassMode>,
proc_res: &ProcRes,
) {
if self.should_compile_successfully(pass_mode) {
if !proc_res.status.success() {
match (fail_mode, pass_mode) {
(Some(FailMode::Build), Some(PassMode::Check)) => {
// A `build-fail` test needs to `check-pass`.
self.fatal_proc_rec(
"`build-fail` test is required to pass check build, but check build failed",
proc_res,
);
}
_ => {
self.fatal_proc_rec(
"test compilation failed although it shouldn't!",
proc_res,
);
}
}
}
} else {
if proc_res.status.success() {
{
self.error(&format!("{} test did not emit an error", self.config.mode));
if self.config.mode == crate::common::Mode::Ui {
println!("note: by default, ui tests are expected not to compile");
}
proc_res.fatal(None, || ());
};
}
if !self.props.dont_check_failure_status {
self.check_correct_failure_status(proc_res);
}
}
}
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,
);
}
}
/// Runs a [`Command`] and waits for it to finish, then converts its exit
/// status and output streams into a [`ProcRes`].
///
/// The command might have succeeded or failed; it is the caller's
/// responsibility to check the exit status and take appropriate action.
///
/// # Panics
/// Panics if the command couldn't be executed at all
/// (e.g. because the executable could not be found).
#[must_use = "caller should check whether the command succeeded"]
fn run_command_to_procres(&self, cmd: &mut Command) -> ProcRes {
let output = cmd
.output()
.unwrap_or_else(|e| self.fatal(&format!("failed to exec `{cmd:?}` because: {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(
self.config.verbose,
&cmd.get_program().to_string_lossy(),
&proc_res.stdout,
&proc_res.stderr,
);
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) {
// Normalize revisions to be lowercase and replace `-`s with `_`s.
// Otherwise the `--cfg` flag is not valid.
let normalize_revision = |revision: &str| revision.to_lowercase().replace("-", "_");
if let Some(revision) = self.revision {
let normalized_revision = normalize_revision(revision);
let cfg_arg = ["--cfg", &normalized_revision];
let arg = format!("--cfg={normalized_revision}");
if self
.props
.compile_flags
.windows(2)
.any(|args| args == cfg_arg || args[0] == arg || args[1] == arg)
{
panic!(
"error: redundant cfg argument `{normalized_revision}` is already created by the revision"
);
}
if self.config.builtin_cfg_names().contains(&normalized_revision) {
panic!("error: revision `{normalized_revision}` collides with a builtin cfg");
}
cmd.args(cfg_arg);
}
if !self.props.no_auto_check_cfg {
let mut check_cfg = String::with_capacity(25);
// Generate `cfg(FALSE, REV1, ..., REVN)` (for all possible revisions)
//
// For compatibility reason we consider the `FALSE` cfg to be expected
// since it is extensively used in the testsuite, as well as the `test`
// cfg since we have tests that uses it.
check_cfg.push_str("cfg(test,FALSE");
for revision in &self.props.revisions {
check_cfg.push(',');
check_cfg.push_str(&normalize_revision(revision));
}
check_cfg.push(')');
cmd.args(&["--check-cfg", &check_cfg]);
}
}
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");
remove_and_create_dir_all(&out_dir);
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))
.arg("-L")
// FIXME(jieyouxu): this search path seems questionable. Is this intended for
// `rust_test_helpers` in ui tests?
.arg(&self.config.build_test_suite_root)
.arg("-L")
.arg(aux_dir)
.arg("-A")
.arg("internal_features");
self.set_revision_flags(&mut rustc);
self.maybe_add_external_args(&mut rustc, &self.config.target_rustcflags);
rustc.args(&self.props.compile_flags);
self.compose_and_run_compiler(rustc, Some(src), self.testpaths)
}
fn maybe_add_external_args(&self, cmd: &mut Command, args: &Vec<String>) {
// Filter out the arguments that should not be added by runtest here.
//
// Notable use-cases are: do not add our optimisation flag if
// `compile-flags: -Copt-level=x` and similar for debug-info level as well.
const OPT_FLAGS: &[&str] = &["-O", "-Copt-level=", /*-C<space>*/ "opt-level="];
const DEBUG_FLAGS: &[&str] = &["-g", "-Cdebuginfo=", /*-C<space>*/ "debuginfo="];
// FIXME: ideally we would "just" check the `cmd` itself, but it does not allow inspecting
// its arguments. They need to be collected separately. For now I cannot be bothered to
// implement this the "right" way.
let have_opt_flag =
self.props.compile_flags.iter().any(|arg| OPT_FLAGS.iter().any(|f| arg.starts_with(f)));
let have_debug_flag = self
.props
.compile_flags
.iter()
.any(|arg| DEBUG_FLAGS.iter().any(|f| arg.starts_with(f)));
for arg in args {
if OPT_FLAGS.iter().any(|f| arg.starts_with(f)) && have_opt_flag {
continue;
}
if DEBUG_FLAGS.iter().any(|f| arg.starts_with(f)) && have_debug_flag {
continue;
}
cmd.arg(arg);
}
}
fn check_all_error_patterns(
&self,
output_to_check: &str,
proc_res: &ProcRes,
pm: Option<PassMode>,
) {
if self.props.error_patterns.is_empty() && self.props.regex_error_patterns.is_empty() {
if pm.is_some() {
// FIXME(#65865)
return;
} else {
self.fatal(&format!(
"no error pattern specified in {:?}",
self.testpaths.file.display()
));
}
}
let mut missing_patterns: Vec<String> = Vec::new();
self.check_error_patterns(output_to_check, &mut missing_patterns);
self.check_regex_error_patterns(output_to_check, proc_res, &mut missing_patterns);
if missing_patterns.is_empty() {
return;
}
if missing_patterns.len() == 1 {
self.fatal_proc_rec(
&format!("error pattern '{}' not found!", missing_patterns[0]),
proc_res,
);
} else {
for pattern in missing_patterns {
self.error(&format!("error pattern '{}' not found!", pattern));
}
self.fatal_proc_rec("multiple error patterns not found", proc_res);
}
}
fn check_error_patterns(&self, output_to_check: &str, missing_patterns: &mut Vec<String>) {
debug!("check_error_patterns");
for pattern in &self.props.error_patterns {
if output_to_check.contains(pattern.trim()) {
debug!("found error pattern {}", pattern);
} else {
missing_patterns.push(pattern.to_string());
}
}
}
fn check_regex_error_patterns(
&self,
output_to_check: &str,
proc_res: &ProcRes,
missing_patterns: &mut Vec<String>,
) {
debug!("check_regex_error_patterns");
for pattern in &self.props.regex_error_patterns {
let pattern = pattern.trim();
let re = match Regex::new(pattern) {
Ok(re) => re,
Err(err) => {
self.fatal_proc_rec(
&format!("invalid regex error pattern '{}': {:?}", pattern, err),
proc_res,
);
}
};
if re.is_match(output_to_check) {
debug!("found regex error pattern {}", pattern);
} else {
missing_patterns.push(pattern.to_string());
}
}
}
fn check_no_compiler_crash(&self, proc_res: &ProcRes, should_ice: bool) {
match proc_res.status.code() {
Some(101) if !should_ice => {
self.fatal_proc_rec("compiler encountered internal error", proc_res)
}
None => self.fatal_proc_rec("compiler terminated by signal", proc_res),
_ => (),
}
}
fn check_forbid_output(&self, output_to_check: &str, proc_res: &ProcRes) {
for pat in &self.props.forbid_output {
if output_to_check.contains(pat) {
self.fatal_proc_rec("forbidden pattern found in compiler output", proc_res);
}
}
}
fn check_expected_errors(&self, expected_errors: Vec<errors::Error>, proc_res: &ProcRes) {
debug!(
"check_expected_errors: expected_errors={:?} proc_res.status={:?}",
expected_errors, proc_res.status
);
if proc_res.status.success()
&& expected_errors.iter().any(|x| x.kind == Some(ErrorKind::Error))
{
self.fatal_proc_rec("process did not return an error status", proc_res);
}
if self.props.known_bug {
if !expected_errors.is_empty() {
self.fatal_proc_rec(
"`known_bug` tests should not have an expected error",
proc_res,
);
}
return;
}
// On Windows, translate all '\' path separators to '/'
let file_name = format!("{}", self.testpaths.file.display()).replace(r"\", "/");
// On Windows, keep all '\' path separators to match the paths reported in the JSON output
// from the compiler
let diagnostic_file_name = if self.props.remap_src_base {
let mut p = PathBuf::from(FAKE_SRC_BASE);
p.push(&self.testpaths.relative_dir);
p.push(self.testpaths.file.file_name().unwrap());
p.display().to_string()
} else {
self.testpaths.file.display().to_string()
};
// If the testcase being checked contains at least one expected "help"
// message, then we'll ensure that all "help" messages are expected.
// Otherwise, all "help" messages reported by the compiler will be ignored.
// This logic also applies to "note" messages.
let expect_help = expected_errors.iter().any(|ee| ee.kind == Some(ErrorKind::Help));
let expect_note = expected_errors.iter().any(|ee| ee.kind == Some(ErrorKind::Note));
// Parse the JSON output from the compiler and extract out the messages.
let actual_errors = json::parse_output(&diagnostic_file_name, &proc_res.stderr, proc_res);
let mut unexpected = Vec::new();
let mut found = vec![false; expected_errors.len()];
for mut actual_error in actual_errors {
actual_error.msg = self.normalize_output(&actual_error.msg, &[]);
let opt_index =
expected_errors.iter().enumerate().position(|(index, expected_error)| {
!found[index]
&& actual_error.line_num == expected_error.line_num
&& (expected_error.kind.is_none()
|| actual_error.kind == expected_error.kind)
&& actual_error.msg.contains(&expected_error.msg)
});
match opt_index {
Some(index) => {
// found a match, everybody is happy
assert!(!found[index]);
found[index] = true;
}
None => {
// If the test is a known bug, don't require that the error is annotated
if self.is_unexpected_compiler_message(&actual_error, expect_help, expect_note)
{
self.error(&format!(
"{}:{}: unexpected {}: '{}'",
file_name,
actual_error.line_num_str(),
actual_error
.kind
.as_ref()
.map_or(String::from("message"), |k| k.to_string()),
actual_error.msg
));
unexpected.push(actual_error);
}
}
}
}
let mut not_found = Vec::new();
// anything not yet found is a problem
for (index, expected_error) in expected_errors.iter().enumerate() {
if !found[index] {
self.error(&format!(
"{}:{}: expected {} not found: {}",
file_name,
expected_error.line_num_str(),
expected_error.kind.as_ref().map_or("message".into(), |k| k.to_string()),
expected_error.msg
));
not_found.push(expected_error);
}
}
if !unexpected.is_empty() || !not_found.is_empty() {
self.error(&format!(
"{} unexpected errors found, {} expected errors not found",
unexpected.len(),
not_found.len()
));
println!("status: {}\ncommand: {}\n", proc_res.status, proc_res.cmdline);
if !unexpected.is_empty() {
println!("{}", "--- unexpected errors (from JSON output) ---".green());
for error in &unexpected {
println!("{}", error.render_for_expected());
}
println!("{}", "---".green());
}
if !not_found.is_empty() {
println!("{}", "--- not found errors (from test file) ---".red());
for error in ¬_found {
println!("{}", error.render_for_expected());
}
println!("{}", "---\n".red());
}
panic!("errors differ from expected");
}
}
/// Returns `true` if we should report an error about `actual_error`,
/// which did not match any of the expected error. We always require
/// errors/warnings to be explicitly listed, but only require
/// helps/notes if there are explicit helps/notes given.
fn is_unexpected_compiler_message(
&self,
actual_error: &Error,
expect_help: bool,
expect_note: bool,
) -> bool {
!actual_error.msg.is_empty()
&& match actual_error.kind {
Some(ErrorKind::Help) => expect_help,
Some(ErrorKind::Note) => expect_note,
Some(ErrorKind::Error) | Some(ErrorKind::Warning) => true,
Some(ErrorKind::Suggestion) | None => false,
}
}
fn should_emit_metadata(&self, pm: Option<PassMode>) -> Emit {
match (pm, self.props.fail_mode, self.config.mode) {
(Some(PassMode::Check), ..) | (_, Some(FailMode::Check), Ui) => Emit::Metadata,
_ => Emit::None,
}
}
fn compile_test(&self, will_execute: WillExecute, emit: Emit) -> ProcRes {
self.compile_test_general(will_execute, emit, self.props.local_pass_mode(), Vec::new())
}
fn compile_test_with_passes(
&self,
will_execute: WillExecute,
emit: Emit,
passes: Vec<String>,
) -> ProcRes {
self.compile_test_general(will_execute, emit, self.props.local_pass_mode(), passes)
}
fn compile_test_general(
&self,
will_execute: WillExecute,
emit: Emit,
local_pm: Option<PassMode>,
passes: Vec<String>,
) -> ProcRes {
// Only use `make_exe_name` when the test ends up being executed.
let output_file = match will_execute {
WillExecute::Yes => TargetLocation::ThisFile(self.make_exe_name()),
WillExecute::No | WillExecute::Disabled => {
TargetLocation::ThisDirectory(self.output_base_dir())
}
};
let allow_unused = match self.config.mode {
Ui => {
// UI tests tend to have tons of unused code as
// it's just testing various pieces of the compile, but we don't
// want to actually assert warnings about all this code. Instead
// let's just ignore unused code warnings by defaults and tests
// can turn it back on if needed.
if !self.is_rustdoc()
// Note that we use the local pass mode here as we don't want
// to set unused to allow if we've overridden the pass mode
// via command line flags.
&& local_pm != Some(PassMode::Run)
{
AllowUnused::Yes
} else {
AllowUnused::No
}
}
_ => AllowUnused::No,
};
let rustc = self.make_compile_args(
&self.testpaths.file,
output_file,
emit,
allow_unused,
LinkToAux::Yes,
passes,
);
self.compose_and_run_compiler(rustc, None, self.testpaths)
}
/// `root_out_dir` and `root_testpaths` refer to the parameters of the actual test being run.
/// Auxiliaries, no matter how deep, have the same root_out_dir and root_testpaths.
fn document(&self, root_out_dir: &Path, root_testpaths: &TestPaths) -> ProcRes {
if self.props.build_aux_docs {
for rel_ab in &self.props.aux.builds {
let aux_testpaths = self.compute_aux_test_paths(root_testpaths, rel_ab);
let props_for_aux =
self.props.from_aux_file(&aux_testpaths.file, self.revision, self.config);
let aux_cx = TestCx {
config: self.config,
props: &props_for_aux,
testpaths: &aux_testpaths,
revision: self.revision,
};
// Create the directory for the stdout/stderr files.
create_dir_all(aux_cx.output_base_dir()).unwrap();
// use root_testpaths here, because aux-builds should have the
// same --out-dir and auxiliary directory.
let auxres = aux_cx.document(&root_out_dir, root_testpaths);
if !auxres.status.success() {
return auxres;
}
}
}
let aux_dir = self.aux_output_dir_name();
let rustdoc_path = self.config.rustdoc_path.as_ref().expect("--rustdoc-path not passed");
// actual --out-dir given to the auxiliary or test, as opposed to the root out dir for the entire
// test
let out_dir: Cow<'_, Path> = if self.props.unique_doc_out_dir {
let file_name = self.testpaths.file.file_stem().expect("file name should not be empty");
let out_dir = PathBuf::from_iter([
root_out_dir,
Path::new("docs"),
Path::new(file_name),
Path::new("doc"),
]);
create_dir_all(&out_dir).unwrap();
Cow::Owned(out_dir)
} else {
Cow::Borrowed(root_out_dir)
};
let mut rustdoc = Command::new(rustdoc_path);
let current_dir = output_base_dir(self.config, root_testpaths, self.safe_revision());
rustdoc.current_dir(current_dir);
rustdoc
.arg("-L")
.arg(self.config.run_lib_path.to_str().unwrap())
.arg("-L")
.arg(aux_dir)
.arg("-o")
.arg(out_dir.as_ref())
.arg("--deny")
.arg("warnings")
.arg(&self.testpaths.file)
.arg("-A")
.arg("internal_features")
.args(&self.props.compile_flags)
.args(&self.props.doc_flags);
if self.config.mode == RustdocJson {
rustdoc.arg("--output-format").arg("json").arg("-Zunstable-options");
}
if let Some(ref linker) = self.config.target_linker {
rustdoc.arg(format!("-Clinker={}", linker));
}
self.compose_and_run_compiler(rustdoc, None, root_testpaths)
}
fn exec_compiled_test(&self) -> ProcRes {
self.exec_compiled_test_general(&[], true)
}
fn exec_compiled_test_general(
&self,
env_extra: &[(&str, &str)],
delete_after_success: bool,
) -> ProcRes {
let prepare_env = |cmd: &mut Command| {
for key in &self.props.unset_exec_env {
cmd.env_remove(key);
}
for (key, val) in &self.props.exec_env {
cmd.env(key, val);
}
for (key, val) in env_extra {
cmd.env(key, val);
}
};
let proc_res = match &*self.config.target {
// This is pretty similar to below, we're transforming:
//
// program arg1 arg2
//
// into
//
// remote-test-client run program 2 support-lib.so support-lib2.so arg1 arg2
//
// The test-client program will upload `program` to the emulator
// along with all other support libraries listed (in this case
// `support-lib.so` and `support-lib2.so`. It will then execute
// the program on the emulator with the arguments specified
// (in the environment we give the process) and then report back
// the same result.