1use std::borrow::Cow;
2use std::collections::{HashMap, HashSet};
3use std::ffi::OsString;
4use std::fs::{self, create_dir_all};
5use std::hash::{DefaultHasher, Hash, Hasher};
6use std::io::prelude::*;
7use std::process::{Child, Command, ExitStatus, Output, Stdio};
8use std::{env, fmt, io, iter, str};
9
10use build_helper::fs::remove_and_create_dir_all;
11use camino::{Utf8Path, Utf8PathBuf};
12use colored::{Color, Colorize};
13use regex::{Captures, Regex};
14use tracing::*;
15
16use crate::common::{
17 CompareMode, Config, Debugger, FailMode, PassMode, RunFailMode, RunResult, TestMode, TestPaths,
18 TestSuite, UI_EXTENSIONS, UI_FIXED, UI_RUN_STDERR, UI_RUN_STDOUT, UI_STDERR, UI_STDOUT, UI_SVG,
19 UI_WINDOWS_SVG, expected_output_path, incremental_dir, output_base_dir, output_base_name,
20};
21use crate::directives::{AuxCrate, TestProps};
22use crate::errors::{Error, ErrorKind, load_errors};
23use crate::output_capture::ConsoleOut;
24use crate::read2::{Truncated, read2_abbreviated};
25use crate::runtest::compute_diff::{DiffLine, make_diff, write_diff};
26use crate::util::{Utf8PathBufExt, add_dylib_path, static_regex};
27use crate::{json, stamp_file_path};
28
29mod assembly;
32mod codegen;
33mod codegen_units;
34mod coverage;
35mod crashes;
36mod debuginfo;
37mod incremental;
38mod js_doc;
39mod mir_opt;
40mod pretty;
41mod run_make;
42mod rustdoc;
43mod rustdoc_json;
44mod ui;
45mod compute_diff;
48mod debugger;
49#[cfg(test)]
50mod tests;
51
52const FAKE_SRC_BASE: &str = "fake-test-src-base";
53
54#[cfg(windows)]
55fn disable_error_reporting<F: FnOnce() -> R, R>(f: F) -> R {
56 use std::sync::Mutex;
57
58 use windows::Win32::System::Diagnostics::Debug::{
59 SEM_FAILCRITICALERRORS, SEM_NOGPFAULTERRORBOX, SetErrorMode,
60 };
61
62 static LOCK: Mutex<()> = Mutex::new(());
63
64 let _lock = LOCK.lock().unwrap();
66
67 unsafe {
78 let old_mode = SetErrorMode(SEM_NOGPFAULTERRORBOX | SEM_FAILCRITICALERRORS);
80 SetErrorMode(old_mode | SEM_NOGPFAULTERRORBOX | SEM_FAILCRITICALERRORS);
81 let r = f();
82 SetErrorMode(old_mode);
83 r
84 }
85}
86
87#[cfg(not(windows))]
88fn disable_error_reporting<F: FnOnce() -> R, R>(f: F) -> R {
89 f()
90}
91
92fn get_lib_name(name: &str, aux_type: AuxType) -> Option<String> {
94 match aux_type {
95 AuxType::Bin => None,
96 AuxType::Lib => Some(format!("lib{name}.rlib")),
101 AuxType::Dylib | AuxType::ProcMacro => Some(dylib_name(name)),
102 }
103}
104
105fn dylib_name(name: &str) -> String {
106 format!("{}{name}.{}", std::env::consts::DLL_PREFIX, std::env::consts::DLL_EXTENSION)
107}
108
109pub fn run(
110 config: &Config,
111 stdout: &dyn ConsoleOut,
112 stderr: &dyn ConsoleOut,
113 testpaths: &TestPaths,
114 revision: Option<&str>,
115) {
116 match &*config.target {
117 "arm-linux-androideabi"
118 | "armv7-linux-androideabi"
119 | "thumbv7neon-linux-androideabi"
120 | "aarch64-linux-android" => {
121 if !config.adb_device_status {
122 panic!("android device not available");
123 }
124 }
125
126 _ => {
127 if config.debugger == Some(Debugger::Gdb) && config.gdb.is_none() {
131 panic!("gdb not available but debuginfo gdb debuginfo test requested");
132 }
133 }
134 }
135
136 if config.verbose {
137 write!(stdout, "\n\n");
139 }
140 debug!("running {}", testpaths.file);
141 let mut props = TestProps::from_file(&testpaths.file, revision, &config);
142
143 if props.incremental {
147 props.incremental_dir = Some(incremental_dir(&config, testpaths, revision));
148 }
149
150 let cx = TestCx { config: &config, stdout, stderr, props: &props, testpaths, revision };
151
152 if let Err(e) = create_dir_all(&cx.output_base_dir()) {
153 panic!("failed to create output base directory {}: {e}", cx.output_base_dir());
154 }
155
156 if props.incremental {
157 cx.init_incremental_test();
158 }
159
160 if config.mode == TestMode::Incremental {
161 assert!(!props.revisions.is_empty(), "Incremental tests require revisions.");
164 for revision in &props.revisions {
165 let mut revision_props = TestProps::from_file(&testpaths.file, Some(revision), &config);
166 revision_props.incremental_dir = props.incremental_dir.clone();
167 let rev_cx = TestCx {
168 config: &config,
169 stdout,
170 stderr,
171 props: &revision_props,
172 testpaths,
173 revision: Some(revision),
174 };
175 rev_cx.run_revision();
176 }
177 } else {
178 cx.run_revision();
179 }
180
181 cx.create_stamp();
182}
183
184pub fn compute_stamp_hash(config: &Config) -> String {
185 let mut hash = DefaultHasher::new();
186 config.stage_id.hash(&mut hash);
187 config.run.hash(&mut hash);
188 config.edition.hash(&mut hash);
189
190 match config.debugger {
191 Some(Debugger::Cdb) => {
192 config.cdb.hash(&mut hash);
193 }
194
195 Some(Debugger::Gdb) => {
196 config.gdb.hash(&mut hash);
197 env::var_os("PATH").hash(&mut hash);
198 env::var_os("PYTHONPATH").hash(&mut hash);
199 }
200
201 Some(Debugger::Lldb) => {
202 config.lldb.hash(&mut hash);
206 env::var_os("PATH").hash(&mut hash);
207 }
208
209 None => {}
210 }
211
212 if config.mode == TestMode::Ui {
213 config.force_pass_mode.hash(&mut hash);
214 }
215
216 format!("{:x}", hash.finish())
217}
218
219#[derive(Copy, Clone, Debug)]
220struct TestCx<'test> {
221 config: &'test Config,
222 stdout: &'test dyn ConsoleOut,
223 stderr: &'test dyn ConsoleOut,
224 props: &'test TestProps,
225 testpaths: &'test TestPaths,
226 revision: Option<&'test str>,
227}
228
229enum ReadFrom {
230 Path,
231 Stdin(String),
232}
233
234enum TestOutput {
235 Compile,
236 Run,
237}
238
239#[derive(Copy, Clone, PartialEq)]
241enum WillExecute {
242 Yes,
243 No,
244 Disabled,
245}
246
247#[derive(Copy, Clone)]
249enum Emit {
250 None,
251 Metadata,
252 LlvmIr,
253 Mir,
254 Asm,
255 LinkArgsAsm,
256}
257
258#[derive(Clone, Copy, Debug, PartialEq, Eq)]
260enum CompilerKind {
261 Rustc,
262 Rustdoc,
263}
264
265impl<'test> TestCx<'test> {
266 fn run_revision(&self) {
269 if self.props.should_ice
270 && self.config.mode != TestMode::Incremental
271 && self.config.mode != TestMode::Crashes
272 {
273 self.fatal("cannot use should-ice in a test that is not cfail");
274 }
275 match self.config.mode {
276 TestMode::Pretty => self.run_pretty_test(),
277 TestMode::DebugInfo => self.run_debuginfo_test(),
278 TestMode::Codegen => self.run_codegen_test(),
279 TestMode::RustdocHtml => self.run_rustdoc_html_test(),
280 TestMode::RustdocJson => self.run_rustdoc_json_test(),
281 TestMode::CodegenUnits => self.run_codegen_units_test(),
282 TestMode::Incremental => self.run_incremental_test(),
283 TestMode::RunMake => self.run_rmake_test(),
284 TestMode::Ui => self.run_ui_test(),
285 TestMode::MirOpt => self.run_mir_opt_test(),
286 TestMode::Assembly => self.run_assembly_test(),
287 TestMode::RustdocJs => self.run_rustdoc_js_test(),
288 TestMode::CoverageMap => self.run_coverage_map_test(), TestMode::CoverageRun => self.run_coverage_run_test(), TestMode::Crashes => self.run_crash_test(),
291 }
292 }
293
294 fn pass_mode(&self) -> Option<PassMode> {
295 self.props.pass_mode(self.config)
296 }
297
298 fn should_run(&self, pm: Option<PassMode>) -> WillExecute {
299 let test_should_run = match self.config.mode {
300 TestMode::Ui
301 if pm == Some(PassMode::Run)
302 || matches!(self.props.fail_mode, Some(FailMode::Run(_))) =>
303 {
304 true
305 }
306 TestMode::MirOpt if pm == Some(PassMode::Run) => true,
307 TestMode::Ui | TestMode::MirOpt => false,
308 mode => panic!("unimplemented for mode {:?}", mode),
309 };
310 if test_should_run { self.run_if_enabled() } else { WillExecute::No }
311 }
312
313 fn run_if_enabled(&self) -> WillExecute {
314 if self.config.run_enabled() { WillExecute::Yes } else { WillExecute::Disabled }
315 }
316
317 fn should_run_successfully(&self, pm: Option<PassMode>) -> bool {
318 match self.config.mode {
319 TestMode::Ui | TestMode::MirOpt => pm == Some(PassMode::Run),
320 mode => panic!("unimplemented for mode {:?}", mode),
321 }
322 }
323
324 fn should_compile_successfully(&self, pm: Option<PassMode>) -> bool {
325 match self.config.mode {
326 TestMode::RustdocJs => true,
327 TestMode::Ui => pm.is_some() || self.props.fail_mode > Some(FailMode::Build),
328 TestMode::Crashes => false,
329 TestMode::Incremental => {
330 let revision =
331 self.revision.expect("incremental tests require a list of revisions");
332 if revision.starts_with("cpass")
333 || revision.starts_with("rpass")
334 || revision.starts_with("rfail")
335 {
336 true
337 } else if revision.starts_with("cfail") {
338 pm.is_some()
339 } else {
340 panic!("revision name must begin with cpass, rpass, rfail, or cfail");
341 }
342 }
343 mode => panic!("unimplemented for mode {:?}", mode),
344 }
345 }
346
347 fn check_if_test_should_compile(
348 &self,
349 fail_mode: Option<FailMode>,
350 pass_mode: Option<PassMode>,
351 proc_res: &ProcRes,
352 ) {
353 if self.should_compile_successfully(pass_mode) {
354 if !proc_res.status.success() {
355 match (fail_mode, pass_mode) {
356 (Some(FailMode::Build), Some(PassMode::Check)) => {
357 self.fatal_proc_rec(
359 "`build-fail` test is required to pass check build, but check build failed",
360 proc_res,
361 );
362 }
363 _ => {
364 self.fatal_proc_rec(
365 "test compilation failed although it shouldn't!",
366 proc_res,
367 );
368 }
369 }
370 }
371 } else {
372 if proc_res.status.success() {
373 let err = &format!("{} test did not emit an error", self.config.mode);
374 let extra_note = (self.config.mode == crate::common::TestMode::Ui)
375 .then_some("note: by default, ui tests are expected not to compile.\nhint: use check-pass, build-pass, or run-pass directive to change this behavior.");
376 self.fatal_proc_rec_general(err, extra_note, proc_res, || ());
377 }
378
379 if !self.props.dont_check_failure_status {
380 self.check_correct_failure_status(proc_res);
381 }
382 }
383 }
384
385 fn get_output(&self, proc_res: &ProcRes) -> String {
386 if self.props.check_stdout {
387 format!("{}{}", proc_res.stdout, proc_res.stderr)
388 } else {
389 proc_res.stderr.clone()
390 }
391 }
392
393 fn check_correct_failure_status(&self, proc_res: &ProcRes) {
394 let expected_status = Some(self.props.failure_status.unwrap_or(1));
395 let received_status = proc_res.status.code();
396
397 if expected_status != received_status {
398 self.fatal_proc_rec(
399 &format!(
400 "Error: expected failure status ({:?}) but received status {:?}.",
401 expected_status, received_status
402 ),
403 proc_res,
404 );
405 }
406 }
407
408 #[must_use = "caller should check whether the command succeeded"]
418 fn run_command_to_procres(&self, cmd: &mut Command) -> ProcRes {
419 let output = cmd
420 .output()
421 .unwrap_or_else(|e| self.fatal(&format!("failed to exec `{cmd:?}` because: {e}")));
422
423 let proc_res = ProcRes {
424 status: output.status,
425 stdout: String::from_utf8(output.stdout).unwrap(),
426 stderr: String::from_utf8(output.stderr).unwrap(),
427 truncated: Truncated::No,
428 cmdline: format!("{cmd:?}"),
429 };
430 self.dump_output(
431 self.config.verbose || !proc_res.status.success(),
432 &cmd.get_program().to_string_lossy(),
433 &proc_res.stdout,
434 &proc_res.stderr,
435 );
436
437 proc_res
438 }
439
440 fn print_source(&self, read_from: ReadFrom, pretty_type: &str) -> ProcRes {
441 let aux_dir = self.aux_output_dir_name();
442 let input: &str = match read_from {
443 ReadFrom::Stdin(_) => "-",
444 ReadFrom::Path => self.testpaths.file.as_str(),
445 };
446
447 let mut rustc = Command::new(&self.config.rustc_path);
448
449 self.build_all_auxiliary(&self.aux_output_dir(), &mut rustc);
450
451 rustc
452 .arg(input)
453 .args(&["-Z", &format!("unpretty={}", pretty_type)])
454 .args(&["--target", &self.config.target])
455 .arg("-L")
456 .arg(&aux_dir)
457 .arg("-A")
458 .arg("internal_features")
459 .args(&self.props.compile_flags)
460 .envs(self.props.rustc_env.clone());
461 self.maybe_add_external_args(&mut rustc, &self.config.target_rustcflags);
462
463 let src = match read_from {
464 ReadFrom::Stdin(src) => Some(src),
465 ReadFrom::Path => None,
466 };
467
468 self.compose_and_run(
469 rustc,
470 self.config.host_compile_lib_path.as_path(),
471 Some(aux_dir.as_path()),
472 src,
473 )
474 }
475
476 fn compare_source(&self, expected: &str, actual: &str) {
477 if expected != actual {
478 self.fatal(&format!(
479 "pretty-printed source does not match expected source\n\
480 expected:\n\
481 ------------------------------------------\n\
482 {}\n\
483 ------------------------------------------\n\
484 actual:\n\
485 ------------------------------------------\n\
486 {}\n\
487 ------------------------------------------\n\
488 diff:\n\
489 ------------------------------------------\n\
490 {}\n",
491 expected,
492 actual,
493 write_diff(expected, actual, 3),
494 ));
495 }
496 }
497
498 fn set_revision_flags(&self, cmd: &mut Command) {
499 let normalize_revision = |revision: &str| revision.to_lowercase().replace("-", "_");
502
503 if let Some(revision) = self.revision {
504 let normalized_revision = normalize_revision(revision);
505 let cfg_arg = ["--cfg", &normalized_revision];
506 let arg = format!("--cfg={normalized_revision}");
507 if self
508 .props
509 .compile_flags
510 .windows(2)
511 .any(|args| args == cfg_arg || args[0] == arg || args[1] == arg)
512 {
513 error!(
514 "redundant cfg argument `{normalized_revision}` is already created by the \
515 revision"
516 );
517 panic!("redundant cfg argument");
518 }
519 if self.config.builtin_cfg_names().contains(&normalized_revision) {
520 error!("revision `{normalized_revision}` collides with a built-in cfg");
521 panic!("revision collides with built-in cfg");
522 }
523 cmd.args(cfg_arg);
524 }
525
526 if !self.props.no_auto_check_cfg {
527 let mut check_cfg = String::with_capacity(25);
528
529 check_cfg.push_str("cfg(test,FALSE");
535 for revision in &self.props.revisions {
536 check_cfg.push(',');
537 check_cfg.push_str(&normalize_revision(revision));
538 }
539 check_cfg.push(')');
540
541 cmd.args(&["--check-cfg", &check_cfg]);
542 }
543 }
544
545 fn typecheck_source(&self, src: String) -> ProcRes {
546 let mut rustc = Command::new(&self.config.rustc_path);
547
548 let out_dir = self.output_base_name().with_extension("pretty-out");
549 remove_and_create_dir_all(&out_dir).unwrap_or_else(|e| {
550 panic!("failed to remove and recreate output directory `{out_dir}`: {e}")
551 });
552
553 let target = if self.props.force_host { &*self.config.host } else { &*self.config.target };
554
555 let aux_dir = self.aux_output_dir_name();
556
557 rustc
558 .arg("-")
559 .arg("-Zno-codegen")
560 .arg("--out-dir")
561 .arg(&out_dir)
562 .arg(&format!("--target={}", target))
563 .arg("-L")
564 .arg(&self.config.build_test_suite_root)
567 .arg("-L")
568 .arg(aux_dir)
569 .arg("-A")
570 .arg("internal_features");
571 self.set_revision_flags(&mut rustc);
572 self.maybe_add_external_args(&mut rustc, &self.config.target_rustcflags);
573 rustc.args(&self.props.compile_flags);
574
575 self.compose_and_run_compiler(rustc, Some(src))
576 }
577
578 fn maybe_add_external_args(&self, cmd: &mut Command, args: &Vec<String>) {
579 const OPT_FLAGS: &[&str] = &["-O", "-Copt-level=", "opt-level="];
584 const DEBUG_FLAGS: &[&str] = &["-g", "-Cdebuginfo=", "debuginfo="];
585
586 let have_opt_flag =
590 self.props.compile_flags.iter().any(|arg| OPT_FLAGS.iter().any(|f| arg.starts_with(f)));
591 let have_debug_flag = self
592 .props
593 .compile_flags
594 .iter()
595 .any(|arg| DEBUG_FLAGS.iter().any(|f| arg.starts_with(f)));
596
597 for arg in args {
598 if OPT_FLAGS.iter().any(|f| arg.starts_with(f)) && have_opt_flag {
599 continue;
600 }
601 if DEBUG_FLAGS.iter().any(|f| arg.starts_with(f)) && have_debug_flag {
602 continue;
603 }
604 cmd.arg(arg);
605 }
606 }
607
608 fn check_all_error_patterns(&self, output_to_check: &str, proc_res: &ProcRes) {
610 let mut missing_patterns: Vec<String> = Vec::new();
611 self.check_error_patterns(output_to_check, &mut missing_patterns);
612 self.check_regex_error_patterns(output_to_check, proc_res, &mut missing_patterns);
613
614 if missing_patterns.is_empty() {
615 return;
616 }
617
618 if missing_patterns.len() == 1 {
619 self.fatal_proc_rec(
620 &format!("error pattern '{}' not found!", missing_patterns[0]),
621 proc_res,
622 );
623 } else {
624 for pattern in missing_patterns {
625 writeln!(
626 self.stdout,
627 "\n{prefix}: error pattern '{pattern}' not found!",
628 prefix = self.error_prefix()
629 );
630 }
631 self.fatal_proc_rec("multiple error patterns not found", proc_res);
632 }
633 }
634
635 fn check_error_patterns(&self, output_to_check: &str, missing_patterns: &mut Vec<String>) {
636 debug!("check_error_patterns");
637 for pattern in &self.props.error_patterns {
638 if output_to_check.contains(pattern.trim()) {
639 debug!("found error pattern {}", pattern);
640 } else {
641 missing_patterns.push(pattern.to_string());
642 }
643 }
644 }
645
646 fn check_regex_error_patterns(
647 &self,
648 output_to_check: &str,
649 proc_res: &ProcRes,
650 missing_patterns: &mut Vec<String>,
651 ) {
652 debug!("check_regex_error_patterns");
653
654 for pattern in &self.props.regex_error_patterns {
655 let pattern = pattern.trim();
656 let re = match Regex::new(pattern) {
657 Ok(re) => re,
658 Err(err) => {
659 self.fatal_proc_rec(
660 &format!("invalid regex error pattern '{}': {:?}", pattern, err),
661 proc_res,
662 );
663 }
664 };
665 if re.is_match(output_to_check) {
666 debug!("found regex error pattern {}", pattern);
667 } else {
668 missing_patterns.push(pattern.to_string());
669 }
670 }
671 }
672
673 fn check_no_compiler_crash(&self, proc_res: &ProcRes, should_ice: bool) {
674 match proc_res.status.code() {
675 Some(101) if !should_ice => {
676 self.fatal_proc_rec("compiler encountered internal error", proc_res)
677 }
678 None => self.fatal_proc_rec("compiler terminated by signal", proc_res),
679 _ => (),
680 }
681 }
682
683 fn check_forbid_output(&self, output_to_check: &str, proc_res: &ProcRes) {
684 for pat in &self.props.forbid_output {
685 if output_to_check.contains(pat) {
686 self.fatal_proc_rec("forbidden pattern found in compiler output", proc_res);
687 }
688 }
689 }
690
691 fn check_expected_errors(&self, proc_res: &ProcRes) {
693 let expected_errors = load_errors(&self.testpaths.file, self.revision);
694 debug!(
695 "check_expected_errors: expected_errors={:?} proc_res.status={:?}",
696 expected_errors, proc_res.status
697 );
698 if proc_res.status.success() && expected_errors.iter().any(|x| x.kind == ErrorKind::Error) {
699 self.fatal_proc_rec("process did not return an error status", proc_res);
700 }
701
702 if self.props.known_bug {
703 if !expected_errors.is_empty() {
704 self.fatal_proc_rec(
705 "`known_bug` tests should not have an expected error",
706 proc_res,
707 );
708 }
709 return;
710 }
711
712 let diagnostic_file_name = if self.props.remap_src_base {
715 let mut p = Utf8PathBuf::from(FAKE_SRC_BASE);
716 p.push(&self.testpaths.relative_dir);
717 p.push(self.testpaths.file.file_name().unwrap());
718 p.to_string()
719 } else {
720 self.testpaths.file.to_string()
721 };
722
723 let expected_kinds: HashSet<_> = [ErrorKind::Error, ErrorKind::Warning]
726 .into_iter()
727 .chain(expected_errors.iter().map(|e| e.kind))
728 .collect();
729
730 let actual_errors = json::parse_output(&diagnostic_file_name, &self.get_output(proc_res))
732 .into_iter()
733 .map(|e| Error { msg: self.normalize_output(&e.msg, &[]), ..e });
734
735 let mut unexpected = Vec::new();
736 let mut unimportant = Vec::new();
737 let mut found = vec![false; expected_errors.len()];
738 for actual_error in actual_errors {
739 for pattern in &self.props.error_patterns {
740 let pattern = pattern.trim();
741 if actual_error.msg.contains(pattern) {
742 let q = if actual_error.line_num.is_none() { "?" } else { "" };
743 self.fatal(&format!(
744 "error pattern '{pattern}' is found in structured \
745 diagnostics, use `//~{q} {} {pattern}` instead",
746 actual_error.kind,
747 ));
748 }
749 }
750
751 let opt_index =
752 expected_errors.iter().enumerate().position(|(index, expected_error)| {
753 !found[index]
754 && actual_error.line_num == expected_error.line_num
755 && actual_error.kind == expected_error.kind
756 && actual_error.msg.contains(&expected_error.msg)
757 });
758
759 match opt_index {
760 Some(index) => {
761 assert!(!found[index]);
763 found[index] = true;
764 }
765
766 None => {
767 if actual_error.require_annotation
768 && expected_kinds.contains(&actual_error.kind)
769 && !self.props.dont_require_annotations.contains(&actual_error.kind)
770 {
771 unexpected.push(actual_error);
772 } else {
773 unimportant.push(actual_error);
774 }
775 }
776 }
777 }
778
779 let mut not_found = Vec::new();
780 for (index, expected_error) in expected_errors.iter().enumerate() {
782 if !found[index] {
783 not_found.push(expected_error);
784 }
785 }
786
787 if !unexpected.is_empty() || !not_found.is_empty() {
788 let file_name = self
791 .testpaths
792 .file
793 .strip_prefix(self.config.src_root.as_str())
794 .unwrap_or(&self.testpaths.file)
795 .to_string()
796 .replace(r"\", "/");
797 let line_str = |e: &Error| {
798 let line_num = e.line_num.map_or("?".to_string(), |line_num| line_num.to_string());
799 let opt_col_num = match e.column_num {
801 Some(col_num) if line_num != "?" => format!(":{col_num}"),
802 _ => "".to_string(),
803 };
804 format!("{file_name}:{line_num}{opt_col_num}")
805 };
806 let print_error =
807 |e| writeln!(self.stdout, "{}: {}: {}", line_str(e), e.kind, e.msg.cyan());
808 let push_suggestion =
809 |suggestions: &mut Vec<_>, e: &Error, kind, line, msg, color, rank| {
810 let mut ret = String::new();
811 if kind {
812 ret += &format!("{} {}", "with different kind:".color(color), e.kind);
813 }
814 if line {
815 if !ret.is_empty() {
816 ret.push(' ');
817 }
818 ret += &format!("{} {}", "on different line:".color(color), line_str(e));
819 }
820 if msg {
821 if !ret.is_empty() {
822 ret.push(' ');
823 }
824 ret +=
825 &format!("{} {}", "with different message:".color(color), e.msg.cyan());
826 }
827 suggestions.push((ret, rank));
828 };
829 let show_suggestions = |mut suggestions: Vec<_>, prefix: &str, color| {
830 suggestions.sort_by_key(|(_, rank)| *rank);
832 if let Some(&(_, top_rank)) = suggestions.first() {
833 for (suggestion, rank) in suggestions {
834 if rank == top_rank {
835 writeln!(self.stdout, " {} {suggestion}", prefix.color(color));
836 }
837 }
838 }
839 };
840
841 if !unexpected.is_empty() {
848 writeln!(
849 self.stdout,
850 "\n{prefix}: {n} diagnostics reported in JSON output but not expected in test file",
851 prefix = self.error_prefix(),
852 n = unexpected.len(),
853 );
854 for error in &unexpected {
855 print_error(error);
856 let mut suggestions = Vec::new();
857 for candidate in ¬_found {
858 let kind_mismatch = candidate.kind != error.kind;
859 let mut push_red_suggestion = |line, msg, rank| {
860 push_suggestion(
861 &mut suggestions,
862 candidate,
863 kind_mismatch,
864 line,
865 msg,
866 Color::Red,
867 rank,
868 )
869 };
870 if error.msg.contains(&candidate.msg) {
871 push_red_suggestion(candidate.line_num != error.line_num, false, 0);
872 } else if candidate.line_num.is_some()
873 && candidate.line_num == error.line_num
874 {
875 push_red_suggestion(false, true, if kind_mismatch { 2 } else { 1 });
876 }
877 }
878
879 show_suggestions(suggestions, "expected", Color::Red);
880 }
881 }
882 if !not_found.is_empty() {
883 writeln!(
884 self.stdout,
885 "\n{prefix}: {n} diagnostics expected in test file but not reported in JSON output",
886 prefix = self.error_prefix(),
887 n = not_found.len(),
888 );
889
890 if let Some(human_format) = self.props.compile_flags.iter().find(|flag| {
893 flag.contains("error-format")
895 && (flag.contains("short") || flag.contains("human"))
896 }) {
897 let msg = format!(
898 "tests with compile flag `{}` should not have error annotations such as `//~ ERROR`",
899 human_format
900 ).color(Color::Red);
901 writeln!(self.stdout, "{}", msg);
902 }
903
904 for error in ¬_found {
905 print_error(error);
906 let mut suggestions = Vec::new();
907 for candidate in unexpected.iter().chain(&unimportant) {
908 let kind_mismatch = candidate.kind != error.kind;
909 let mut push_green_suggestion = |line, msg, rank| {
910 push_suggestion(
911 &mut suggestions,
912 candidate,
913 kind_mismatch,
914 line,
915 msg,
916 Color::Green,
917 rank,
918 )
919 };
920 if candidate.msg.contains(&error.msg) {
921 push_green_suggestion(candidate.line_num != error.line_num, false, 0);
922 } else if candidate.line_num.is_some()
923 && candidate.line_num == error.line_num
924 {
925 push_green_suggestion(false, true, if kind_mismatch { 2 } else { 1 });
926 }
927 }
928
929 show_suggestions(suggestions, "reported", Color::Green);
930 }
931 }
932 panic!(
933 "errors differ from expected\nstatus: {}\ncommand: {}\n",
934 proc_res.status, proc_res.cmdline
935 );
936 }
937 }
938
939 fn should_emit_metadata(&self, pm: Option<PassMode>) -> Emit {
940 match (pm, self.props.fail_mode, self.config.mode) {
941 (Some(PassMode::Check), ..) | (_, Some(FailMode::Check), TestMode::Ui) => {
942 Emit::Metadata
943 }
944 _ => Emit::None,
945 }
946 }
947
948 fn compile_test(&self, will_execute: WillExecute, emit: Emit) -> ProcRes {
949 self.compile_test_general(will_execute, emit, self.props.local_pass_mode(), Vec::new())
950 }
951
952 fn compile_test_with_passes(
953 &self,
954 will_execute: WillExecute,
955 emit: Emit,
956 passes: Vec<String>,
957 ) -> ProcRes {
958 self.compile_test_general(will_execute, emit, self.props.local_pass_mode(), passes)
959 }
960
961 fn compile_test_general(
962 &self,
963 will_execute: WillExecute,
964 emit: Emit,
965 local_pm: Option<PassMode>,
966 passes: Vec<String>,
967 ) -> ProcRes {
968 let compiler_kind = self.compiler_kind_for_non_aux();
969
970 let output_file = match will_execute {
972 WillExecute::Yes => TargetLocation::ThisFile(self.make_exe_name()),
973 WillExecute::No | WillExecute::Disabled => {
974 TargetLocation::ThisDirectory(self.output_base_dir())
975 }
976 };
977
978 let allow_unused = match self.config.mode {
979 TestMode::Ui => {
980 if compiler_kind == CompilerKind::Rustc
986 && local_pm != Some(PassMode::Run)
990 {
991 AllowUnused::Yes
992 } else {
993 AllowUnused::No
994 }
995 }
996 _ => AllowUnused::No,
997 };
998
999 let rustc = self.make_compile_args(
1000 compiler_kind,
1001 &self.testpaths.file,
1002 output_file,
1003 emit,
1004 allow_unused,
1005 LinkToAux::Yes,
1006 passes,
1007 );
1008
1009 self.compose_and_run_compiler(rustc, None)
1010 }
1011
1012 fn document(&self, root_out_dir: &Utf8Path, kind: DocKind) -> ProcRes {
1015 self.document_inner(&self.testpaths.file, root_out_dir, kind)
1016 }
1017
1018 fn document_inner(
1022 &self,
1023 file_to_doc: &Utf8Path,
1024 root_out_dir: &Utf8Path,
1025 kind: DocKind,
1026 ) -> ProcRes {
1027 if self.props.build_aux_docs {
1028 assert_eq!(kind, DocKind::Html, "build-aux-docs only make sense for html output");
1029
1030 for rel_ab in &self.props.aux.builds {
1031 let aux_path = self.resolve_aux_path(rel_ab);
1032 let props_for_aux = self.props.from_aux_file(&aux_path, self.revision, self.config);
1033 let aux_cx = TestCx {
1034 config: self.config,
1035 stdout: self.stdout,
1036 stderr: self.stderr,
1037 props: &props_for_aux,
1038 testpaths: self.testpaths,
1039 revision: self.revision,
1040 };
1041 create_dir_all(aux_cx.output_base_dir()).unwrap();
1043 let auxres = aux_cx.document_inner(&aux_path, &root_out_dir, kind);
1044 if !auxres.status.success() {
1045 return auxres;
1046 }
1047 }
1048 }
1049
1050 let aux_dir = self.aux_output_dir_name();
1051
1052 let rustdoc_path = self.config.rustdoc_path.as_ref().expect("--rustdoc-path not passed");
1053
1054 let out_dir: Cow<'_, Utf8Path> = if self.props.unique_doc_out_dir {
1057 let file_name = file_to_doc.file_stem().expect("file name should not be empty");
1058 let out_dir = Utf8PathBuf::from_iter([
1059 root_out_dir,
1060 Utf8Path::new("docs"),
1061 Utf8Path::new(file_name),
1062 Utf8Path::new("doc"),
1063 ]);
1064 create_dir_all(&out_dir).unwrap();
1065 Cow::Owned(out_dir)
1066 } else {
1067 Cow::Borrowed(root_out_dir)
1068 };
1069
1070 let mut rustdoc = Command::new(rustdoc_path);
1071 let current_dir = self.output_base_dir();
1072 rustdoc.current_dir(current_dir);
1073 rustdoc
1074 .arg("-L")
1075 .arg(self.config.target_run_lib_path.as_path())
1076 .arg("-L")
1077 .arg(aux_dir)
1078 .arg("-o")
1079 .arg(out_dir.as_ref())
1080 .arg("--deny")
1081 .arg("warnings")
1082 .arg(file_to_doc)
1083 .arg("-A")
1084 .arg("internal_features")
1085 .args(&self.props.compile_flags)
1086 .args(&self.props.doc_flags);
1087
1088 match kind {
1089 DocKind::Html => {}
1090 DocKind::Json => {
1091 rustdoc.arg("--output-format").arg("json").arg("-Zunstable-options");
1092 }
1093 }
1094
1095 if let Some(ref linker) = self.config.target_linker {
1096 rustdoc.arg(format!("-Clinker={}", linker));
1097 }
1098
1099 self.compose_and_run_compiler(rustdoc, None)
1100 }
1101
1102 fn exec_compiled_test(&self) -> ProcRes {
1103 self.exec_compiled_test_general(&[], true)
1104 }
1105
1106 fn exec_compiled_test_general(
1107 &self,
1108 env_extra: &[(&str, &str)],
1109 delete_after_success: bool,
1110 ) -> ProcRes {
1111 let prepare_env = |cmd: &mut Command| {
1112 for (key, val) in &self.props.exec_env {
1113 cmd.env(key, val);
1114 }
1115 for (key, val) in env_extra {
1116 cmd.env(key, val);
1117 }
1118
1119 for key in &self.props.unset_exec_env {
1120 cmd.env_remove(key);
1121 }
1122 };
1123
1124 let proc_res = match &*self.config.target {
1125 _ if self.config.remote_test_client.is_some() => {
1142 let aux_dir = self.aux_output_dir_name();
1143 let ProcArgs { prog, args } = self.make_run_args();
1144 let mut support_libs = Vec::new();
1145 if let Ok(entries) = aux_dir.read_dir() {
1146 for entry in entries {
1147 let entry = entry.unwrap();
1148 if !entry.path().is_file() {
1149 continue;
1150 }
1151 support_libs.push(entry.path());
1152 }
1153 }
1154 let mut test_client =
1155 Command::new(self.config.remote_test_client.as_ref().unwrap());
1156 test_client
1157 .args(&["run", &support_libs.len().to_string()])
1158 .arg(&prog)
1159 .args(support_libs)
1160 .args(args);
1161
1162 prepare_env(&mut test_client);
1163
1164 self.compose_and_run(
1165 test_client,
1166 self.config.target_run_lib_path.as_path(),
1167 Some(aux_dir.as_path()),
1168 None,
1169 )
1170 }
1171 _ if self.config.target.contains("vxworks") => {
1172 let aux_dir = self.aux_output_dir_name();
1173 let ProcArgs { prog, args } = self.make_run_args();
1174 let mut wr_run = Command::new("wr-run");
1175 wr_run.args(&[&prog]).args(args);
1176
1177 prepare_env(&mut wr_run);
1178
1179 self.compose_and_run(
1180 wr_run,
1181 self.config.target_run_lib_path.as_path(),
1182 Some(aux_dir.as_path()),
1183 None,
1184 )
1185 }
1186 _ => {
1187 let aux_dir = self.aux_output_dir_name();
1188 let ProcArgs { prog, args } = self.make_run_args();
1189 let mut program = Command::new(&prog);
1190 program.args(args).current_dir(&self.output_base_dir());
1191
1192 prepare_env(&mut program);
1193
1194 self.compose_and_run(
1195 program,
1196 self.config.target_run_lib_path.as_path(),
1197 Some(aux_dir.as_path()),
1198 None,
1199 )
1200 }
1201 };
1202
1203 if delete_after_success && proc_res.status.success() {
1204 let _ = fs::remove_file(self.make_exe_name());
1207 }
1208
1209 proc_res
1210 }
1211
1212 fn resolve_aux_path(&self, relative_aux_path: &str) -> Utf8PathBuf {
1215 let aux_path = self
1216 .testpaths
1217 .file
1218 .parent()
1219 .expect("test file path has no parent")
1220 .join("auxiliary")
1221 .join(relative_aux_path);
1222 if !aux_path.exists() {
1223 self.fatal(&format!(
1224 "auxiliary source file `{relative_aux_path}` not found at `{aux_path}`"
1225 ));
1226 }
1227
1228 aux_path
1229 }
1230
1231 fn is_vxworks_pure_static(&self) -> bool {
1232 if self.config.target.contains("vxworks") {
1233 match env::var("RUST_VXWORKS_TEST_DYLINK") {
1234 Ok(s) => s != "1",
1235 _ => true,
1236 }
1237 } else {
1238 false
1239 }
1240 }
1241
1242 fn is_vxworks_pure_dynamic(&self) -> bool {
1243 self.config.target.contains("vxworks") && !self.is_vxworks_pure_static()
1244 }
1245
1246 fn has_aux_dir(&self) -> bool {
1247 !self.props.aux.builds.is_empty()
1248 || !self.props.aux.crates.is_empty()
1249 || !self.props.aux.proc_macros.is_empty()
1250 }
1251
1252 fn aux_output_dir(&self) -> Utf8PathBuf {
1253 let aux_dir = self.aux_output_dir_name();
1254
1255 if !self.props.aux.builds.is_empty() {
1256 remove_and_create_dir_all(&aux_dir).unwrap_or_else(|e| {
1257 panic!("failed to remove and recreate output directory `{aux_dir}`: {e}")
1258 });
1259 }
1260
1261 if !self.props.aux.bins.is_empty() {
1262 let aux_bin_dir = self.aux_bin_output_dir_name();
1263 remove_and_create_dir_all(&aux_dir).unwrap_or_else(|e| {
1264 panic!("failed to remove and recreate output directory `{aux_dir}`: {e}")
1265 });
1266 remove_and_create_dir_all(&aux_bin_dir).unwrap_or_else(|e| {
1267 panic!("failed to remove and recreate output directory `{aux_bin_dir}`: {e}")
1268 });
1269 }
1270
1271 aux_dir
1272 }
1273
1274 fn build_all_auxiliary(&self, aux_dir: &Utf8Path, rustc: &mut Command) {
1275 for rel_ab in &self.props.aux.builds {
1276 self.build_auxiliary(rel_ab, &aux_dir, None);
1277 }
1278
1279 for rel_ab in &self.props.aux.bins {
1280 self.build_auxiliary(rel_ab, &aux_dir, Some(AuxType::Bin));
1281 }
1282
1283 let path_to_crate_name = |path: &str| -> String {
1284 path.rsplit_once('/')
1285 .map_or(path, |(_, tail)| tail)
1286 .trim_end_matches(".rs")
1287 .replace('-', "_")
1288 };
1289
1290 let add_extern = |rustc: &mut Command,
1291 extern_modifiers: Option<&str>,
1292 aux_name: &str,
1293 aux_path: &str,
1294 aux_type: AuxType| {
1295 let lib_name = get_lib_name(&path_to_crate_name(aux_path), aux_type);
1296 if let Some(lib_name) = lib_name {
1297 let modifiers_and_name = match extern_modifiers {
1298 Some(modifiers) => format!("{modifiers}:{aux_name}"),
1299 None => aux_name.to_string(),
1300 };
1301 rustc.arg("--extern").arg(format!("{modifiers_and_name}={aux_dir}/{lib_name}"));
1302 }
1303 };
1304
1305 for AuxCrate { extern_modifiers, name, path } in &self.props.aux.crates {
1306 let aux_type = self.build_auxiliary(&path, &aux_dir, None);
1307 add_extern(rustc, extern_modifiers.as_deref(), name, path, aux_type);
1308 }
1309
1310 for proc_macro in &self.props.aux.proc_macros {
1311 self.build_auxiliary(&proc_macro.path, &aux_dir, Some(AuxType::ProcMacro));
1312 let crate_name = path_to_crate_name(&proc_macro.path);
1313 add_extern(
1314 rustc,
1315 proc_macro.extern_modifiers.as_deref(),
1316 &crate_name,
1317 &proc_macro.path,
1318 AuxType::ProcMacro,
1319 );
1320 }
1321
1322 if let Some(aux_file) = &self.props.aux.codegen_backend {
1325 let aux_type = self.build_auxiliary(aux_file, aux_dir, None);
1326 if let Some(lib_name) = get_lib_name(aux_file.trim_end_matches(".rs"), aux_type) {
1327 let lib_path = aux_dir.join(&lib_name);
1328 rustc.arg(format!("-Zcodegen-backend={}", lib_path));
1329 }
1330 }
1331 }
1332
1333 fn compose_and_run_compiler(&self, mut rustc: Command, input: Option<String>) -> ProcRes {
1336 if self.props.add_minicore {
1337 let minicore_path = self.build_minicore();
1338 rustc.arg("--extern");
1339 rustc.arg(&format!("minicore={}", minicore_path));
1340 }
1341
1342 let aux_dir = self.aux_output_dir();
1343 self.build_all_auxiliary(&aux_dir, &mut rustc);
1344
1345 rustc.envs(self.props.rustc_env.clone());
1346 self.props.unset_rustc_env.iter().fold(&mut rustc, Command::env_remove);
1347 self.compose_and_run(
1348 rustc,
1349 self.config.host_compile_lib_path.as_path(),
1350 Some(aux_dir.as_path()),
1351 input,
1352 )
1353 }
1354
1355 fn build_minicore(&self) -> Utf8PathBuf {
1358 let output_file_path = self.output_base_dir().join("libminicore.rlib");
1359 let mut rustc = self.make_compile_args(
1360 CompilerKind::Rustc,
1361 &self.config.minicore_path,
1362 TargetLocation::ThisFile(output_file_path.clone()),
1363 Emit::None,
1364 AllowUnused::Yes,
1365 LinkToAux::No,
1366 vec![],
1367 );
1368
1369 rustc.args(&["--crate-type", "rlib"]);
1370 rustc.arg("-Cpanic=abort");
1371 rustc.args(self.props.minicore_compile_flags.clone());
1372
1373 let res =
1374 self.compose_and_run(rustc, self.config.host_compile_lib_path.as_path(), None, None);
1375 if !res.status.success() {
1376 self.fatal_proc_rec(
1377 &format!("auxiliary build of {} failed to compile: ", self.config.minicore_path),
1378 &res,
1379 );
1380 }
1381
1382 output_file_path
1383 }
1384
1385 fn build_auxiliary(
1389 &self,
1390 source_path: &str,
1391 aux_dir: &Utf8Path,
1392 aux_type: Option<AuxType>,
1393 ) -> AuxType {
1394 let aux_path = self.resolve_aux_path(source_path);
1395 let mut aux_props = self.props.from_aux_file(&aux_path, self.revision, self.config);
1396 if aux_type == Some(AuxType::ProcMacro) {
1397 aux_props.force_host = true;
1398 }
1399 let mut aux_dir = aux_dir.to_path_buf();
1400 if aux_type == Some(AuxType::Bin) {
1401 aux_dir.push("bin");
1405 }
1406 let aux_output = TargetLocation::ThisDirectory(aux_dir.clone());
1407 let aux_cx = TestCx {
1408 config: self.config,
1409 stdout: self.stdout,
1410 stderr: self.stderr,
1411 props: &aux_props,
1412 testpaths: self.testpaths,
1413 revision: self.revision,
1414 };
1415 create_dir_all(aux_cx.output_base_dir()).unwrap();
1417 let mut aux_rustc = aux_cx.make_compile_args(
1418 CompilerKind::Rustc,
1420 &aux_path,
1421 aux_output,
1422 Emit::None,
1423 AllowUnused::No,
1424 LinkToAux::No,
1425 Vec::new(),
1426 );
1427 aux_cx.build_all_auxiliary(&aux_dir, &mut aux_rustc);
1428
1429 aux_rustc.envs(aux_props.rustc_env.clone());
1430 for key in &aux_props.unset_rustc_env {
1431 aux_rustc.env_remove(key);
1432 }
1433
1434 let (aux_type, crate_type) = if aux_type == Some(AuxType::Bin) {
1435 (AuxType::Bin, Some("bin"))
1436 } else if aux_type == Some(AuxType::ProcMacro) {
1437 (AuxType::ProcMacro, Some("proc-macro"))
1438 } else if aux_type.is_some() {
1439 panic!("aux_type {aux_type:?} not expected");
1440 } else if aux_props.no_prefer_dynamic {
1441 (AuxType::Lib, None)
1442 } else if self.config.target.contains("emscripten")
1443 || (self.config.target.contains("musl")
1444 && !aux_props.force_host
1445 && !self.config.host.contains("musl"))
1446 || self.config.target.contains("wasm32")
1447 || self.config.target.contains("nvptx")
1448 || self.is_vxworks_pure_static()
1449 || self.config.target.contains("bpf")
1450 || !self.config.target_cfg().dynamic_linking
1451 || matches!(self.config.mode, TestMode::CoverageMap | TestMode::CoverageRun)
1452 {
1453 (AuxType::Lib, Some("lib"))
1467 } else {
1468 (AuxType::Dylib, Some("dylib"))
1469 };
1470
1471 if let Some(crate_type) = crate_type {
1472 aux_rustc.args(&["--crate-type", crate_type]);
1473 }
1474
1475 if aux_type == AuxType::ProcMacro {
1476 aux_rustc.args(&["--extern", "proc_macro"]);
1478 }
1479
1480 aux_rustc.arg("-L").arg(&aux_dir);
1481
1482 if aux_props.add_minicore {
1483 let minicore_path = self.build_minicore();
1484 aux_rustc.arg("--extern");
1485 aux_rustc.arg(&format!("minicore={}", minicore_path));
1486 }
1487
1488 let auxres = aux_cx.compose_and_run(
1489 aux_rustc,
1490 aux_cx.config.host_compile_lib_path.as_path(),
1491 Some(aux_dir.as_path()),
1492 None,
1493 );
1494 if !auxres.status.success() {
1495 self.fatal_proc_rec(
1496 &format!("auxiliary build of {aux_path} failed to compile: "),
1497 &auxres,
1498 );
1499 }
1500 aux_type
1501 }
1502
1503 fn read2_abbreviated(&self, child: Child) -> (Output, Truncated) {
1504 let mut filter_paths_from_len = Vec::new();
1505 let mut add_path = |path: &Utf8Path| {
1506 let path = path.to_string();
1507 let windows = path.replace("\\", "\\\\");
1508 if windows != path {
1509 filter_paths_from_len.push(windows);
1510 }
1511 filter_paths_from_len.push(path);
1512 };
1513
1514 add_path(&self.config.src_test_suite_root);
1520 add_path(&self.config.build_test_suite_root);
1521
1522 read2_abbreviated(child, &filter_paths_from_len).expect("failed to read output")
1523 }
1524
1525 fn compose_and_run(
1526 &self,
1527 mut command: Command,
1528 lib_path: &Utf8Path,
1529 aux_path: Option<&Utf8Path>,
1530 input: Option<String>,
1531 ) -> ProcRes {
1532 let cmdline = {
1533 let cmdline = self.make_cmdline(&command, lib_path);
1534 self.logv(format_args!("executing {cmdline}"));
1535 cmdline
1536 };
1537
1538 command.stdout(Stdio::piped()).stderr(Stdio::piped()).stdin(Stdio::piped());
1539
1540 add_dylib_path(&mut command, iter::once(lib_path).chain(aux_path));
1543
1544 let mut child = disable_error_reporting(|| command.spawn())
1545 .unwrap_or_else(|e| panic!("failed to exec `{command:?}`: {e:?}"));
1546 if let Some(input) = input {
1547 child.stdin.as_mut().unwrap().write_all(input.as_bytes()).unwrap();
1548 }
1549
1550 let (Output { status, stdout, stderr }, truncated) = self.read2_abbreviated(child);
1551
1552 let result = ProcRes {
1553 status,
1554 stdout: String::from_utf8_lossy(&stdout).into_owned(),
1555 stderr: String::from_utf8_lossy(&stderr).into_owned(),
1556 truncated,
1557 cmdline,
1558 };
1559
1560 self.dump_output(
1561 self.config.verbose || (!result.status.success() && self.config.mode != TestMode::Ui),
1562 &command.get_program().to_string_lossy(),
1563 &result.stdout,
1564 &result.stderr,
1565 );
1566
1567 result
1568 }
1569
1570 fn compiler_kind_for_non_aux(&self) -> CompilerKind {
1573 match self.config.suite {
1574 TestSuite::RustdocJs | TestSuite::RustdocJson | TestSuite::RustdocUi => {
1575 CompilerKind::Rustdoc
1576 }
1577
1578 TestSuite::AssemblyLlvm
1582 | TestSuite::BuildStd
1583 | TestSuite::CodegenLlvm
1584 | TestSuite::CodegenUnits
1585 | TestSuite::Coverage
1586 | TestSuite::CoverageRunRustdoc
1587 | TestSuite::Crashes
1588 | TestSuite::Debuginfo
1589 | TestSuite::Incremental
1590 | TestSuite::MirOpt
1591 | TestSuite::Pretty
1592 | TestSuite::RunMake
1593 | TestSuite::RunMakeCargo
1594 | TestSuite::RustdocGui
1595 | TestSuite::RustdocHtml
1596 | TestSuite::RustdocJsStd
1597 | TestSuite::Ui
1598 | TestSuite::UiFullDeps => CompilerKind::Rustc,
1599 }
1600 }
1601
1602 fn make_compile_args(
1603 &self,
1604 compiler_kind: CompilerKind,
1605 input_file: &Utf8Path,
1606 output_file: TargetLocation,
1607 emit: Emit,
1608 allow_unused: AllowUnused,
1609 link_to_aux: LinkToAux,
1610 passes: Vec<String>, ) -> Command {
1612 let mut compiler = match compiler_kind {
1615 CompilerKind::Rustc => Command::new(&self.config.rustc_path),
1616 CompilerKind::Rustdoc => {
1617 Command::new(&self.config.rustdoc_path.clone().expect("no rustdoc built yet"))
1618 }
1619 };
1620 compiler.arg(input_file);
1621
1622 compiler.arg("-Zthreads=1");
1624
1625 compiler.arg("-Zsimulate-remapped-rust-src-base=/rustc/FAKE_PREFIX");
1634 compiler.arg("-Ztranslate-remapped-path-to-local-path=no");
1635
1636 compiler.arg("-Z").arg(format!(
1641 "ignore-directory-in-diagnostics-source-blocks={}",
1642 home::cargo_home().expect("failed to find cargo home").to_str().unwrap()
1643 ));
1644 compiler.arg("-Z").arg(format!(
1646 "ignore-directory-in-diagnostics-source-blocks={}",
1647 self.config.src_root.join("vendor"),
1648 ));
1649
1650 if !self.props.compile_flags.iter().any(|flag| flag.starts_with("--sysroot"))
1654 && !self.config.host_rustcflags.iter().any(|flag| flag == "--sysroot")
1655 {
1656 compiler.arg("--sysroot").arg(&self.config.sysroot_base);
1658 }
1659
1660 if let Some(ref backend) = self.config.override_codegen_backend {
1662 compiler.arg(format!("-Zcodegen-backend={}", backend));
1663 }
1664
1665 let custom_target = self.props.compile_flags.iter().any(|x| x.starts_with("--target"));
1667
1668 if !custom_target {
1669 let target =
1670 if self.props.force_host { &*self.config.host } else { &*self.config.target };
1671
1672 compiler.arg(&format!("--target={}", target));
1673 if target.ends_with(".json") {
1674 compiler.arg("-Zunstable-options");
1677 }
1678 }
1679 self.set_revision_flags(&mut compiler);
1680
1681 if compiler_kind == CompilerKind::Rustc {
1682 if let Some(ref incremental_dir) = self.props.incremental_dir {
1683 compiler.args(&["-C", &format!("incremental={}", incremental_dir)]);
1684 compiler.args(&["-Z", "incremental-verify-ich"]);
1685 }
1686
1687 if self.config.mode == TestMode::CodegenUnits {
1688 compiler.args(&["-Z", "human_readable_cgu_names"]);
1689 }
1690 }
1691
1692 if self.config.optimize_tests && compiler_kind == CompilerKind::Rustc {
1693 match self.config.mode {
1694 TestMode::Ui => {
1695 if self.props.pass_mode(&self.config) == Some(PassMode::Run)
1700 && !self
1701 .props
1702 .compile_flags
1703 .iter()
1704 .any(|arg| arg == "-O" || arg.contains("opt-level"))
1705 {
1706 compiler.arg("-O");
1707 }
1708 }
1709 TestMode::DebugInfo => { }
1710 TestMode::CoverageMap | TestMode::CoverageRun => {
1711 }
1716 _ => {
1717 compiler.arg("-O");
1718 }
1719 }
1720 }
1721
1722 let set_mir_dump_dir = |rustc: &mut Command| {
1723 let mir_dump_dir = self.output_base_dir();
1724 let mut dir_opt = "-Zdump-mir-dir=".to_string();
1725 dir_opt.push_str(mir_dump_dir.as_str());
1726 debug!("dir_opt: {:?}", dir_opt);
1727 rustc.arg(dir_opt);
1728 };
1729
1730 match self.config.mode {
1731 TestMode::Incremental => {
1732 if self.props.error_patterns.is_empty()
1736 && self.props.regex_error_patterns.is_empty()
1737 {
1738 compiler.args(&["--error-format", "json"]);
1739 compiler.args(&["--json", "future-incompat"]);
1740 }
1741 compiler.arg("-Zui-testing");
1742 compiler.arg("-Zdeduplicate-diagnostics=no");
1743 }
1744 TestMode::Ui => {
1745 if !self.props.compile_flags.iter().any(|s| s.starts_with("--error-format")) {
1746 compiler.args(&["--error-format", "json"]);
1747 compiler.args(&["--json", "future-incompat"]);
1748 }
1749 compiler.arg("-Ccodegen-units=1");
1750 compiler.arg("-Zui-testing");
1752 compiler.arg("-Zdeduplicate-diagnostics=no");
1753 compiler.arg("-Zwrite-long-types-to-disk=no");
1754 compiler.arg("-Cstrip=debuginfo");
1756 }
1757 TestMode::MirOpt => {
1758 let zdump_arg = if !passes.is_empty() {
1762 format!("-Zdump-mir={}", passes.join(" | "))
1763 } else {
1764 "-Zdump-mir=all".to_string()
1765 };
1766
1767 compiler.args(&[
1768 "-Copt-level=1",
1769 &zdump_arg,
1770 "-Zvalidate-mir",
1771 "-Zlint-mir",
1772 "-Zdump-mir-exclude-pass-number",
1773 "-Zmir-include-spans=false", "--crate-type=rlib",
1775 ]);
1776 if let Some(pass) = &self.props.mir_unit_test {
1777 compiler
1778 .args(&["-Zmir-opt-level=0", &format!("-Zmir-enable-passes=+{}", pass)]);
1779 } else {
1780 compiler.args(&[
1781 "-Zmir-opt-level=4",
1782 "-Zmir-enable-passes=+ReorderBasicBlocks,+ReorderLocals",
1783 ]);
1784 }
1785
1786 set_mir_dump_dir(&mut compiler);
1787 }
1788 TestMode::CoverageMap => {
1789 compiler.arg("-Cinstrument-coverage");
1790 compiler.arg("-Zno-profiler-runtime");
1793 compiler.arg("-Copt-level=2");
1797 }
1798 TestMode::CoverageRun => {
1799 compiler.arg("-Cinstrument-coverage");
1800 compiler.arg("-Copt-level=2");
1804 }
1805 TestMode::Assembly | TestMode::Codegen => {
1806 compiler.arg("-Cdebug-assertions=no");
1807 compiler.arg("-Zcodegen-source-order");
1811 }
1812 TestMode::Crashes => {
1813 set_mir_dump_dir(&mut compiler);
1814 }
1815 TestMode::CodegenUnits => {
1816 compiler.arg("-Zprint-mono-items");
1817 }
1818 TestMode::Pretty
1819 | TestMode::DebugInfo
1820 | TestMode::RustdocHtml
1821 | TestMode::RustdocJson
1822 | TestMode::RunMake
1823 | TestMode::RustdocJs => {
1824 }
1826 }
1827
1828 if self.props.remap_src_base {
1829 compiler.arg(format!(
1830 "--remap-path-prefix={}={}",
1831 self.config.src_test_suite_root, FAKE_SRC_BASE,
1832 ));
1833 }
1834
1835 if compiler_kind == CompilerKind::Rustc {
1836 match emit {
1837 Emit::None => {}
1838 Emit::Metadata => {
1839 compiler.args(&["--emit", "metadata"]);
1840 }
1841 Emit::LlvmIr => {
1842 compiler.args(&["--emit", "llvm-ir"]);
1843 }
1844 Emit::Mir => {
1845 compiler.args(&["--emit", "mir"]);
1846 }
1847 Emit::Asm => {
1848 compiler.args(&["--emit", "asm"]);
1849 }
1850 Emit::LinkArgsAsm => {
1851 compiler.args(&["-Clink-args=--emit=asm"]);
1852 }
1853 }
1854 }
1855
1856 if compiler_kind == CompilerKind::Rustc {
1857 if self.config.target == "wasm32-unknown-unknown" || self.is_vxworks_pure_static() {
1858 } else if !self.props.no_prefer_dynamic {
1860 compiler.args(&["-C", "prefer-dynamic"]);
1861 }
1862 }
1863
1864 match output_file {
1865 _ if self.props.compile_flags.iter().any(|flag| flag == "-o") => {}
1868 TargetLocation::ThisFile(path) => {
1869 compiler.arg("-o").arg(path);
1870 }
1871 TargetLocation::ThisDirectory(path) => match compiler_kind {
1872 CompilerKind::Rustdoc => {
1873 compiler.arg("-o").arg(path);
1875 }
1876 CompilerKind::Rustc => {
1877 compiler.arg("--out-dir").arg(path);
1878 }
1879 },
1880 }
1881
1882 match self.config.compare_mode {
1883 Some(CompareMode::Polonius) => {
1884 compiler.args(&["-Zpolonius=next"]);
1885 }
1886 Some(CompareMode::NextSolver) => {
1887 compiler.args(&["-Znext-solver"]);
1888 }
1889 Some(CompareMode::NextSolverCoherence) => {
1890 compiler.args(&["-Znext-solver=coherence"]);
1891 }
1892 Some(CompareMode::SplitDwarf) if self.config.target.contains("windows") => {
1893 compiler.args(&["-Csplit-debuginfo=unpacked", "-Zunstable-options"]);
1894 }
1895 Some(CompareMode::SplitDwarf) => {
1896 compiler.args(&["-Csplit-debuginfo=unpacked"]);
1897 }
1898 Some(CompareMode::SplitDwarfSingle) => {
1899 compiler.args(&["-Csplit-debuginfo=packed"]);
1900 }
1901 None => {}
1902 }
1903
1904 if let AllowUnused::Yes = allow_unused {
1908 compiler.args(&["-A", "unused", "-W", "unused_attributes"]);
1909 }
1910
1911 compiler.args(&["-A", "internal_features"]);
1913
1914 compiler.args(&["-A", "unused_parens"]);
1918 compiler.args(&["-A", "unused_braces"]);
1919
1920 if self.props.force_host {
1921 self.maybe_add_external_args(&mut compiler, &self.config.host_rustcflags);
1922 if compiler_kind == CompilerKind::Rustc
1923 && let Some(ref linker) = self.config.host_linker
1924 {
1925 compiler.arg(format!("-Clinker={linker}"));
1926 }
1927 } else {
1928 self.maybe_add_external_args(&mut compiler, &self.config.target_rustcflags);
1929 if compiler_kind == CompilerKind::Rustc
1930 && let Some(ref linker) = self.config.target_linker
1931 {
1932 compiler.arg(format!("-Clinker={linker}"));
1933 }
1934 }
1935
1936 if self.config.host.contains("musl") || self.is_vxworks_pure_dynamic() {
1938 compiler.arg("-Ctarget-feature=-crt-static");
1939 }
1940
1941 if let LinkToAux::Yes = link_to_aux {
1942 if self.has_aux_dir() {
1945 compiler.arg("-L").arg(self.aux_output_dir_name());
1946 }
1947 }
1948
1949 if self.props.add_minicore {
1959 compiler.arg("-Cpanic=abort");
1960 compiler.arg("-Cforce-unwind-tables=yes");
1961 }
1962
1963 compiler.args(&self.props.compile_flags);
1964
1965 compiler
1966 }
1967
1968 fn make_exe_name(&self) -> Utf8PathBuf {
1969 let mut f = self.output_base_dir().join("a");
1974 if self.config.target.contains("emscripten") {
1976 f = f.with_extra_extension("js");
1977 } else if self.config.target.starts_with("wasm") {
1978 f = f.with_extra_extension("wasm");
1979 } else if self.config.target.contains("spirv") {
1980 f = f.with_extra_extension("spv");
1981 } else if !env::consts::EXE_SUFFIX.is_empty() {
1982 f = f.with_extra_extension(env::consts::EXE_SUFFIX);
1983 }
1984 f
1985 }
1986
1987 fn make_run_args(&self) -> ProcArgs {
1988 let mut args = self.split_maybe_args(&self.config.runner);
1991
1992 let exe_file = self.make_exe_name();
1993
1994 args.push(exe_file.into_os_string());
1995
1996 args.extend(self.props.run_flags.iter().map(OsString::from));
1998
1999 let prog = args.remove(0);
2000 ProcArgs { prog, args }
2001 }
2002
2003 fn split_maybe_args(&self, argstr: &Option<String>) -> Vec<OsString> {
2004 match *argstr {
2005 Some(ref s) => s
2006 .split(' ')
2007 .filter_map(|s| {
2008 if s.chars().all(|c| c.is_whitespace()) {
2009 None
2010 } else {
2011 Some(OsString::from(s))
2012 }
2013 })
2014 .collect(),
2015 None => Vec::new(),
2016 }
2017 }
2018
2019 fn make_cmdline(&self, command: &Command, libpath: &Utf8Path) -> String {
2020 use crate::util;
2021
2022 if cfg!(unix) {
2024 format!("{:?}", command)
2025 } else {
2026 fn lib_path_cmd_prefix(path: &str) -> String {
2029 format!("{}=\"{}\"", util::lib_path_env_var(), util::make_new_path(path))
2030 }
2031
2032 format!("{} {:?}", lib_path_cmd_prefix(libpath.as_str()), command)
2033 }
2034 }
2035
2036 fn dump_output(&self, print_output: bool, proc_name: &str, out: &str, err: &str) {
2037 let revision = if let Some(r) = self.revision { format!("{}.", r) } else { String::new() };
2038
2039 self.dump_output_file(out, &format!("{}out", revision));
2040 self.dump_output_file(err, &format!("{}err", revision));
2041
2042 if !print_output {
2043 return;
2044 }
2045
2046 let path = Utf8Path::new(proc_name);
2047 let proc_name = if path.file_stem().is_some_and(|p| p == "rmake") {
2048 String::from_iter(
2049 path.parent()
2050 .unwrap()
2051 .file_name()
2052 .into_iter()
2053 .chain(Some("/"))
2054 .chain(path.file_name()),
2055 )
2056 } else {
2057 path.file_name().unwrap().into()
2058 };
2059 writeln!(self.stdout, "------{proc_name} stdout------------------------------");
2060 writeln!(self.stdout, "{}", out);
2061 writeln!(self.stdout, "------{proc_name} stderr------------------------------");
2062 writeln!(self.stdout, "{}", err);
2063 writeln!(self.stdout, "------------------------------------------");
2064 }
2065
2066 fn dump_output_file(&self, out: &str, extension: &str) {
2067 let outfile = self.make_out_name(extension);
2068 fs::write(outfile.as_std_path(), out)
2069 .unwrap_or_else(|err| panic!("failed to write {outfile}: {err:?}"));
2070 }
2071
2072 fn make_out_name(&self, extension: &str) -> Utf8PathBuf {
2075 self.output_base_name().with_extension(extension)
2076 }
2077
2078 fn aux_output_dir_name(&self) -> Utf8PathBuf {
2081 self.output_base_dir()
2082 .join("auxiliary")
2083 .with_extra_extension(self.config.mode.aux_dir_disambiguator())
2084 }
2085
2086 fn aux_bin_output_dir_name(&self) -> Utf8PathBuf {
2089 self.aux_output_dir_name().join("bin")
2090 }
2091
2092 fn safe_revision(&self) -> Option<&str> {
2095 if self.config.mode == TestMode::Incremental { None } else { self.revision }
2096 }
2097
2098 fn output_base_dir(&self) -> Utf8PathBuf {
2102 output_base_dir(self.config, self.testpaths, self.safe_revision())
2103 }
2104
2105 fn output_base_name(&self) -> Utf8PathBuf {
2109 output_base_name(self.config, self.testpaths, self.safe_revision())
2110 }
2111
2112 fn logv(&self, message: impl fmt::Display) {
2117 debug!("{message}");
2118 if self.config.verbose {
2119 writeln!(self.stdout, "{message}");
2121 }
2122 }
2123
2124 #[must_use]
2127 fn error_prefix(&self) -> String {
2128 match self.revision {
2129 Some(rev) => format!("error in revision `{rev}`"),
2130 None => format!("error"),
2131 }
2132 }
2133
2134 #[track_caller]
2135 fn fatal(&self, err: &str) -> ! {
2136 writeln!(self.stdout, "\n{prefix}: {err}", prefix = self.error_prefix());
2137 error!("fatal error, panic: {:?}", err);
2138 panic!("fatal error");
2139 }
2140
2141 fn fatal_proc_rec(&self, err: &str, proc_res: &ProcRes) -> ! {
2142 self.fatal_proc_rec_general(err, None, proc_res, || ());
2143 }
2144
2145 fn fatal_proc_rec_general(
2148 &self,
2149 err: &str,
2150 extra_note: Option<&str>,
2151 proc_res: &ProcRes,
2152 callback_before_unwind: impl FnOnce(),
2153 ) -> ! {
2154 writeln!(self.stdout, "\n{prefix}: {err}", prefix = self.error_prefix());
2155
2156 if let Some(note) = extra_note {
2158 writeln!(self.stdout, "{note}");
2159 }
2160
2161 writeln!(self.stdout, "{}", proc_res.format_info());
2163
2164 callback_before_unwind();
2166
2167 std::panic::resume_unwind(Box::new(()));
2170 }
2171
2172 fn compile_test_and_save_ir(&self) -> (ProcRes, Utf8PathBuf) {
2175 let output_path = self.output_base_name().with_extension("ll");
2176 let input_file = &self.testpaths.file;
2177 let rustc = self.make_compile_args(
2178 CompilerKind::Rustc,
2179 input_file,
2180 TargetLocation::ThisFile(output_path.clone()),
2181 Emit::LlvmIr,
2182 AllowUnused::No,
2183 LinkToAux::Yes,
2184 Vec::new(),
2185 );
2186
2187 let proc_res = self.compose_and_run_compiler(rustc, None);
2188 (proc_res, output_path)
2189 }
2190
2191 fn verify_with_filecheck(&self, output: &Utf8Path) -> ProcRes {
2192 let mut filecheck = Command::new(self.config.llvm_filecheck.as_ref().unwrap());
2193 filecheck.arg("--input-file").arg(output).arg(&self.testpaths.file);
2194
2195 filecheck.arg("--check-prefix=CHECK");
2197
2198 if let Some(rev) = self.revision {
2206 filecheck.arg("--check-prefix").arg(rev);
2207 }
2208
2209 filecheck.arg("--allow-unused-prefixes");
2213
2214 filecheck.args(&["--dump-input-context", "100"]);
2216
2217 filecheck.args(&self.props.filecheck_flags);
2219
2220 self.compose_and_run(filecheck, Utf8Path::new(""), None, None)
2222 }
2223
2224 fn charset() -> &'static str {
2225 if cfg!(target_os = "freebsd") { "ISO-8859-1" } else { "UTF-8" }
2227 }
2228
2229 fn get_lines(&self, path: &Utf8Path, mut other_files: Option<&mut Vec<String>>) -> Vec<usize> {
2230 let content = fs::read_to_string(path.as_std_path()).unwrap();
2231 let mut ignore = false;
2232 content
2233 .lines()
2234 .enumerate()
2235 .filter_map(|(line_nb, line)| {
2236 if (line.trim_start().starts_with("pub mod ")
2237 || line.trim_start().starts_with("mod "))
2238 && line.ends_with(';')
2239 {
2240 if let Some(ref mut other_files) = other_files {
2241 other_files.push(line.rsplit("mod ").next().unwrap().replace(';', ""));
2242 }
2243 None
2244 } else {
2245 let sline = line.rsplit("///").next().unwrap();
2246 let line = sline.trim_start();
2247 if line.starts_with("```") {
2248 if ignore {
2249 ignore = false;
2250 None
2251 } else {
2252 ignore = true;
2253 Some(line_nb + 1)
2254 }
2255 } else {
2256 None
2257 }
2258 }
2259 })
2260 .collect()
2261 }
2262
2263 fn check_rustdoc_test_option(&self, res: ProcRes) {
2268 let mut other_files = Vec::new();
2269 let mut files: HashMap<String, Vec<usize>> = HashMap::new();
2270 let normalized = fs::canonicalize(&self.testpaths.file).expect("failed to canonicalize");
2271 let normalized = normalized.to_str().unwrap().replace('\\', "/");
2272 files.insert(normalized, self.get_lines(&self.testpaths.file, Some(&mut other_files)));
2273 for other_file in other_files {
2274 let mut path = self.testpaths.file.clone();
2275 path.set_file_name(&format!("{}.rs", other_file));
2276 let path = path.canonicalize_utf8().expect("failed to canonicalize");
2277 let normalized = path.as_str().replace('\\', "/");
2278 files.insert(normalized, self.get_lines(&path, None));
2279 }
2280
2281 let mut tested = 0;
2282 for _ in res.stdout.split('\n').filter(|s| s.starts_with("test ")).inspect(|s| {
2283 if let Some((left, right)) = s.split_once(" - ") {
2284 let path = left.rsplit("test ").next().unwrap();
2285 let path = fs::canonicalize(&path).expect("failed to canonicalize");
2286 let path = path.to_str().unwrap().replace('\\', "/");
2287 if let Some(ref mut v) = files.get_mut(&path) {
2288 tested += 1;
2289 let mut iter = right.split("(line ");
2290 iter.next();
2291 let line = iter
2292 .next()
2293 .unwrap_or(")")
2294 .split(')')
2295 .next()
2296 .unwrap_or("0")
2297 .parse()
2298 .unwrap_or(0);
2299 if let Ok(pos) = v.binary_search(&line) {
2300 v.remove(pos);
2301 } else {
2302 self.fatal_proc_rec(
2303 &format!("Not found doc test: \"{}\" in \"{}\":{:?}", s, path, v),
2304 &res,
2305 );
2306 }
2307 }
2308 }
2309 }) {}
2310 if tested == 0 {
2311 self.fatal_proc_rec(&format!("No test has been found... {:?}", files), &res);
2312 } else {
2313 for (entry, v) in &files {
2314 if !v.is_empty() {
2315 self.fatal_proc_rec(
2316 &format!(
2317 "Not found test at line{} \"{}\":{:?}",
2318 if v.len() > 1 { "s" } else { "" },
2319 entry,
2320 v
2321 ),
2322 &res,
2323 );
2324 }
2325 }
2326 }
2327 }
2328
2329 fn force_color_svg(&self) -> bool {
2330 self.props.compile_flags.iter().any(|s| s.contains("--color=always"))
2331 }
2332
2333 fn load_compare_outputs(
2334 &self,
2335 proc_res: &ProcRes,
2336 output_kind: TestOutput,
2337 explicit_format: bool,
2338 ) -> usize {
2339 let stderr_bits = format!("{}bit.stderr", self.config.get_pointer_width());
2340 let (stderr_kind, stdout_kind) = match output_kind {
2341 TestOutput::Compile => (
2342 if self.force_color_svg() {
2343 if self.config.target.contains("windows") {
2344 UI_WINDOWS_SVG
2347 } else {
2348 UI_SVG
2349 }
2350 } else if self.props.stderr_per_bitwidth {
2351 &stderr_bits
2352 } else {
2353 UI_STDERR
2354 },
2355 UI_STDOUT,
2356 ),
2357 TestOutput::Run => (UI_RUN_STDERR, UI_RUN_STDOUT),
2358 };
2359
2360 let expected_stderr = self.load_expected_output(stderr_kind);
2361 let expected_stdout = self.load_expected_output(stdout_kind);
2362
2363 let mut normalized_stdout =
2364 self.normalize_output(&proc_res.stdout, &self.props.normalize_stdout);
2365 match output_kind {
2366 TestOutput::Run if self.config.remote_test_client.is_some() => {
2367 normalized_stdout = static_regex!(
2372 "^uploaded \"\\$TEST_BUILD_DIR(/[[:alnum:]_\\-.]+)+\", waiting for result\n"
2373 )
2374 .replace(&normalized_stdout, "")
2375 .to_string();
2376 normalized_stdout = static_regex!("^died due to signal [0-9]+\n")
2379 .replace(&normalized_stdout, "")
2380 .to_string();
2381 }
2384 _ => {}
2385 };
2386
2387 let stderr = if self.force_color_svg() {
2388 anstyle_svg::Term::new().render_svg(&proc_res.stderr)
2389 } else if explicit_format {
2390 proc_res.stderr.clone()
2391 } else {
2392 json::extract_rendered(&proc_res.stderr)
2393 };
2394
2395 let normalized_stderr = self.normalize_output(&stderr, &self.props.normalize_stderr);
2396 let mut errors = 0;
2397 match output_kind {
2398 TestOutput::Compile => {
2399 if !self.props.dont_check_compiler_stdout {
2400 if self
2401 .compare_output(
2402 stdout_kind,
2403 &normalized_stdout,
2404 &proc_res.stdout,
2405 &expected_stdout,
2406 )
2407 .should_error()
2408 {
2409 errors += 1;
2410 }
2411 }
2412 if !self.props.dont_check_compiler_stderr {
2413 if self
2414 .compare_output(stderr_kind, &normalized_stderr, &stderr, &expected_stderr)
2415 .should_error()
2416 {
2417 errors += 1;
2418 }
2419 }
2420 }
2421 TestOutput::Run => {
2422 if self
2423 .compare_output(
2424 stdout_kind,
2425 &normalized_stdout,
2426 &proc_res.stdout,
2427 &expected_stdout,
2428 )
2429 .should_error()
2430 {
2431 errors += 1;
2432 }
2433
2434 if self
2435 .compare_output(stderr_kind, &normalized_stderr, &stderr, &expected_stderr)
2436 .should_error()
2437 {
2438 errors += 1;
2439 }
2440 }
2441 }
2442 errors
2443 }
2444
2445 fn normalize_output(&self, output: &str, custom_rules: &[(String, String)]) -> String {
2446 let rflags = self.props.run_flags.join(" ");
2449 let cflags = self.props.compile_flags.join(" ");
2450 let json = rflags.contains("--format json")
2451 || rflags.contains("--format=json")
2452 || cflags.contains("--error-format json")
2453 || cflags.contains("--error-format pretty-json")
2454 || cflags.contains("--error-format=json")
2455 || cflags.contains("--error-format=pretty-json")
2456 || cflags.contains("--output-format json")
2457 || cflags.contains("--output-format=json");
2458
2459 let mut normalized = output.to_string();
2460
2461 let mut normalize_path = |from: &Utf8Path, to: &str| {
2462 let from = if json { &from.as_str().replace("\\", "\\\\") } else { from.as_str() };
2463
2464 normalized = normalized.replace(from, to);
2465 };
2466
2467 let parent_dir = self.testpaths.file.parent().unwrap();
2468 normalize_path(parent_dir, "$DIR");
2469
2470 if self.props.remap_src_base {
2471 let mut remapped_parent_dir = Utf8PathBuf::from(FAKE_SRC_BASE);
2472 if self.testpaths.relative_dir != Utf8Path::new("") {
2473 remapped_parent_dir.push(&self.testpaths.relative_dir);
2474 }
2475 normalize_path(&remapped_parent_dir, "$DIR");
2476 }
2477
2478 let base_dir = Utf8Path::new("/rustc/FAKE_PREFIX");
2479 normalize_path(&base_dir.join("library"), "$SRC_DIR");
2481 normalize_path(&base_dir.join("compiler"), "$COMPILER_DIR");
2485
2486 let rust_src_dir = &self.config.sysroot_base.join("lib/rustlib/src/rust");
2488 rust_src_dir.try_exists().expect(&*format!("{} should exists", rust_src_dir));
2489 let rust_src_dir =
2490 rust_src_dir.read_link_utf8().unwrap_or_else(|_| rust_src_dir.to_path_buf());
2491 normalize_path(&rust_src_dir.join("library"), "$SRC_DIR_REAL");
2492
2493 let rustc_src_dir = &self.config.sysroot_base.join("lib/rustlib/rustc-src/rust");
2495 rustc_src_dir.try_exists().expect(&*format!("{} should exists", rustc_src_dir));
2496 let rustc_src_dir = rustc_src_dir.read_link_utf8().unwrap_or(rustc_src_dir.to_path_buf());
2497 normalize_path(&rustc_src_dir.join("compiler"), "$COMPILER_DIR_REAL");
2498
2499 normalize_path(&self.output_base_dir(), "$TEST_BUILD_DIR");
2502 normalize_path(&self.output_base_dir().canonicalize_utf8().unwrap(), "$TEST_BUILD_DIR");
2509 normalize_path(&self.config.build_root, "$BUILD_DIR");
2511
2512 if json {
2513 normalized = normalized.replace("\\n", "\n");
2518 }
2519
2520 normalized = static_regex!("SRC_DIR(.+):\\d+:\\d+(: \\d+:\\d+)?")
2525 .replace_all(&normalized, "SRC_DIR$1:LL:COL")
2526 .into_owned();
2527
2528 normalized = Self::normalize_platform_differences(&normalized);
2529
2530 normalized =
2532 static_regex!(r"\$TEST_BUILD_DIR/(?P<filename>[^\.]+).long-type-(?P<hash>\d+).txt")
2533 .replace_all(&normalized, |caps: &Captures<'_>| {
2534 format!(
2535 "$TEST_BUILD_DIR/{filename}.long-type-$LONG_TYPE_HASH.txt",
2536 filename = &caps["filename"]
2537 )
2538 })
2539 .into_owned();
2540
2541 normalized = static_regex!(r"thread '(?P<name>.*?)' \((rtid )?\d+\) panicked")
2543 .replace_all(&normalized, "thread '$name' ($$TID) panicked")
2544 .into_owned();
2545
2546 normalized = normalized.replace("\t", "\\t"); normalized =
2553 static_regex!("\\s*//(\\[.*\\])?~.*").replace_all(&normalized, "").into_owned();
2554
2555 let v0_crate_hash_prefix_re = static_regex!(r"_R.*?Cs[0-9a-zA-Z]+_");
2558 let v0_crate_hash_re = static_regex!(r"Cs[0-9a-zA-Z]+_");
2559
2560 const V0_CRATE_HASH_PLACEHOLDER: &str = r"CsCRATE_HASH_";
2561 if v0_crate_hash_prefix_re.is_match(&normalized) {
2562 normalized =
2564 v0_crate_hash_re.replace_all(&normalized, V0_CRATE_HASH_PLACEHOLDER).into_owned();
2565 }
2566
2567 let v0_back_ref_prefix_re = static_regex!(r"\(_R.*?B[0-9a-zA-Z]_");
2568 let v0_back_ref_re = static_regex!(r"B[0-9a-zA-Z]_");
2569
2570 const V0_BACK_REF_PLACEHOLDER: &str = r"B<REF>_";
2571 if v0_back_ref_prefix_re.is_match(&normalized) {
2572 normalized =
2574 v0_back_ref_re.replace_all(&normalized, V0_BACK_REF_PLACEHOLDER).into_owned();
2575 }
2576
2577 {
2584 let mut seen_allocs = indexmap::IndexSet::new();
2585
2586 normalized = static_regex!(
2588 r"╾─*a(lloc)?([0-9]+)(\+0x[0-9a-f]+)?(<imm>)?( \([0-9]+ ptr bytes\))?─*╼"
2589 )
2590 .replace_all(&normalized, |caps: &Captures<'_>| {
2591 let index = caps.get(2).unwrap().as_str().to_string();
2593 let (index, _) = seen_allocs.insert_full(index);
2594 let offset = caps.get(3).map_or("", |c| c.as_str());
2595 let imm = caps.get(4).map_or("", |c| c.as_str());
2596 format!("╾ALLOC{index}{offset}{imm}╼")
2598 })
2599 .into_owned();
2600
2601 normalized = static_regex!(r"\balloc([0-9]+)\b")
2603 .replace_all(&normalized, |caps: &Captures<'_>| {
2604 let index = caps.get(1).unwrap().as_str().to_string();
2605 let (index, _) = seen_allocs.insert_full(index);
2606 format!("ALLOC{index}")
2607 })
2608 .into_owned();
2609 }
2610
2611 for rule in custom_rules {
2613 let re = Regex::new(&rule.0).expect("bad regex in custom normalization rule");
2614 normalized = re.replace_all(&normalized, &rule.1[..]).into_owned();
2615 }
2616 normalized
2617 }
2618
2619 fn normalize_platform_differences(output: &str) -> String {
2625 let output = output.replace(r"\\", r"\");
2626
2627 let re = static_regex!(
2632 r#"(?x)
2633 (?:
2634 # Match paths that don't include spaces.
2635 (?:\\[\pL\pN\.\-_']+)+\.\pL+
2636 |
2637 # If the path starts with a well-known root, then allow spaces and no file extension.
2638 \$(?:DIR|SRC_DIR|TEST_BUILD_DIR|BUILD_DIR|LIB_DIR)(?:\\[\pL\pN\.\-_'\ ]+)+
2639 )"#
2640 );
2641 re.replace_all(&output, |caps: &Captures<'_>| caps[0].replace(r"\", "/"))
2642 .replace("\r\n", "\n")
2643 }
2644
2645 fn expected_output_path(&self, kind: &str) -> Utf8PathBuf {
2646 let mut path =
2647 expected_output_path(&self.testpaths, self.revision, &self.config.compare_mode, kind);
2648
2649 if !path.exists() {
2650 if let Some(CompareMode::Polonius) = self.config.compare_mode {
2651 path = expected_output_path(&self.testpaths, self.revision, &None, kind);
2652 }
2653 }
2654
2655 if !path.exists() {
2656 path = expected_output_path(&self.testpaths, self.revision, &None, kind);
2657 }
2658
2659 path
2660 }
2661
2662 fn load_expected_output(&self, kind: &str) -> String {
2663 let path = self.expected_output_path(kind);
2664 if path.exists() {
2665 match self.load_expected_output_from_path(&path) {
2666 Ok(x) => x,
2667 Err(x) => self.fatal(&x),
2668 }
2669 } else {
2670 String::new()
2671 }
2672 }
2673
2674 fn load_expected_output_from_path(&self, path: &Utf8Path) -> Result<String, String> {
2675 fs::read_to_string(path)
2676 .map_err(|err| format!("failed to load expected output from `{}`: {}", path, err))
2677 }
2678
2679 fn delete_file(&self, file: &Utf8Path) {
2681 if let Err(e) = fs::remove_file(file.as_std_path())
2682 && e.kind() != io::ErrorKind::NotFound
2683 {
2684 self.fatal(&format!("failed to delete `{}`: {}", file, e,));
2685 }
2686 }
2687
2688 fn compare_output(
2689 &self,
2690 stream: &str,
2691 actual: &str,
2692 actual_unnormalized: &str,
2693 expected: &str,
2694 ) -> CompareOutcome {
2695 let expected_path =
2696 expected_output_path(self.testpaths, self.revision, &self.config.compare_mode, stream);
2697
2698 if self.config.bless && actual.is_empty() && expected_path.exists() {
2699 self.delete_file(&expected_path);
2700 }
2701
2702 let are_different = match (self.force_color_svg(), expected.find('\n'), actual.find('\n')) {
2703 (true, Some(nl_e), Some(nl_a)) => expected[nl_e..] != actual[nl_a..],
2706 _ => expected != actual,
2707 };
2708 if !are_different {
2709 return CompareOutcome::Same;
2710 }
2711
2712 let compare_output_by_lines =
2719 self.props.compare_output_by_lines || self.config.runner.is_some();
2720
2721 let tmp;
2722 let (expected, actual): (&str, &str) = if compare_output_by_lines {
2723 let actual_lines: HashSet<_> = actual.lines().collect();
2724 let expected_lines: Vec<_> = expected.lines().collect();
2725 let mut used = expected_lines.clone();
2726 used.retain(|line| actual_lines.contains(line));
2727 if used.len() == expected_lines.len() && (expected.is_empty() == actual.is_empty()) {
2729 return CompareOutcome::Same;
2730 }
2731 if expected_lines.is_empty() {
2732 ("", actual)
2734 } else {
2735 tmp = (expected_lines.join("\n"), used.join("\n"));
2736 (&tmp.0, &tmp.1)
2737 }
2738 } else {
2739 (expected, actual)
2740 };
2741
2742 let actual_path = self
2744 .output_base_name()
2745 .with_extra_extension(self.revision.unwrap_or(""))
2746 .with_extra_extension(
2747 self.config.compare_mode.as_ref().map(|cm| cm.to_str()).unwrap_or(""),
2748 )
2749 .with_extra_extension(stream);
2750
2751 if let Err(err) = fs::write(&actual_path, &actual) {
2752 self.fatal(&format!("failed to write {stream} to `{actual_path}`: {err}",));
2753 }
2754 writeln!(self.stdout, "Saved the actual {stream} to `{actual_path}`");
2755
2756 if !self.config.bless {
2757 if expected.is_empty() {
2758 writeln!(self.stdout, "normalized {}:\n{}\n", stream, actual);
2759 } else {
2760 self.show_diff(
2761 stream,
2762 &expected_path,
2763 &actual_path,
2764 expected,
2765 actual,
2766 actual_unnormalized,
2767 );
2768 }
2769 } else {
2770 if self.revision.is_some() {
2773 let old =
2774 expected_output_path(self.testpaths, None, &self.config.compare_mode, stream);
2775 self.delete_file(&old);
2776 }
2777
2778 if !actual.is_empty() {
2779 if let Err(err) = fs::write(&expected_path, &actual) {
2780 self.fatal(&format!("failed to write {stream} to `{expected_path}`: {err}"));
2781 }
2782 writeln!(
2783 self.stdout,
2784 "Blessing the {stream} of `{test_name}` as `{expected_path}`",
2785 test_name = self.testpaths.file
2786 );
2787 }
2788 }
2789
2790 writeln!(self.stdout, "\nThe actual {stream} differed from the expected {stream}");
2791
2792 if self.config.bless { CompareOutcome::Blessed } else { CompareOutcome::Differed }
2793 }
2794
2795 fn show_diff(
2797 &self,
2798 stream: &str,
2799 expected_path: &Utf8Path,
2800 actual_path: &Utf8Path,
2801 expected: &str,
2802 actual: &str,
2803 actual_unnormalized: &str,
2804 ) {
2805 writeln!(self.stderr, "diff of {stream}:\n");
2806 if let Some(diff_command) = self.config.diff_command.as_deref() {
2807 let mut args = diff_command.split_whitespace();
2808 let name = args.next().unwrap();
2809 match Command::new(name).args(args).args([expected_path, actual_path]).output() {
2810 Err(err) => {
2811 self.fatal(&format!(
2812 "failed to call custom diff command `{diff_command}`: {err}"
2813 ));
2814 }
2815 Ok(output) => {
2816 let output = String::from_utf8_lossy(&output.stdout);
2817 write!(self.stderr, "{output}");
2818 }
2819 }
2820 } else {
2821 write!(self.stderr, "{}", write_diff(expected, actual, 3));
2822 }
2823
2824 let diff_results = make_diff(actual, expected, 0);
2826
2827 let (mut mismatches_normalized, mut mismatch_line_nos) = (String::new(), vec![]);
2828 for hunk in diff_results {
2829 let mut line_no = hunk.line_number;
2830 for line in hunk.lines {
2831 if let DiffLine::Expected(normalized) = line {
2833 mismatches_normalized += &normalized;
2834 mismatches_normalized += "\n";
2835 mismatch_line_nos.push(line_no);
2836 line_no += 1;
2837 }
2838 }
2839 }
2840 let mut mismatches_unnormalized = String::new();
2841 let diff_normalized = make_diff(actual, actual_unnormalized, 0);
2842 for hunk in diff_normalized {
2843 if mismatch_line_nos.contains(&hunk.line_number) {
2844 for line in hunk.lines {
2845 if let DiffLine::Resulting(unnormalized) = line {
2846 mismatches_unnormalized += &unnormalized;
2847 mismatches_unnormalized += "\n";
2848 }
2849 }
2850 }
2851 }
2852
2853 let normalized_diff = make_diff(&mismatches_normalized, &mismatches_unnormalized, 0);
2854 if !normalized_diff.is_empty()
2856 && !mismatches_unnormalized.is_empty()
2857 && !mismatches_normalized.is_empty()
2858 {
2859 writeln!(
2860 self.stderr,
2861 "Note: some mismatched output was normalized before being compared"
2862 );
2863 write!(
2865 self.stderr,
2866 "{}",
2867 write_diff(&mismatches_unnormalized, &mismatches_normalized, 0)
2868 );
2869 }
2870 }
2871
2872 fn check_and_prune_duplicate_outputs(
2873 &self,
2874 proc_res: &ProcRes,
2875 modes: &[CompareMode],
2876 require_same_modes: &[CompareMode],
2877 ) {
2878 for kind in UI_EXTENSIONS {
2879 let canon_comparison_path =
2880 expected_output_path(&self.testpaths, self.revision, &None, kind);
2881
2882 let canon = match self.load_expected_output_from_path(&canon_comparison_path) {
2883 Ok(canon) => canon,
2884 _ => continue,
2885 };
2886 let bless = self.config.bless;
2887 let check_and_prune_duplicate_outputs = |mode: &CompareMode, require_same: bool| {
2888 let examined_path =
2889 expected_output_path(&self.testpaths, self.revision, &Some(mode.clone()), kind);
2890
2891 let examined_content = match self.load_expected_output_from_path(&examined_path) {
2893 Ok(content) => content,
2894 _ => return,
2895 };
2896
2897 let is_duplicate = canon == examined_content;
2898
2899 match (bless, require_same, is_duplicate) {
2900 (true, _, true) => {
2902 self.delete_file(&examined_path);
2903 }
2904 (_, true, false) => {
2907 self.fatal_proc_rec(
2908 &format!("`{}` should not have different output from base test!", kind),
2909 proc_res,
2910 );
2911 }
2912 _ => {}
2913 }
2914 };
2915 for mode in modes {
2916 check_and_prune_duplicate_outputs(mode, false);
2917 }
2918 for mode in require_same_modes {
2919 check_and_prune_duplicate_outputs(mode, true);
2920 }
2921 }
2922 }
2923
2924 fn create_stamp(&self) {
2925 let stamp_file_path = stamp_file_path(&self.config, self.testpaths, self.revision);
2926 fs::write(&stamp_file_path, compute_stamp_hash(&self.config)).unwrap();
2927 }
2928
2929 fn init_incremental_test(&self) {
2930 let incremental_dir = self.props.incremental_dir.as_ref().unwrap();
2937 if incremental_dir.exists() {
2938 let canonicalized = incremental_dir.canonicalize().unwrap();
2941 fs::remove_dir_all(canonicalized).unwrap();
2942 }
2943 fs::create_dir_all(&incremental_dir).unwrap();
2944
2945 if self.config.verbose {
2946 writeln!(self.stdout, "init_incremental_test: incremental_dir={incremental_dir}");
2947 }
2948 }
2949}
2950
2951struct ProcArgs {
2952 prog: OsString,
2953 args: Vec<OsString>,
2954}
2955
2956#[derive(Debug)]
2957pub struct ProcRes {
2958 status: ExitStatus,
2959 stdout: String,
2960 stderr: String,
2961 truncated: Truncated,
2962 cmdline: String,
2963}
2964
2965impl ProcRes {
2966 #[must_use]
2967 pub fn format_info(&self) -> String {
2968 fn render(name: &str, contents: &str) -> String {
2969 let contents = json::extract_rendered(contents);
2970 let contents = contents.trim_end();
2971 if contents.is_empty() {
2972 format!("{name}: none")
2973 } else {
2974 format!(
2975 "\
2976 --- {name} -------------------------------\n\
2977 {contents}\n\
2978 ------------------------------------------",
2979 )
2980 }
2981 }
2982
2983 format!(
2984 "status: {}\ncommand: {}\n{}\n{}\n",
2985 self.status,
2986 self.cmdline,
2987 render("stdout", &self.stdout),
2988 render("stderr", &self.stderr),
2989 )
2990 }
2991}
2992
2993#[derive(Debug)]
2994enum TargetLocation {
2995 ThisFile(Utf8PathBuf),
2996 ThisDirectory(Utf8PathBuf),
2997}
2998
2999enum AllowUnused {
3000 Yes,
3001 No,
3002}
3003
3004enum LinkToAux {
3005 Yes,
3006 No,
3007}
3008
3009#[derive(Debug, PartialEq)]
3010enum AuxType {
3011 Bin,
3012 Lib,
3013 Dylib,
3014 ProcMacro,
3015}
3016
3017#[derive(Copy, Clone, Debug, PartialEq, Eq)]
3020enum CompareOutcome {
3021 Same,
3023 Blessed,
3025 Differed,
3027}
3028
3029#[derive(Clone, Copy, Debug, PartialEq, Eq)]
3030enum DocKind {
3031 Html,
3032 Json,
3033}
3034
3035impl CompareOutcome {
3036 fn should_error(&self) -> bool {
3037 matches!(self, CompareOutcome::Differed)
3038 }
3039}