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, ForcePassMode, PassFailMode, 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::executor::TestVariant;
24use crate::output_capture::ConsoleOut;
25use crate::read2::{Truncated, read2_abbreviated};
26use crate::runtest::compute_diff::{DiffLine, diff_by_lines, make_diff, write_diff};
27use crate::util::{ArgFileCommand, Utf8PathBufExt, add_dylib_path, static_regex};
28use crate::{json, stamp_file_path};
29
30mod assembly;
33mod codegen;
34mod codegen_units;
35mod coverage;
36mod crashes;
37mod debuginfo;
38mod incremental;
39mod js_doc;
40mod mir_opt;
41mod pretty;
42mod run_make;
43mod rustdoc;
44mod rustdoc_json;
45mod ui;
46mod compute_diff;
49mod debugger;
50#[cfg(test)]
51mod tests;
52
53const FAKE_SRC_BASE: &str = "fake-test-src-base";
54
55#[cfg(windows)]
56fn disable_error_reporting<F: FnOnce() -> R, R>(f: F) -> R {
57 use std::sync::Mutex;
58
59 use windows::Win32::System::Diagnostics::Debug::{
60 SEM_FAILCRITICALERRORS, SEM_NOGPFAULTERRORBOX, SetErrorMode,
61 };
62
63 static LOCK: Mutex<()> = Mutex::new(());
64
65 let _lock = LOCK.lock().unwrap();
67
68 unsafe {
79 let old_mode = SetErrorMode(SEM_NOGPFAULTERRORBOX | SEM_FAILCRITICALERRORS);
81 SetErrorMode(old_mode | SEM_NOGPFAULTERRORBOX | SEM_FAILCRITICALERRORS);
82 let r = f();
83 SetErrorMode(old_mode);
84 r
85 }
86}
87
88#[cfg(not(windows))]
89fn disable_error_reporting<F: FnOnce() -> R, R>(f: F) -> R {
90 f()
91}
92
93fn get_lib_name(name: &str, aux_type: AuxType, wasm_proc_macros: bool) -> Option<String> {
95 match aux_type {
96 AuxType::Bin => None,
97 AuxType::Lib => Some(format!("lib{name}.rlib")),
102 AuxType::ProcMacro if wasm_proc_macros => Some(format!("{name}.wasm")),
104 AuxType::Dylib | AuxType::ProcMacro => Some(dylib_name(name)),
105 }
106}
107
108fn dylib_name(name: &str) -> String {
109 format!("{}{name}.{}", std::env::consts::DLL_PREFIX, std::env::consts::DLL_EXTENSION)
110}
111
112pub(crate) fn run(
113 config: &Config,
114 stdout: &dyn ConsoleOut,
115 stderr: &dyn ConsoleOut,
116 testpaths: &TestPaths,
117 variant: &TestVariant,
118) {
119 match &*config.target {
120 "arm-linux-androideabi"
121 | "armv7-linux-androideabi"
122 | "thumbv7neon-linux-androideabi"
123 | "aarch64-linux-android" => {
124 if !config.adb_device_status {
125 panic!("android device not available");
126 }
127 }
128 _ => {}
129 }
130
131 if config.verbose {
132 write!(stdout, "\n\n");
134 }
135 debug!("running {}", testpaths.file);
136 let mut props = TestProps::from_file(&testpaths.file, variant.revision(), &config);
137
138 if props.incremental {
142 props.incremental_dir = Some(incremental_dir(&config, testpaths, variant));
143 }
144
145 let cx = TestCx { config: &config, stdout, stderr, props: &props, testpaths, variant };
146
147 if let Err(e) = create_dir_all(&cx.output_base_dir()) {
148 panic!("failed to create output base directory {}: {e}", cx.output_base_dir());
149 }
150
151 if props.incremental {
152 cx.init_incremental_test();
153 }
154
155 if config.mode == TestMode::Incremental {
156 assert!(!props.revisions.is_empty(), "Incremental tests require revisions.");
159 for revision in &props.revisions {
160 let mut revision_props = TestProps::from_file(&testpaths.file, Some(revision), &config);
161 revision_props.incremental_dir = props.incremental_dir.clone();
162 let rev_cx = TestCx {
163 config: &config,
164 stdout,
165 stderr,
166 props: &revision_props,
167 testpaths,
168 variant: &TestVariant {
169 revision: Some(revision.clone()),
170 debugger: variant.debugger,
171 },
172 };
173 rev_cx.run_revision();
174 }
175 } else {
176 cx.run_revision();
177 }
178
179 cx.create_stamp();
180}
181
182pub(crate) fn compute_stamp_hash(config: &Config, variant: &TestVariant) -> String {
183 let mut hash = DefaultHasher::new();
184 config.stage_id.hash(&mut hash);
185 config.run.hash(&mut hash);
186 config.edition.hash(&mut hash);
187
188 match variant.debugger {
189 Some(Debugger::Cdb) => {
190 config.cdb.hash(&mut hash);
191 }
192
193 Some(Debugger::Gdb) => {
194 config.gdb.hash(&mut hash);
195 env::var_os("PATH").hash(&mut hash);
196 env::var_os("PYTHONPATH").hash(&mut hash);
197 }
198
199 Some(Debugger::Lldb) => {
200 config.lldb.hash(&mut hash);
204 env::var_os("PATH").hash(&mut hash);
205 }
206
207 None => {}
208 }
209
210 if config.mode == TestMode::Ui {
211 config.force_pass_mode.hash(&mut hash);
212 }
213
214 format!("{:x}", hash.finish())
215}
216
217#[derive(Copy, Clone, Debug)]
218struct TestCx<'test> {
219 config: &'test Config,
220 stdout: &'test dyn ConsoleOut,
221 stderr: &'test dyn ConsoleOut,
222 props: &'test TestProps,
223 testpaths: &'test TestPaths,
224 variant: &'test TestVariant,
225}
226
227enum ReadFrom {
228 Path,
229 Stdin(String),
230}
231
232enum TestOutput {
233 Compile,
234 Run,
235}
236
237#[derive(Copy, Clone, PartialEq)]
239enum WillExecute {
240 Yes,
241 No,
242 Disabled,
243}
244
245#[derive(Copy, Clone)]
247enum Emit {
248 None,
249 Metadata,
250 LlvmIr,
251 Mir,
252 Asm,
253 LinkArgsAsm,
254}
255
256#[derive(Clone, Copy, Debug, PartialEq, Eq)]
258enum CompilerKind {
259 Rustc,
260 Rustdoc,
261}
262
263impl<'test> TestCx<'test> {
264 fn run_revision(&self) {
267 for _ in 0..self.config.iteration_count {
270 match self.config.mode {
271 TestMode::Pretty => self.run_pretty_test(),
272 TestMode::DebugInfo => self.run_debuginfo_test(),
273 TestMode::Codegen => self.run_codegen_test(),
274 TestMode::RustdocHtml => self.run_rustdoc_html_test(),
275 TestMode::RustdocJson => self.run_rustdoc_json_test(),
276 TestMode::CodegenUnits => self.run_codegen_units_test(),
277 TestMode::Incremental => self.run_incremental_test(),
278 TestMode::RunMake => self.run_rmake_test(),
279 TestMode::Ui => self.run_ui_test(),
280 TestMode::MirOpt => self.run_mir_opt_test(),
281 TestMode::Assembly => self.run_assembly_test(),
282 TestMode::RustdocJs => self.run_rustdoc_js_test(),
283 TestMode::CoverageMap => self.run_coverage_map_test(), TestMode::CoverageRun => self.run_coverage_run_test(), TestMode::Crashes => self.run_crash_test(),
286 }
287 }
288 }
289
290 fn effective_pass_fail_mode(&self) -> Option<PassFailMode> {
294 assert_eq!(self.config.mode, TestMode::Ui);
295 let declared = self.props.pass_fail_mode?;
297
298 if let Some(force_pass_mode) = self.config.force_pass_mode
301 && !self.props.no_pass_override
302 && declared.is_pass()
303 {
304 match force_pass_mode {
305 ForcePassMode::Check => Some(PassFailMode::CheckPass),
306 ForcePassMode::Build => Some(PassFailMode::BuildPass),
307 ForcePassMode::Run => Some(PassFailMode::RunPass),
308 }
309 } else {
310 Some(declared)
311 }
312 }
313
314 fn run_if_enabled(&self) -> WillExecute {
315 if self.config.run_enabled() { WillExecute::Yes } else { WillExecute::Disabled }
316 }
317
318 fn check_if_test_should_compile(&self, pass_fail: PassFailMode, proc_res: &ProcRes) {
319 assert_eq!(self.config.mode, TestMode::Ui);
320
321 let should_compile_successfully = match pass_fail {
322 PassFailMode::CheckFail | PassFailMode::BuildFail => false,
323
324 PassFailMode::CheckPass
325 | PassFailMode::BuildPass
326 | PassFailMode::RunFail
327 | PassFailMode::RunCrash
328 | PassFailMode::RunFailOrCrash
329 | PassFailMode::RunPass => true,
330 };
331
332 if should_compile_successfully {
333 if !proc_res.status.success() {
334 if pass_fail == PassFailMode::CheckPass
335 && self.effective_pass_fail_mode() == Some(PassFailMode::BuildFail)
336 {
337 self.fatal_proc_rec(
339 "`build-fail` test is required to pass check build, but check build failed",
340 proc_res,
341 );
342 } else {
343 self.fatal_proc_rec("test compilation failed although it shouldn't!", proc_res);
344 }
345 }
346 } else {
347 if proc_res.status.success() {
348 let err = &format!("{} test did not emit an error", self.config.mode);
349 let extra_note = Some(
350 "note: by default, ui tests are expected not to compile.\nhint: use check-pass, build-pass, or run-pass directive to change this behavior.",
351 );
352 self.fatal_proc_rec_general(err, extra_note, proc_res, || ());
353 }
354
355 if !self.props.dont_check_failure_status {
356 self.check_correct_failure_status(proc_res);
357 }
358 }
359 }
360
361 fn get_output(&self, proc_res: &ProcRes) -> String {
362 if self.props.check_stdout {
363 format!("{}{}", proc_res.stdout, proc_res.stderr)
364 } else {
365 proc_res.stderr.clone()
366 }
367 }
368
369 fn check_correct_failure_status(&self, proc_res: &ProcRes) {
370 let expected_status = Some(self.props.failure_status.unwrap_or(1));
371 let received_status = proc_res.status.code();
372
373 if expected_status != received_status {
374 self.fatal_proc_rec(
375 &format!(
376 "Error: expected failure status ({:?}) but received status {:?}.",
377 expected_status, received_status
378 ),
379 proc_res,
380 );
381 }
382 }
383
384 #[must_use = "caller should check whether the command succeeded"]
394 fn run_command_to_procres(&self, cmd: ArgFileCommand) -> ProcRes {
395 let (mut cmd, _arg_file) = cmd.build().unwrap();
396 let output = cmd
397 .output()
398 .unwrap_or_else(|e| self.fatal(&format!("failed to exec `{cmd:?}` because: {e}")));
399
400 let proc_res = ProcRes {
401 status: output.status,
402 stdout: String::from_utf8(output.stdout).unwrap(),
403 stderr: String::from_utf8(output.stderr).unwrap(),
404 truncated: Truncated::No,
405 cmdline: format!("{cmd:?}"),
406 };
407 self.dump_output(
408 self.config.verbose || !proc_res.status.success(),
409 &cmd.get_program().to_string_lossy(),
410 &proc_res.stdout,
411 &proc_res.stderr,
412 );
413
414 proc_res
415 }
416
417 fn print_source(&self, read_from: ReadFrom, pretty_type: &str) -> ProcRes {
418 let aux_dir = self.aux_output_dir_name();
419 let input: &str = match read_from {
420 ReadFrom::Stdin(_) => "-",
421 ReadFrom::Path => self.testpaths.file.as_str(),
422 };
423
424 let mut rustc = Command::new(&self.config.rustc_path);
425
426 self.build_all_auxiliary(&self.aux_output_dir(), &mut rustc);
427
428 rustc
429 .arg(input)
430 .args(&["-Z", &format!("unpretty={}", pretty_type)])
431 .arg("-Zunstable-options")
432 .args(&["--target", &self.config.target])
433 .arg("-L")
434 .arg(&aux_dir)
435 .arg("-A")
436 .arg("internal_features")
437 .args(&self.props.compile_flags)
438 .envs(self.props.rustc_env.clone());
439 self.maybe_add_external_args(&mut rustc, &self.config.target_rustcflags);
440
441 let src = match read_from {
442 ReadFrom::Stdin(src) => Some(src),
443 ReadFrom::Path => None,
444 };
445
446 self.compose_and_run(
447 rustc,
448 self.config.host_compile_lib_path.as_path(),
449 Some(aux_dir.as_path()),
450 src,
451 )
452 }
453
454 fn compare_source(&self, expected: &str, actual: &str) {
455 if expected != actual {
456 self.fatal(&format!(
457 "pretty-printed source does not match expected source\n\
458 expected:\n\
459 ------------------------------------------\n\
460 {}\n\
461 ------------------------------------------\n\
462 actual:\n\
463 ------------------------------------------\n\
464 {}\n\
465 ------------------------------------------\n\
466 diff:\n\
467 ------------------------------------------\n\
468 {}\n",
469 expected,
470 actual,
471 write_diff(expected, actual, 3),
472 ));
473 }
474 }
475
476 fn set_revision_flags(&self, cmd: &mut Command) {
477 let normalize_revision = |revision: &str| revision.to_lowercase().replace("-", "_");
480
481 if let Some(revision) = self.variant.revision() {
482 let normalized_revision = normalize_revision(revision);
483 let cfg_arg = ["--cfg", &normalized_revision];
484 let arg = format!("--cfg={normalized_revision}");
485 let contains_arg =
487 self.props.compile_flags.iter().any(|considered_arg| *considered_arg == arg);
488 let contains_cfg_arg = self.props.compile_flags.windows(2).any(|args| args == cfg_arg);
489 if contains_arg || contains_cfg_arg {
490 error!(
491 "redundant cfg argument `{normalized_revision}` is already created by the \
492 revision"
493 );
494 panic!("redundant cfg argument");
495 }
496 if self.config.builtin_cfg_names().contains(&normalized_revision) {
497 error!("revision `{normalized_revision}` collides with a built-in cfg");
498 panic!("revision collides with built-in cfg");
499 }
500 cmd.args(cfg_arg);
501 }
502
503 if !self.props.no_auto_check_cfg {
504 let mut check_cfg = String::with_capacity(25);
505
506 check_cfg.push_str("cfg(test,FALSE");
512 for revision in &self.props.revisions {
513 check_cfg.push(',');
514 check_cfg.push_str(&normalize_revision(revision));
515 }
516 check_cfg.push(')');
517
518 cmd.args(&["--check-cfg", &check_cfg]);
519 }
520 }
521
522 fn typecheck_source(&self, src: String) -> ProcRes {
523 let mut rustc = Command::new(&self.config.rustc_path);
524
525 let out_dir = self.output_base_name().with_extension("pretty-out");
526 remove_and_create_dir_all(&out_dir).unwrap_or_else(|e| {
527 panic!("failed to remove and recreate output directory `{out_dir}`: {e}")
528 });
529
530 let target = if self.props.force_host { &*self.config.host } else { &*self.config.target };
531
532 let aux_dir = self.aux_output_dir_name();
533
534 rustc
535 .arg("-")
536 .arg("-Zno-codegen")
537 .arg("-Zunstable-options")
538 .arg("--out-dir")
539 .arg(&out_dir)
540 .arg(&format!("--target={}", target))
541 .arg("-L")
542 .arg(&self.config.build_test_suite_root)
545 .arg("-L")
546 .arg(aux_dir)
547 .arg("-A")
548 .arg("internal_features");
549 self.set_revision_flags(&mut rustc);
550 self.maybe_add_external_args(&mut rustc, &self.config.target_rustcflags);
551 rustc.args(&self.props.compile_flags);
552
553 self.compose_and_run_compiler(rustc, Some(src))
554 }
555
556 fn maybe_add_external_args(&self, cmd: &mut Command, args: &Vec<String>) {
557 const OPT_FLAGS: &[&str] = &["-O", "-Copt-level=", "opt-level="];
562 const DEBUG_FLAGS: &[&str] = &["-g", "-Cdebuginfo=", "debuginfo="];
563
564 let have_opt_flag =
568 self.props.compile_flags.iter().any(|arg| OPT_FLAGS.iter().any(|f| arg.starts_with(f)));
569 let have_debug_flag = self
570 .props
571 .compile_flags
572 .iter()
573 .any(|arg| DEBUG_FLAGS.iter().any(|f| arg.starts_with(f)));
574
575 for arg in args {
576 if OPT_FLAGS.iter().any(|f| arg.starts_with(f)) && have_opt_flag {
577 continue;
578 }
579 if DEBUG_FLAGS.iter().any(|f| arg.starts_with(f)) && have_debug_flag {
580 continue;
581 }
582 cmd.arg(arg);
583 }
584 }
585
586 fn check_all_error_patterns(&self, output_to_check: &str, proc_res: &ProcRes) {
588 let mut missing_patterns: Vec<String> = Vec::new();
589 self.check_error_patterns(output_to_check, &mut missing_patterns);
590 self.check_regex_error_patterns(output_to_check, proc_res, &mut missing_patterns);
591
592 if missing_patterns.is_empty() {
593 return;
594 }
595
596 if missing_patterns.len() == 1 {
597 self.fatal_proc_rec(
598 &format!("error pattern '{}' not found!", missing_patterns[0]),
599 proc_res,
600 );
601 } else {
602 for pattern in missing_patterns {
603 writeln!(
604 self.stdout,
605 "\n{prefix}: error pattern '{pattern}' not found!",
606 prefix = self.error_prefix()
607 );
608 }
609 self.fatal_proc_rec("multiple error patterns not found", proc_res);
610 }
611 }
612
613 fn check_error_patterns(&self, output_to_check: &str, missing_patterns: &mut Vec<String>) {
614 debug!("check_error_patterns");
615 for pattern in &self.props.error_patterns {
616 if output_to_check.contains(pattern.trim()) {
617 debug!("found error pattern {}", pattern);
618 } else {
619 missing_patterns.push(pattern.to_string());
620 }
621 }
622 }
623
624 fn check_regex_error_patterns(
625 &self,
626 output_to_check: &str,
627 proc_res: &ProcRes,
628 missing_patterns: &mut Vec<String>,
629 ) {
630 debug!("check_regex_error_patterns");
631
632 for pattern in &self.props.regex_error_patterns {
633 let pattern = pattern.trim();
634 let re = match Regex::new(pattern) {
635 Ok(re) => re,
636 Err(err) => {
637 self.fatal_proc_rec(
638 &format!("invalid regex error pattern '{}': {:?}", pattern, err),
639 proc_res,
640 );
641 }
642 };
643 if re.is_match(output_to_check) {
644 debug!("found regex error pattern {}", pattern);
645 } else {
646 missing_patterns.push(pattern.to_string());
647 }
648 }
649 }
650
651 fn check_forbid_output(&self, output_to_check: &str, proc_res: &ProcRes) {
652 for pat in &self.props.forbid_output {
653 if output_to_check.contains(pat) {
654 self.fatal_proc_rec("forbidden pattern found in compiler output", proc_res);
655 }
656 }
657 }
658
659 fn check_expected_errors(&self, proc_res: &ProcRes) {
661 let expected_errors = load_errors(&self.testpaths.file, self.variant.revision());
662 debug!(
663 "check_expected_errors: expected_errors={:?} proc_res.status={:?}",
664 expected_errors, proc_res.status
665 );
666 if proc_res.status.success() && expected_errors.iter().any(|x| x.kind == ErrorKind::Error) {
667 self.fatal_proc_rec("process did not return an error status", proc_res);
668 }
669
670 if self.props.known_bug {
671 if !expected_errors.is_empty() {
672 self.fatal_proc_rec(
673 "`known_bug` tests should not have an expected error",
674 proc_res,
675 );
676 }
677 return;
678 }
679
680 let diagnostic_file_name = if self.props.remap_src_base {
683 let mut p = Utf8PathBuf::from(FAKE_SRC_BASE);
684 p.push(&self.testpaths.relative_dir);
685 p.push(self.testpaths.file.file_name().unwrap());
686 p.to_string()
687 } else {
688 self.testpaths.file.to_string()
689 };
690
691 let expected_kinds: HashSet<_> = [ErrorKind::Error, ErrorKind::Warning]
694 .into_iter()
695 .chain(expected_errors.iter().map(|e| e.kind))
696 .collect();
697
698 let actual_errors = json::parse_output(&diagnostic_file_name, &self.get_output(proc_res))
700 .into_iter()
701 .map(|e| Error { msg: self.normalize_output(&e.msg, &[]), ..e });
702
703 let mut unexpected = Vec::new();
704 let mut unimportant = Vec::new();
705 let mut found = vec![false; expected_errors.len()];
706 for actual_error in actual_errors {
707 for pattern in &self.props.error_patterns {
708 let pattern = pattern.trim();
709 if actual_error.msg.contains(pattern) {
710 let q = if actual_error.line_num.is_none() { "?" } else { "" };
711 self.fatal(&format!(
712 "error pattern '{pattern}' is found in structured \
713 diagnostics, use `//~{q} {} {pattern}` instead",
714 actual_error.kind,
715 ));
716 }
717 }
718
719 let opt_index =
720 expected_errors.iter().enumerate().position(|(index, expected_error)| {
721 !found[index]
722 && actual_error.line_num == expected_error.line_num
723 && actual_error.kind == expected_error.kind
724 && actual_error.msg.contains(&expected_error.msg)
725 });
726
727 match opt_index {
728 Some(index) => {
729 assert!(!found[index]);
731 found[index] = true;
732 }
733
734 None => {
735 if actual_error.require_annotation
736 && expected_kinds.contains(&actual_error.kind)
737 && !self.props.dont_require_annotations.contains(&actual_error.kind)
738 {
739 unexpected.push(actual_error);
740 } else {
741 unimportant.push(actual_error);
742 }
743 }
744 }
745 }
746
747 unexpected.sort_by_key(|e| (e.line_num, e.column_num));
748 unimportant.sort_by_key(|e| (e.line_num, e.column_num));
749
750 let mut not_found = Vec::new();
753 for (index, expected_error) in expected_errors.iter().enumerate() {
755 if !found[index] {
756 not_found.push(expected_error);
757 }
758 }
759
760 if !unexpected.is_empty() || !not_found.is_empty() {
761 let file_name = self
764 .testpaths
765 .file
766 .strip_prefix(self.config.src_root.as_str())
767 .unwrap_or(&self.testpaths.file)
768 .to_string()
769 .replace(r"\", "/");
770 let line_str = |e: &Error| {
771 let line_num = e.line_num.map_or("?".to_string(), |line_num| line_num.to_string());
772 let opt_col_num = match e.column_num {
774 Some(col_num) if line_num != "?" => format!(":{col_num}"),
775 _ => "".to_string(),
776 };
777 format!("{file_name}:{line_num}{opt_col_num}")
778 };
779 let print_error =
780 |e| writeln!(self.stdout, "{}: {}: {}", line_str(e), e.kind, e.msg.cyan());
781 let push_suggestion =
782 |suggestions: &mut Vec<_>, e: &Error, kind, line, msg, color, rank| {
783 let mut ret = String::new();
784 if kind {
785 ret += &format!("{} {}", "with different kind:".color(color), e.kind);
786 }
787 if line {
788 if !ret.is_empty() {
789 ret.push(' ');
790 }
791 ret += &format!("{} {}", "on different line:".color(color), line_str(e));
792 }
793 if msg {
794 if !ret.is_empty() {
795 ret.push(' ');
796 }
797 ret +=
798 &format!("{} {}", "with different message:".color(color), e.msg.cyan());
799 }
800 suggestions.push((ret, rank));
801 };
802 let show_suggestions = |mut suggestions: Vec<_>, prefix: &str, color| {
803 suggestions.sort_by_key(|(_, rank)| *rank);
805 if let Some(&(_, top_rank)) = suggestions.first() {
806 for (suggestion, rank) in suggestions {
807 if rank == top_rank {
808 writeln!(self.stdout, " {} {suggestion}", prefix.color(color));
809 }
810 }
811 }
812 };
813
814 if !unexpected.is_empty() {
821 writeln!(
822 self.stdout,
823 "\n{prefix}: {n} diagnostics reported in rustc output but not expected in test file",
824 prefix = self.error_prefix(),
825 n = unexpected.len(),
826 );
827 for error in &unexpected {
828 print_error(error);
829 let mut suggestions = Vec::new();
830 for candidate in ¬_found {
831 let kind_mismatch = candidate.kind != error.kind;
832 let mut push_red_suggestion = |line, msg, rank| {
833 push_suggestion(
834 &mut suggestions,
835 candidate,
836 kind_mismatch,
837 line,
838 msg,
839 Color::Red,
840 rank,
841 )
842 };
843 if error.msg.contains(&candidate.msg) {
844 push_red_suggestion(candidate.line_num != error.line_num, false, 0);
845 } else if candidate.line_num.is_some()
846 && candidate.line_num == error.line_num
847 {
848 push_red_suggestion(false, true, if kind_mismatch { 2 } else { 1 });
849 }
850 }
851
852 show_suggestions(suggestions, "expected", Color::Red);
853 }
854 }
855 if !not_found.is_empty() {
856 writeln!(
857 self.stdout,
858 "\n{prefix}: {n} diagnostics expected in test file but not reported in rustc output",
859 prefix = self.error_prefix(),
860 n = not_found.len(),
861 );
862
863 if let Some(human_format) = self.props.compile_flags.iter().find(|flag| {
866 flag.contains("error-format")
868 && (flag.contains("short") || flag.contains("human"))
869 }) {
870 let msg = format!(
871 "tests with compile flag `{}` should not have error annotations such as `//~ ERROR`",
872 human_format
873 ).color(Color::Red);
874 writeln!(self.stdout, "{}", msg);
875 }
876
877 for error in ¬_found {
878 print_error(error);
879 let mut suggestions = Vec::new();
880 for candidate in unexpected.iter().chain(&unimportant) {
881 let kind_mismatch = candidate.kind != error.kind;
882 let mut push_green_suggestion = |line, msg, rank| {
883 push_suggestion(
884 &mut suggestions,
885 candidate,
886 kind_mismatch,
887 line,
888 msg,
889 Color::Green,
890 rank,
891 )
892 };
893 if candidate.msg.contains(&error.msg) {
894 push_green_suggestion(candidate.line_num != error.line_num, false, 0);
895 } else if candidate.line_num.is_some()
896 && candidate.line_num == error.line_num
897 {
898 push_green_suggestion(false, true, if kind_mismatch { 2 } else { 1 });
899 }
900 }
901
902 show_suggestions(suggestions, "reported", Color::Green);
903 }
904 }
905 panic!(
906 "errors differ from expected\nstatus: {}\ncommand: {}\n",
907 proc_res.status, proc_res.cmdline
908 );
909 }
910 }
911
912 fn compile_test(&self, will_execute: WillExecute, emit: Emit) -> ProcRes {
913 self.compile_test_general(will_execute, emit, Vec::new())
914 }
915
916 fn compile_test_general(
917 &self,
918 will_execute: WillExecute,
919 emit: Emit,
920 passes: Vec<String>,
921 ) -> ProcRes {
922 let compiler_kind = self.compiler_kind_for_non_aux();
923
924 let output_file = match will_execute {
926 WillExecute::Yes => TargetLocation::ThisFile(self.make_exe_name()),
927 WillExecute::No | WillExecute::Disabled => {
928 TargetLocation::ThisDirectory(self.output_base_dir())
929 }
930 };
931
932 let allow_unused = match self.config.mode {
933 TestMode::Ui => {
934 if compiler_kind == CompilerKind::Rustc
940 && self.props.pass_fail_mode != Some(PassFailMode::RunPass)
946 {
947 AllowUnused::Yes
948 } else {
949 AllowUnused::No
950 }
951 }
952 TestMode::Incremental => AllowUnused::Yes,
953 _ => AllowUnused::No,
954 };
955
956 let rustc = self.make_compile_args(
957 compiler_kind,
958 &self.testpaths.file,
959 output_file,
960 emit,
961 allow_unused,
962 LinkToAux::Yes,
963 passes,
964 );
965
966 self.compose_and_run_compiler(rustc, None)
967 }
968
969 fn document(&self, root_out_dir: &Utf8Path, kind: DocKind) -> ProcRes {
972 self.document_inner(&self.testpaths.file, root_out_dir, kind)
973 }
974
975 fn document_inner(
979 &self,
980 file_to_doc: &Utf8Path,
981 root_out_dir: &Utf8Path,
982 kind: DocKind,
983 ) -> ProcRes {
984 if self.props.build_aux_docs {
985 assert_eq!(kind, DocKind::Html, "build-aux-docs only make sense for html output");
986
987 for rel_ab in &self.props.aux.builds {
988 let aux_path = self.resolve_aux_path(rel_ab);
989 let props_for_aux =
990 self.props.from_aux_file(&aux_path, self.variant.revision(), self.config);
991 let aux_cx = TestCx {
992 config: self.config,
993 stdout: self.stdout,
994 stderr: self.stderr,
995 props: &props_for_aux,
996 testpaths: self.testpaths,
997 variant: self.variant,
998 };
999 create_dir_all(aux_cx.output_base_dir()).unwrap();
1001 let auxres = aux_cx.document_inner(&aux_path, &root_out_dir, kind);
1002 if !auxres.status.success() {
1003 return auxres;
1004 }
1005 }
1006 }
1007
1008 let aux_dir = self.aux_output_dir_name();
1009
1010 let rustdoc_path = self.config.rustdoc_path.as_ref().expect("--rustdoc-path not passed");
1011
1012 let out_dir: Cow<'_, Utf8Path> = if self.props.unique_doc_out_dir {
1015 let file_name = file_to_doc.file_stem().expect("file name should not be empty");
1016 let out_dir = Utf8PathBuf::from_iter([
1017 root_out_dir,
1018 Utf8Path::new("docs"),
1019 Utf8Path::new(file_name),
1020 Utf8Path::new("doc"),
1021 ]);
1022 create_dir_all(&out_dir).unwrap();
1023 Cow::Owned(out_dir)
1024 } else {
1025 Cow::Borrowed(root_out_dir)
1026 };
1027
1028 let mut rustdoc = Command::new(rustdoc_path);
1029 let current_dir = self.output_base_dir();
1030 rustdoc.current_dir(current_dir);
1031 rustdoc
1032 .arg("-L")
1033 .arg(self.config.target_run_lib_path.as_path())
1034 .arg("-L")
1035 .arg(aux_dir)
1036 .arg("-o")
1037 .arg(out_dir.as_ref())
1038 .arg("--deny")
1039 .arg("warnings")
1040 .arg(file_to_doc)
1041 .arg("-A")
1042 .arg("internal_features")
1043 .arg("-Znext-solver=coherence")
1046 .args(&self.props.compile_flags)
1047 .args(&self.props.doc_flags);
1048
1049 match kind {
1050 DocKind::Html => {
1051 if self.props.use_rustdoc_cci_doc_meta_merge {
1052 rustdoc.arg("--write-doc-meta-dir").arg(out_dir.as_ref().join("doc.meta"));
1053 }
1054 }
1055 DocKind::Json => {
1056 rustdoc.arg("--output-format").arg("json");
1057 }
1058 }
1059
1060 if matches!(kind, DocKind::Json)
1062 || self.config.disable_minification
1063 || self.props.use_rustdoc_cci_doc_meta_merge
1064 {
1065 rustdoc.arg("-Zunstable-options");
1066 }
1067 if self.config.disable_minification {
1068 rustdoc.arg("--disable-minification");
1069 }
1070
1071 if let Some(ref linker) = self.config.target_linker {
1072 rustdoc.arg(format!("-Clinker={}", linker));
1073 }
1074
1075 let docres = self.compose_and_run_compiler(rustdoc, None);
1076 if !docres.status.success() {
1077 return docres;
1078 }
1079 if kind == DocKind::Html && self.props.use_rustdoc_cci_doc_meta_merge {
1080 let mut rustdoc_merge = Command::new(rustdoc_path);
1081 let current_dir = self.output_base_dir();
1082 rustdoc_merge.current_dir(current_dir);
1083 rustdoc_merge
1084 .arg("-o")
1085 .arg(out_dir.as_ref())
1086 .args(&self.props.compile_flags)
1087 .args(&self.props.doc_flags)
1088 .arg("--read-doc-meta-dir")
1089 .arg(out_dir.as_ref().join("doc.meta"))
1090 .arg("-Zunstable-options");
1091 if self.config.disable_minification {
1092 rustdoc_merge.arg("--disable-minification");
1093 }
1094 let docmerge = self.compose_and_run_compiler(rustdoc_merge, None);
1095 if !docmerge.status.success() {
1096 return docmerge;
1097 }
1098 }
1099 docres
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 =
1296 get_lib_name(&path_to_crate_name(aux_path), aux_type, self.config.wasm_proc_macros);
1297 if let Some(lib_name) = lib_name {
1298 let modifiers_and_name = match extern_modifiers {
1299 Some(modifiers) => format!("{modifiers}:{aux_name}"),
1300 None => aux_name.to_string(),
1301 };
1302 rustc.arg("--extern").arg(format!("{modifiers_and_name}={aux_dir}/{lib_name}"));
1303 }
1304 };
1305
1306 for AuxCrate { extern_modifiers, name, path } in &self.props.aux.crates {
1307 let aux_type = self.build_auxiliary(&path, &aux_dir, None);
1308 add_extern(rustc, extern_modifiers.as_deref(), name, path, aux_type);
1309 }
1310
1311 for proc_macro in &self.props.aux.proc_macros {
1312 self.build_auxiliary(&proc_macro.path, &aux_dir, Some(AuxType::ProcMacro));
1313 let crate_name = path_to_crate_name(&proc_macro.path);
1314 add_extern(
1315 rustc,
1316 proc_macro.extern_modifiers.as_deref(),
1317 &crate_name,
1318 &proc_macro.path,
1319 AuxType::ProcMacro,
1320 );
1321 }
1322
1323 if let Some(aux_file) = &self.props.aux.codegen_backend {
1326 let aux_type = self.build_auxiliary(aux_file, aux_dir, None);
1327 if let Some(lib_name) = get_lib_name(
1328 aux_file.trim_end_matches(".rs"),
1329 aux_type,
1330 self.config.wasm_proc_macros,
1331 ) {
1332 let lib_path = aux_dir.join(&lib_name);
1333 rustc.arg(format!("-Zcodegen-backend={}", lib_path));
1334 }
1335 }
1336 }
1337
1338 fn compose_and_run_compiler(&self, mut rustc: Command, input: Option<String>) -> ProcRes {
1341 if self.props.add_minicore {
1342 let minicore_path = self.build_minicore();
1343 rustc.arg("--extern");
1344 rustc.arg(&format!("minicore={}", minicore_path));
1345 }
1346
1347 let aux_dir = self.aux_output_dir();
1348 self.build_all_auxiliary(&aux_dir, &mut rustc);
1349
1350 rustc.envs(self.props.rustc_env.clone());
1351 self.props.unset_rustc_env.iter().fold(&mut rustc, Command::env_remove);
1352 self.compose_and_run(
1353 rustc,
1354 self.config.host_compile_lib_path.as_path(),
1355 Some(aux_dir.as_path()),
1356 input,
1357 )
1358 }
1359
1360 fn build_minicore(&self) -> Utf8PathBuf {
1363 let output_file_path = self.output_base_dir().join("libminicore.rlib");
1364 let mut rustc = self.make_compile_args(
1365 CompilerKind::Rustc,
1366 &self.config.minicore_path,
1367 TargetLocation::ThisFile(output_file_path.clone()),
1368 Emit::None,
1369 AllowUnused::Yes,
1370 LinkToAux::No,
1371 vec![],
1372 );
1373
1374 rustc.args(&["--crate-type", "rlib"]);
1375 rustc.arg("-Cpanic=abort");
1376 rustc.args(self.props.minicore_compile_flags.clone());
1377
1378 let res =
1379 self.compose_and_run(rustc, self.config.host_compile_lib_path.as_path(), None, None);
1380 if !res.status.success() {
1381 self.fatal_proc_rec(
1382 &format!("auxiliary build of {} failed to compile: ", self.config.minicore_path),
1383 &res,
1384 );
1385 }
1386
1387 output_file_path
1388 }
1389
1390 fn build_auxiliary(
1394 &self,
1395 source_path: &str,
1396 aux_dir: &Utf8Path,
1397 aux_type: Option<AuxType>,
1398 ) -> AuxType {
1399 let aux_path = self.resolve_aux_path(source_path);
1400 let mut aux_props =
1401 self.props.from_aux_file(&aux_path, self.variant.revision(), self.config);
1402 if aux_type == Some(AuxType::ProcMacro) {
1403 if self.config.wasm_proc_macros {
1404 aux_props.compile_flags.push("--target=wasm32-wasip2".to_owned());
1405 aux_props.compile_flags.push("-Clinker=wasm-component-ld".to_owned());
1413 aux_props.compile_flags.push(format!(
1414 "-Clink-arg=--wasm-ld-path={}",
1415 self.config
1416 .sysroot_base
1417 .join("lib/rustlib")
1418 .join(&self.config.host)
1419 .join("bin/gcc-ld/wasm-ld")
1420 ));
1421 } else {
1422 aux_props.force_host = true;
1423 }
1424 }
1425 let mut aux_dir = aux_dir.to_path_buf();
1426 if aux_type == Some(AuxType::Bin) {
1427 aux_dir.push("bin");
1431 }
1432 let aux_output = TargetLocation::ThisDirectory(aux_dir.clone());
1433 let aux_cx = TestCx {
1434 config: self.config,
1435 stdout: self.stdout,
1436 stderr: self.stderr,
1437 props: &aux_props,
1438 testpaths: self.testpaths,
1439 variant: self.variant,
1440 };
1441 create_dir_all(aux_cx.output_base_dir()).unwrap();
1443 let mut aux_rustc = aux_cx.make_compile_args(
1444 CompilerKind::Rustc,
1446 &aux_path,
1447 aux_output,
1448 Emit::None,
1449 AllowUnused::No,
1450 LinkToAux::No,
1451 Vec::new(),
1452 );
1453 aux_cx.build_all_auxiliary(&aux_dir, &mut aux_rustc);
1454
1455 aux_rustc.envs(aux_props.rustc_env.clone());
1456 for key in &aux_props.unset_rustc_env {
1457 aux_rustc.env_remove(key);
1458 }
1459
1460 let (aux_type, crate_type) = if aux_type == Some(AuxType::Bin) {
1461 (AuxType::Bin, Some("bin"))
1462 } else if aux_type == Some(AuxType::ProcMacro) {
1463 (AuxType::ProcMacro, Some("proc-macro"))
1464 } else if aux_type.is_some() {
1465 panic!("aux_type {aux_type:?} not expected");
1466 } else if aux_props.no_prefer_dynamic {
1467 (AuxType::Lib, None)
1468 } else if self.config.target.contains("emscripten")
1469 || (self.config.target.contains("musl")
1470 && !aux_props.force_host
1471 && !self.config.host.contains("musl"))
1472 || self.config.target.contains("wasm32")
1473 || self.config.target.contains("nvptx")
1474 || self.is_vxworks_pure_static()
1475 || self.config.target.contains("bpf")
1476 || !self.config.target_cfg().dynamic_linking
1477 || matches!(self.config.mode, TestMode::CoverageMap | TestMode::CoverageRun)
1478 {
1479 (AuxType::Lib, Some("lib"))
1493 } else {
1494 (AuxType::Dylib, Some("dylib"))
1495 };
1496
1497 if let Some(crate_type) = crate_type {
1498 aux_rustc.args(&["--crate-type", crate_type]);
1499 }
1500
1501 if aux_type == AuxType::ProcMacro {
1502 aux_rustc.args(&["--extern", "proc_macro"]);
1504 }
1505
1506 aux_rustc.arg("-L").arg(&aux_dir);
1507
1508 if aux_props.add_minicore {
1509 let minicore_path = self.build_minicore();
1510 aux_rustc.arg("--extern");
1511 aux_rustc.arg(&format!("minicore={}", minicore_path));
1512 }
1513
1514 let auxres = aux_cx.compose_and_run(
1515 aux_rustc,
1516 aux_cx.config.host_compile_lib_path.as_path(),
1517 Some(aux_dir.as_path()),
1518 None,
1519 );
1520 if !auxres.status.success() {
1521 self.fatal_proc_rec(
1522 &format!("auxiliary build of {aux_path} failed to compile: "),
1523 &auxres,
1524 );
1525 }
1526 aux_type
1527 }
1528
1529 fn read2_abbreviated(&self, child: Child) -> (Output, Truncated) {
1530 let mut filter_paths_from_len = Vec::new();
1531 let mut add_path = |path: &Utf8Path| {
1532 let path = path.to_string();
1533 let windows = path.replace("\\", "\\\\");
1534 if windows != path {
1535 filter_paths_from_len.push(windows);
1536 }
1537 filter_paths_from_len.push(path);
1538 };
1539
1540 add_path(&self.config.src_test_suite_root);
1546 add_path(&self.config.build_test_suite_root);
1547
1548 read2_abbreviated(child, &filter_paths_from_len).expect("failed to read output")
1549 }
1550
1551 fn compose_and_run(
1552 &self,
1553 mut command: Command,
1554 lib_path: &Utf8Path,
1555 aux_path: Option<&Utf8Path>,
1556 input: Option<String>,
1557 ) -> ProcRes {
1558 let cmdline = {
1559 let cmdline = self.make_cmdline(&command, lib_path);
1560 self.logv(format_args!("executing {cmdline}"));
1561 cmdline
1562 };
1563
1564 command.stdout(Stdio::piped()).stderr(Stdio::piped()).stdin(Stdio::piped());
1565
1566 add_dylib_path(&mut command, iter::once(lib_path).chain(aux_path));
1569
1570 let mut child = disable_error_reporting(|| command.spawn())
1571 .unwrap_or_else(|e| panic!("failed to exec `{command:?}`: {e:?}"));
1572 if let Some(input) = input {
1573 child.stdin.as_mut().unwrap().write_all(input.as_bytes()).unwrap();
1574 }
1575
1576 let (Output { status, stdout, stderr }, truncated) = self.read2_abbreviated(child);
1577
1578 let result = ProcRes {
1579 status,
1580 stdout: String::from_utf8_lossy(&stdout).into_owned(),
1581 stderr: String::from_utf8_lossy(&stderr).into_owned(),
1582 truncated,
1583 cmdline,
1584 };
1585
1586 self.dump_output(
1587 self.config.verbose || (!result.status.success() && self.config.mode != TestMode::Ui),
1588 &command.get_program().to_string_lossy(),
1589 &result.stdout,
1590 &result.stderr,
1591 );
1592
1593 result
1594 }
1595
1596 fn compiler_kind_for_non_aux(&self) -> CompilerKind {
1599 match self.config.suite {
1600 TestSuite::RustdocJs | TestSuite::RustdocJson | TestSuite::RustdocUi => {
1601 CompilerKind::Rustdoc
1602 }
1603
1604 TestSuite::AssemblyLlvm
1608 | TestSuite::BuildStd
1609 | TestSuite::CodegenLlvm
1610 | TestSuite::CodegenUnits
1611 | TestSuite::Coverage
1612 | TestSuite::CoverageRunRustdoc
1613 | TestSuite::Crashes
1614 | TestSuite::Debuginfo
1615 | TestSuite::Incremental
1616 | TestSuite::MirOpt
1617 | TestSuite::Pretty
1618 | TestSuite::RunMake
1619 | TestSuite::RunMakeCargo
1620 | TestSuite::RustdocGui
1621 | TestSuite::RustdocHtml
1622 | TestSuite::RustdocJsStd
1623 | TestSuite::Ui
1624 | TestSuite::UiFullDeps => CompilerKind::Rustc,
1625 }
1626 }
1627
1628 fn make_compile_args(
1629 &self,
1630 compiler_kind: CompilerKind,
1631 input_file: &Utf8Path,
1632 output_file: TargetLocation,
1633 emit: Emit,
1634 allow_unused: AllowUnused,
1635 link_to_aux: LinkToAux,
1636 passes: Vec<String>, ) -> Command {
1638 let mut compiler = match compiler_kind {
1641 CompilerKind::Rustc => Command::new(&self.config.rustc_path),
1642 CompilerKind::Rustdoc => {
1643 Command::new(&self.config.rustdoc_path.clone().expect("no rustdoc built yet"))
1644 }
1645 };
1646 compiler.arg(input_file);
1647
1648 if self.config.wasm_proc_macros {
1650 compiler.arg("-Zwasm-proc-macros");
1651 }
1652
1653 if compiler_kind == CompilerKind::Rustdoc
1656 && self.config.disable_minification
1657 && self.config.mode != TestMode::Ui
1658 {
1659 compiler.arg("-Zunstable-options").arg("--disable-minification");
1660 }
1661
1662 compiler.arg("-Zsimulate-remapped-rust-src-base=/rustc/FAKE_PREFIX");
1671 compiler.arg("-Ztranslate-remapped-path-to-local-path=no");
1672
1673 compiler.arg("-Z").arg(format!(
1678 "ignore-directory-in-diagnostics-source-blocks={}",
1679 home::cargo_home().expect("failed to find cargo home").to_str().unwrap()
1680 ));
1681 compiler.arg("-Z").arg(format!(
1683 "ignore-directory-in-diagnostics-source-blocks={}",
1684 self.config.src_root.join("vendor"),
1685 ));
1686
1687 if !self.props.compile_flags.iter().any(|flag| flag.starts_with("--sysroot"))
1691 && !self.config.host_rustcflags.iter().any(|flag| flag == "--sysroot")
1692 {
1693 compiler.arg("--sysroot").arg(&self.config.sysroot_base);
1695 }
1696
1697 if let Some(ref backend) = self.config.override_codegen_backend {
1699 compiler.arg(format!("-Zcodegen-backend={}", backend));
1700 }
1701
1702 let custom_target = self.props.compile_flags.iter().any(|x| x.starts_with("--target"));
1704
1705 if !custom_target {
1706 let target =
1707 if self.props.force_host { &*self.config.host } else { &*self.config.target };
1708
1709 compiler.arg(&format!("--target={}", target));
1710 if target.ends_with(".json") {
1711 compiler.arg("-Zunstable-options");
1714 }
1715 }
1716 self.set_revision_flags(&mut compiler);
1717
1718 if compiler_kind == CompilerKind::Rustc {
1719 if let Some(ref incremental_dir) = self.props.incremental_dir {
1720 compiler.args(&["-C", &format!("incremental={}", incremental_dir)]);
1721 compiler.args(&["-Z", "incremental-verify-ich"]);
1722 }
1723
1724 if self.config.mode == TestMode::CodegenUnits {
1725 compiler.args(&["-Z", "human_readable_cgu_names"]);
1726 }
1727
1728 if self.config.mode == TestMode::DebugInfo && cfg!(target_os = "windows") {
1729 compiler.args(&["-Z", r#"crate-attr=windows_subsystem="windows""#]);
1731 }
1732 }
1733
1734 if self.config.optimize_tests && compiler_kind == CompilerKind::Rustc {
1735 match self.config.mode {
1736 TestMode::Ui => {
1737 if self.effective_pass_fail_mode() == Some(PassFailMode::RunPass)
1744 && !self
1745 .props
1746 .compile_flags
1747 .iter()
1748 .any(|arg| arg == "-O" || arg.contains("opt-level"))
1749 {
1750 compiler.arg("-O");
1751 }
1752 }
1753 TestMode::DebugInfo => { }
1754 TestMode::CoverageMap | TestMode::CoverageRun => {
1755 }
1760 _ => {
1761 compiler.arg("-O");
1762 }
1763 }
1764 }
1765
1766 let set_mir_dump_dir = |rustc: &mut Command| {
1767 let mir_dump_dir = self.output_base_dir();
1768 let mut dir_opt = "-Zdump-mir-dir=".to_string();
1769 dir_opt.push_str(mir_dump_dir.as_str());
1770 debug!("dir_opt: {:?}", dir_opt);
1771 rustc.arg(dir_opt);
1772 };
1773
1774 match self.config.mode {
1775 TestMode::Incremental => {
1776 if self.props.error_patterns.is_empty()
1780 && self.props.regex_error_patterns.is_empty()
1781 {
1782 compiler.args(&["--error-format", "json"]);
1783 compiler.args(&["--json", "future-incompat"]);
1784 }
1785 compiler.arg("-Zui-testing");
1786 compiler.arg("-Zdeduplicate-diagnostics=no");
1787 }
1788 TestMode::Ui => {
1789 if !self.props.compile_flags.iter().any(|s| s.starts_with("--error-format")) {
1790 compiler.args(&["--error-format", "json"]);
1791 compiler.args(&["--json", "future-incompat"]);
1792 }
1793 compiler.arg("-Ccodegen-units=1");
1794 compiler.arg("-Zui-testing");
1796 compiler.arg("-Zdeduplicate-diagnostics=no");
1797 compiler.arg("-Zwrite-long-types-to-disk=no");
1798 compiler.arg("-Cstrip=debuginfo");
1800
1801 if self.config.parallel_frontend_enabled() {
1802 compiler.arg(&format!("-Zthreads={}", self.config.parallel_frontend_threads));
1807 }
1808 }
1809 TestMode::MirOpt => {
1810 let zdump_arg = if !passes.is_empty() {
1814 format!("-Zdump-mir={}", passes.join(" | "))
1815 } else {
1816 "-Zdump-mir=all".to_string()
1817 };
1818
1819 compiler.args(&[
1820 "-Copt-level=1",
1821 &zdump_arg,
1822 "-Zvalidate-mir",
1823 "-Zlint-mir",
1824 "-Zdump-mir-exclude-pass-number",
1825 "-Zmir-include-spans=false", "--crate-type=rlib",
1827 ]);
1828 if let Some(pass) = &self.props.mir_unit_test {
1829 compiler
1830 .args(&["-Zmir-opt-level=0", &format!("-Zmir-enable-passes=+{}", pass)]);
1831 } else {
1832 compiler.args(&[
1833 "-Zmir-opt-level=4",
1834 "-Zmir-enable-passes=+ReorderBasicBlocks,+ReorderLocals",
1835 ]);
1836 }
1837
1838 set_mir_dump_dir(&mut compiler);
1839 }
1840 TestMode::CoverageMap => {
1841 compiler.arg("-Cinstrument-coverage");
1842 compiler.arg("-Zno-profiler-runtime");
1845 compiler.arg("-Copt-level=2");
1849 }
1850 TestMode::CoverageRun => {
1851 compiler.arg("-Cinstrument-coverage");
1852 compiler.arg("-Copt-level=2");
1856 }
1857 TestMode::Assembly | TestMode::Codegen => {
1858 compiler.arg("-Cdebug-assertions=no");
1859 compiler.arg("-Zcodegen-source-order");
1863 }
1864 TestMode::Crashes => {
1865 set_mir_dump_dir(&mut compiler);
1866 }
1867 TestMode::CodegenUnits => {
1868 compiler.arg("-Zprint-mono-items");
1869 }
1870 TestMode::Pretty
1871 | TestMode::DebugInfo
1872 | TestMode::RustdocHtml
1873 | TestMode::RustdocJson
1874 | TestMode::RunMake
1875 | TestMode::RustdocJs => {
1876 }
1878 }
1879
1880 if self.props.remap_src_base {
1881 compiler.arg(format!(
1882 "--remap-path-prefix={}={}",
1883 self.config.src_test_suite_root, FAKE_SRC_BASE,
1884 ));
1885 }
1886
1887 if compiler_kind == CompilerKind::Rustc {
1888 match emit {
1889 Emit::None => {}
1890 Emit::Metadata => {
1891 compiler.args(&["--emit", "metadata"]);
1892 }
1893 Emit::LlvmIr => {
1894 compiler.args(&["--emit", "llvm-ir"]);
1895 }
1896 Emit::Mir => {
1897 compiler.args(&["--emit", "mir"]);
1898 }
1899 Emit::Asm => {
1900 compiler.args(&["--emit", "asm"]);
1901 }
1902 Emit::LinkArgsAsm => {
1903 compiler.args(&["-Clink-args=--emit=asm"]);
1904 }
1905 }
1906 }
1907
1908 if compiler_kind == CompilerKind::Rustc {
1909 if self.config.target == "wasm32-unknown-unknown" || self.is_vxworks_pure_static() {
1910 } else if !self.props.no_prefer_dynamic {
1912 compiler.args(&["-C", "prefer-dynamic"]);
1913 }
1914 }
1915
1916 match output_file {
1917 _ if self.props.compile_flags.iter().any(|flag| flag == "-o") => {}
1920 TargetLocation::ThisFile(path) => {
1921 compiler.arg("-o").arg(path);
1922 }
1923 TargetLocation::ThisDirectory(path) => match compiler_kind {
1924 CompilerKind::Rustdoc => {
1925 compiler.arg("-o").arg(path);
1927 }
1928 CompilerKind::Rustc => {
1929 compiler.arg("--out-dir").arg(path);
1930 }
1931 },
1932 }
1933
1934 compiler.args(["-Znext-solver=coherence"]);
1937
1938 match self.config.compare_mode {
1939 Some(CompareMode::Polonius) => {
1940 compiler.args(&["-Zpolonius=next"]);
1941 }
1942 Some(CompareMode::NextSolver) => {
1943 compiler.args(&["-Znext-solver"]);
1944 }
1945 Some(CompareMode::NextSolverCoherence) => {
1946 compiler.args(&["-Znext-solver=coherence"]);
1947 }
1948 Some(CompareMode::SplitDwarf) if self.config.target.contains("windows") => {
1949 compiler.args(&["-Csplit-debuginfo=unpacked", "-Zunstable-options"]);
1950 }
1951 Some(CompareMode::SplitDwarf) => {
1952 compiler.args(&["-Csplit-debuginfo=unpacked"]);
1953 }
1954 Some(CompareMode::SplitDwarfSingle) => {
1955 compiler.args(&["-Csplit-debuginfo=packed"]);
1956 }
1957 None => {}
1958 }
1959
1960 if let AllowUnused::Yes = allow_unused {
1964 compiler.args(&["-A", "unused", "-W", "unused_attributes"]);
1965 }
1966
1967 compiler.args(&["-A", "internal_features"]);
1969 compiler.args(&["-A", "incomplete_features"]);
1970
1971 compiler.args(&["-A", "unused_parens"]);
1975 compiler.args(&["-A", "unused_braces"]);
1976
1977 if self.props.force_host {
1978 self.maybe_add_external_args(&mut compiler, &self.config.host_rustcflags);
1979 if compiler_kind == CompilerKind::Rustc
1980 && let Some(ref linker) = self.config.host_linker
1981 {
1982 compiler.arg(format!("-Clinker={linker}"));
1983 }
1984 } else {
1985 self.maybe_add_external_args(&mut compiler, &self.config.target_rustcflags);
1986 if compiler_kind == CompilerKind::Rustc
1987 && let Some(ref linker) = self.config.target_linker
1988 {
1989 compiler.arg(format!("-Clinker={linker}"));
1990 }
1991 }
1992
1993 if self.config.host.contains("musl") || self.is_vxworks_pure_dynamic() {
1995 compiler.arg("-Ctarget-feature=-crt-static");
1996 }
1997
1998 if let LinkToAux::Yes = link_to_aux {
1999 if self.has_aux_dir() {
2002 compiler.arg("-L").arg(self.aux_output_dir_name());
2003 }
2004 }
2005
2006 if self.props.add_minicore {
2016 compiler.arg("-Cpanic=abort");
2017 compiler.arg("-Cforce-unwind-tables=yes");
2018 }
2019
2020 compiler.args(&self.props.compile_flags);
2021
2022 compiler
2023 }
2024
2025 fn make_exe_name(&self) -> Utf8PathBuf {
2026 let mut f = self.output_base_dir().join("a");
2031 if self.config.target.contains("emscripten") {
2033 f = f.with_extra_extension("js");
2034 } else if self.config.target.starts_with("wasm") {
2035 f = f.with_extra_extension("wasm");
2036 } else if self.config.target.contains("spirv") {
2037 f = f.with_extra_extension("spv");
2038 } else if !env::consts::EXE_SUFFIX.is_empty() {
2039 f = f.with_extra_extension(env::consts::EXE_SUFFIX);
2040 }
2041 f
2042 }
2043
2044 fn make_run_args(&self) -> ProcArgs {
2045 let mut args = self.split_maybe_args(&self.config.runner);
2048
2049 let exe_file = self.make_exe_name();
2050
2051 args.push(exe_file.into_os_string());
2052
2053 args.extend(self.props.run_flags.iter().map(OsString::from));
2055
2056 let prog = args.remove(0);
2057 ProcArgs { prog, args }
2058 }
2059
2060 fn split_maybe_args(&self, argstr: &Option<String>) -> Vec<OsString> {
2061 match *argstr {
2062 Some(ref s) => s
2063 .split(' ')
2064 .filter_map(|s| {
2065 if s.chars().all(|c| c.is_whitespace()) {
2066 None
2067 } else {
2068 Some(OsString::from(s))
2069 }
2070 })
2071 .collect(),
2072 None => Vec::new(),
2073 }
2074 }
2075
2076 fn make_cmdline(&self, command: &Command, libpath: &Utf8Path) -> String {
2077 use crate::util;
2078
2079 if cfg!(unix) {
2081 format!("{:?}", command)
2082 } else {
2083 fn lib_path_cmd_prefix(path: &str) -> String {
2086 format!("{}=\"{}\"", util::lib_path_env_var(), util::make_new_path(path))
2087 }
2088
2089 format!("{} {:?}", lib_path_cmd_prefix(libpath.as_str()), command)
2090 }
2091 }
2092
2093 fn dump_output(&self, print_output: bool, proc_name: &str, out: &str, err: &str) {
2094 let revision =
2095 if let Some(r) = self.variant.revision() { format!("{}.", r) } else { String::new() };
2096
2097 self.dump_output_file(out, &format!("{}out", revision));
2098 self.dump_output_file(err, &format!("{}err", revision));
2099
2100 if !print_output {
2101 return;
2102 }
2103
2104 let path = Utf8Path::new(proc_name);
2105 let proc_name = if path.file_stem().is_some_and(|p| p == "rmake") {
2106 String::from_iter(
2107 path.parent()
2108 .unwrap()
2109 .file_name()
2110 .into_iter()
2111 .chain(Some("/"))
2112 .chain(path.file_name()),
2113 )
2114 } else {
2115 path.file_name().unwrap().into()
2116 };
2117 writeln!(self.stdout, "------{proc_name} stdout------------------------------");
2118 writeln!(self.stdout, "{}", out);
2119 writeln!(self.stdout, "------{proc_name} stderr------------------------------");
2120 writeln!(self.stdout, "{}", err);
2121 writeln!(self.stdout, "------------------------------------------");
2122 }
2123
2124 fn dump_output_file(&self, out: &str, extension: &str) {
2125 let outfile = self.make_out_name(extension);
2126 fs::write(outfile.as_std_path(), out)
2127 .unwrap_or_else(|err| panic!("failed to write {outfile}: {err:?}"));
2128 }
2129
2130 fn make_out_name(&self, extension: &str) -> Utf8PathBuf {
2133 self.output_base_name().with_extension(extension)
2134 }
2135
2136 fn aux_output_dir_name(&self) -> Utf8PathBuf {
2139 self.output_base_dir()
2140 .join("auxiliary")
2141 .with_extra_extension(self.config.mode.aux_dir_disambiguator())
2142 }
2143
2144 fn aux_bin_output_dir_name(&self) -> Utf8PathBuf {
2147 self.aux_output_dir_name().join("bin")
2148 }
2149
2150 fn variant_with_safe_revision(&self) -> TestVariant {
2153 if self.config.mode == TestMode::Incremental {
2154 TestVariant { revision: None, debugger: self.variant.debugger }
2155 } else {
2156 self.variant.clone()
2157 }
2158 }
2159
2160 fn output_base_dir(&self) -> Utf8PathBuf {
2164 output_base_dir(self.config, self.testpaths, &self.variant_with_safe_revision())
2165 }
2166
2167 fn output_base_name(&self) -> Utf8PathBuf {
2171 output_base_name(self.config, self.testpaths, &self.variant_with_safe_revision())
2172 }
2173
2174 fn logv(&self, message: impl fmt::Display) {
2179 debug!("{message}");
2180 if self.config.verbose {
2181 writeln!(self.stdout, "{message}");
2183 }
2184 }
2185
2186 #[must_use]
2189 fn error_prefix(&self) -> String {
2190 match self.variant.revision() {
2191 Some(rev) => format!("error in revision `{rev}`"),
2192 None => format!("error"),
2193 }
2194 }
2195
2196 #[track_caller]
2197 fn fatal(&self, err: &str) -> ! {
2198 writeln!(self.stdout, "\n{prefix}: {err}", prefix = self.error_prefix());
2199 error!("fatal error, panic: {:?}", err);
2200 panic!("fatal error");
2201 }
2202
2203 fn fatal_proc_rec(&self, err: &str, proc_res: &ProcRes) -> ! {
2204 self.fatal_proc_rec_general(err, None, proc_res, || ());
2205 }
2206
2207 fn fatal_proc_rec_general(
2210 &self,
2211 err: &str,
2212 extra_note: Option<&str>,
2213 proc_res: &ProcRes,
2214 callback_before_unwind: impl FnOnce(),
2215 ) -> ! {
2216 writeln!(self.stdout, "\n{prefix}: {err}", prefix = self.error_prefix());
2217
2218 if let Some(note) = extra_note {
2220 writeln!(self.stdout, "{note}");
2221 }
2222
2223 writeln!(self.stdout, "{}", proc_res.format_info());
2225
2226 callback_before_unwind();
2228
2229 std::panic::resume_unwind(Box::new(()));
2232 }
2233
2234 fn compile_test_and_save_ir(&self) -> (ProcRes, Utf8PathBuf) {
2237 let output_path = self.output_base_name().with_extension("ll");
2238 let input_file = &self.testpaths.file;
2239 let rustc = self.make_compile_args(
2240 CompilerKind::Rustc,
2241 input_file,
2242 TargetLocation::ThisFile(output_path.clone()),
2243 Emit::LlvmIr,
2244 AllowUnused::No,
2245 LinkToAux::Yes,
2246 Vec::new(),
2247 );
2248
2249 let proc_res = self.compose_and_run_compiler(rustc, None);
2250 (proc_res, output_path)
2251 }
2252
2253 fn verify_with_filecheck(&self, output: &Utf8Path) -> ProcRes {
2254 let mut filecheck = Command::new(self.config.llvm_filecheck.as_ref().unwrap());
2255 filecheck.arg("--input-file").arg(output).arg(&self.testpaths.file);
2256
2257 filecheck.arg("--check-prefix=CHECK");
2259
2260 if let Some(rev) = self.variant.revision() {
2268 filecheck.arg("--check-prefix").arg(rev);
2269 }
2270
2271 filecheck.arg("--allow-unused-prefixes");
2275
2276 filecheck.args(&["--dump-input-context", "100"]);
2278
2279 filecheck.args(&self.props.filecheck_flags);
2281
2282 self.compose_and_run(filecheck, Utf8Path::new(""), None, None)
2284 }
2285
2286 fn charset() -> &'static str {
2287 if cfg!(target_os = "freebsd") { "ISO-8859-1" } else { "UTF-8" }
2289 }
2290
2291 fn get_lines(&self, path: &Utf8Path, mut other_files: Option<&mut Vec<String>>) -> Vec<usize> {
2292 let content = fs::read_to_string(path.as_std_path()).unwrap();
2293 let mut ignore = false;
2294 content
2295 .lines()
2296 .enumerate()
2297 .filter_map(|(line_nb, line)| {
2298 if (line.trim_start().starts_with("pub mod ")
2299 || line.trim_start().starts_with("mod "))
2300 && line.ends_with(';')
2301 {
2302 if let Some(ref mut other_files) = other_files {
2303 other_files.push(line.rsplit("mod ").next().unwrap().replace(';', ""));
2304 }
2305 None
2306 } else {
2307 let sline = line.rsplit("///").next().unwrap();
2308 let line = sline.trim_start();
2309 if line.starts_with("```") {
2310 if ignore {
2311 ignore = false;
2312 None
2313 } else {
2314 ignore = true;
2315 Some(line_nb + 1)
2316 }
2317 } else {
2318 None
2319 }
2320 }
2321 })
2322 .collect()
2323 }
2324
2325 fn check_rustdoc_test_option(&self, res: ProcRes) {
2330 let mut other_files = Vec::new();
2331 let mut files: HashMap<String, Vec<usize>> = HashMap::new();
2332 let normalized = fs::canonicalize(&self.testpaths.file).expect("failed to canonicalize");
2333 let normalized = normalized.to_str().unwrap().replace('\\', "/");
2334 files.insert(normalized, self.get_lines(&self.testpaths.file, Some(&mut other_files)));
2335 for other_file in other_files {
2336 let mut path = self.testpaths.file.clone();
2337 path.set_file_name(&format!("{}.rs", other_file));
2338 let path = path.canonicalize_utf8().expect("failed to canonicalize");
2339 let normalized = path.as_str().replace('\\', "/");
2340 files.insert(normalized, self.get_lines(&path, None));
2341 }
2342
2343 let mut tested = 0;
2344 for _ in res.stdout.split('\n').filter(|s| s.starts_with("test ")).inspect(|s| {
2345 if let Some((left, right)) = s.split_once(" - ") {
2346 let path = left.rsplit("test ").next().unwrap();
2347 let path = fs::canonicalize(&path).expect("failed to canonicalize");
2348 let path = path.to_str().unwrap().replace('\\', "/");
2349 if let Some(ref mut v) = files.get_mut(&path) {
2350 tested += 1;
2351 let mut iter = right.split("(line ");
2352 iter.next();
2353 let line = iter
2354 .next()
2355 .unwrap_or(")")
2356 .split(')')
2357 .next()
2358 .unwrap_or("0")
2359 .parse()
2360 .unwrap_or(0);
2361 if let Ok(pos) = v.binary_search(&line) {
2362 v.remove(pos);
2363 } else {
2364 self.fatal_proc_rec(
2365 &format!("Not found doc test: \"{}\" in \"{}\":{:?}", s, path, v),
2366 &res,
2367 );
2368 }
2369 }
2370 }
2371 }) {}
2372 if tested == 0 {
2373 self.fatal_proc_rec(&format!("No test has been found... {:?}", files), &res);
2374 } else {
2375 for (entry, v) in &files {
2376 if !v.is_empty() {
2377 self.fatal_proc_rec(
2378 &format!(
2379 "Not found test at line{} \"{}\":{:?}",
2380 if v.len() > 1 { "s" } else { "" },
2381 entry,
2382 v
2383 ),
2384 &res,
2385 );
2386 }
2387 }
2388 }
2389 }
2390
2391 fn force_color_svg(&self) -> bool {
2392 self.props.compile_flags.iter().any(|s| s.contains("--color=always"))
2393 }
2394
2395 fn lines_for_comparison(&self, output: &str) -> Vec<String> {
2399 if self.force_color_svg() {
2400 let strip_y = static_regex!(r#"y="\d+px""#);
2401 output
2402 .lines()
2403 .skip(1)
2405 .map(|line| strip_y.replace_all(line, r#"y="0px""#).into_owned())
2406 .collect()
2407 } else {
2408 output.lines().filter(|l| l.trim() != "|").map(str::to_owned).collect()
2409 }
2410 }
2411
2412 fn load_compare_outputs(
2413 &self,
2414 proc_res: &ProcRes,
2415 output_kind: TestOutput,
2416 explicit_format: bool,
2417 ) -> usize {
2418 let stderr_bits = format!("{}bit.stderr", self.config.get_pointer_width());
2419 let (stderr_kind, stdout_kind) = match output_kind {
2420 TestOutput::Compile => (
2421 if self.force_color_svg() {
2422 if self.config.target.contains("windows") {
2423 UI_WINDOWS_SVG
2426 } else {
2427 UI_SVG
2428 }
2429 } else if self.props.stderr_per_bitwidth {
2430 &stderr_bits
2431 } else {
2432 UI_STDERR
2433 },
2434 UI_STDOUT,
2435 ),
2436 TestOutput::Run => (UI_RUN_STDERR, UI_RUN_STDOUT),
2437 };
2438
2439 let expected_stderr = self.load_expected_output(stderr_kind);
2440 let expected_stdout = self.load_expected_output(stdout_kind);
2441
2442 let mut normalized_stdout =
2443 self.normalize_output(&proc_res.stdout, &self.props.normalize_stdout);
2444 match output_kind {
2445 TestOutput::Run if self.config.remote_test_client.is_some() => {
2446 normalized_stdout = static_regex!(
2451 "^uploaded \"\\$TEST_BUILD_DIR(/[[:alnum:]_\\-.]+)+\", waiting for result\n"
2452 )
2453 .replace(&normalized_stdout, "")
2454 .to_string();
2455 normalized_stdout = static_regex!("^died due to signal [0-9]+\n")
2458 .replace(&normalized_stdout, "")
2459 .to_string();
2460 }
2463 _ => {}
2464 };
2465
2466 let stderr;
2467 let normalized_stderr;
2468
2469 if self.force_color_svg() {
2470 let normalized = self.normalize_output(&proc_res.stderr, &self.props.normalize_stderr);
2471 stderr = anstyle_svg::Term::new().render_svg(&normalized);
2472 normalized_stderr = stderr.clone();
2473 } else {
2474 stderr = if explicit_format {
2475 proc_res.stderr.clone()
2476 } else {
2477 json::extract_rendered(&proc_res.stderr)
2478 };
2479 normalized_stderr = self.normalize_output(&stderr, &self.props.normalize_stderr);
2480 }
2481
2482 let mut errors = 0;
2483 match output_kind {
2484 TestOutput::Compile => {
2485 if !self.props.dont_check_compiler_stdout {
2486 if self
2487 .compare_output(
2488 stdout_kind,
2489 &normalized_stdout,
2490 &proc_res.stdout,
2491 &expected_stdout,
2492 )
2493 .should_error()
2494 {
2495 errors += 1;
2496 }
2497 }
2498 if !self.props.dont_check_compiler_stderr {
2499 if self
2500 .compare_output(stderr_kind, &normalized_stderr, &stderr, &expected_stderr)
2501 .should_error()
2502 {
2503 errors += 1;
2504 }
2505 }
2506 }
2507 TestOutput::Run => {
2508 if self
2509 .compare_output(
2510 stdout_kind,
2511 &normalized_stdout,
2512 &proc_res.stdout,
2513 &expected_stdout,
2514 )
2515 .should_error()
2516 {
2517 errors += 1;
2518 }
2519
2520 if self
2521 .compare_output(stderr_kind, &normalized_stderr, &stderr, &expected_stderr)
2522 .should_error()
2523 {
2524 errors += 1;
2525 }
2526 }
2527 }
2528 errors
2529 }
2530
2531 fn normalize_output(&self, output: &str, custom_rules: &[(String, String)]) -> String {
2532 let rflags = self.props.run_flags.join(" ");
2535 let cflags = self.props.compile_flags.join(" ");
2536 let json = rflags.contains("--format json")
2537 || rflags.contains("--format=json")
2538 || cflags.contains("--error-format json")
2539 || cflags.contains("--error-format pretty-json")
2540 || cflags.contains("--error-format=json")
2541 || cflags.contains("--error-format=pretty-json")
2542 || cflags.contains("--output-format json")
2543 || cflags.contains("--output-format=json");
2544
2545 let mut normalized = output.to_string();
2546
2547 let mut normalize_path = |from: &Utf8Path, to: &str| {
2548 let from = if json { &from.as_str().replace("\\", "\\\\") } else { from.as_str() };
2549
2550 normalized = normalized.replace(from, to);
2551 };
2552
2553 let parent_dir = self.testpaths.file.parent().unwrap();
2554 normalize_path(parent_dir, "$DIR");
2555
2556 if self.props.remap_src_base {
2557 let mut remapped_parent_dir = Utf8PathBuf::from(FAKE_SRC_BASE);
2558 if self.testpaths.relative_dir != Utf8Path::new("") {
2559 remapped_parent_dir.push(&self.testpaths.relative_dir);
2560 }
2561 normalize_path(&remapped_parent_dir, "$DIR");
2562 }
2563
2564 let base_dir = Utf8Path::new("/rustc/FAKE_PREFIX");
2565 normalize_path(&base_dir.join("library"), "$SRC_DIR");
2567 normalize_path(&base_dir.join("compiler"), "$COMPILER_DIR");
2571
2572 let rust_src_dir = &self.config.sysroot_base.join("lib/rustlib/src/rust");
2574 rust_src_dir.try_exists().expect(&*format!("{} should exists", rust_src_dir));
2575 let rust_src_dir =
2576 rust_src_dir.read_link_utf8().unwrap_or_else(|_| rust_src_dir.to_path_buf());
2577 normalize_path(&rust_src_dir.join("library"), "$SRC_DIR_REAL");
2578
2579 let rustc_src_dir = &self.config.sysroot_base.join("lib/rustlib/rustc-src/rust");
2581 rustc_src_dir.try_exists().expect(&*format!("{} should exists", rustc_src_dir));
2582 let rustc_src_dir = rustc_src_dir.read_link_utf8().unwrap_or(rustc_src_dir.to_path_buf());
2583 normalize_path(&rustc_src_dir.join("compiler"), "$COMPILER_DIR_REAL");
2584
2585 normalize_path(&self.output_base_dir(), "$TEST_BUILD_DIR");
2588 normalize_path(&self.output_base_dir().canonicalize_utf8().unwrap(), "$TEST_BUILD_DIR");
2595 normalize_path(&self.config.build_root, "$BUILD_DIR");
2597
2598 if json {
2599 normalized = normalized.replace("\\n", "\n");
2604 }
2605
2606 normalized = static_regex!("SRC_DIR(.+):\\d+:\\d+(: \\d+:\\d+)?")
2611 .replace_all(&normalized, "SRC_DIR$1:LL:COL")
2612 .into_owned();
2613
2614 normalized = Self::normalize_platform_differences(&normalized);
2615
2616 normalized =
2618 static_regex!(r"\$TEST_BUILD_DIR/(?P<filename>[^\.]+).long-type-(?P<hash>\d+).txt")
2619 .replace_all(&normalized, |caps: &Captures<'_>| {
2620 format!(
2621 "$TEST_BUILD_DIR/{filename}.long-type-$LONG_TYPE_HASH.txt",
2622 filename = &caps["filename"]
2623 )
2624 })
2625 .into_owned();
2626
2627 normalized = static_regex!(r"thread '(?P<name>.*?)' \((rtid )?\d+\) panicked")
2629 .replace_all(&normalized, "thread '$name' ($$TID) panicked")
2630 .into_owned();
2631
2632 normalized = normalized.replace("\t", "\\t"); normalized =
2639 static_regex!("\\s*//(\\[.*\\])?~.*").replace_all(&normalized, "").into_owned();
2640
2641 let v0_crate_hash_prefix_re = static_regex!(r"_R.*?Cs[0-9a-zA-Z]+_");
2644 let v0_crate_hash_re = static_regex!(r"Cs[0-9a-zA-Z]+_");
2645
2646 const V0_CRATE_HASH_PLACEHOLDER: &str = r"CsCRATE_HASH_";
2647 if v0_crate_hash_prefix_re.is_match(&normalized) {
2648 normalized =
2650 v0_crate_hash_re.replace_all(&normalized, V0_CRATE_HASH_PLACEHOLDER).into_owned();
2651 }
2652
2653 let v0_back_ref_prefix_re = static_regex!(r"\(_R.*?B[0-9a-zA-Z]_");
2654 let v0_back_ref_re = static_regex!(r"B[0-9a-zA-Z]_");
2655
2656 const V0_BACK_REF_PLACEHOLDER: &str = r"B<REF>_";
2657 if v0_back_ref_prefix_re.is_match(&normalized) {
2658 normalized =
2660 v0_back_ref_re.replace_all(&normalized, V0_BACK_REF_PLACEHOLDER).into_owned();
2661 }
2662
2663 {
2670 match self.config.mode {
2671 TestMode::Ui => {
2675 normalized = static_regex!(
2677 r"╾─*(a(lloc)?|A(LLOC)?)\d+(\+0x[0-9a-f]+)?(<imm>)?( ?\(\d+ ptr bytes\))?─*╼"
2678 )
2679 .replace_all(&normalized, |_: &Captures<'_>| "╾ALLOC$ID╼".to_string())
2680 .into_owned();
2681
2682 normalized = static_regex!(r"\b(alloc|ALLOC)\d+\b")
2684 .replace_all(&normalized, |_: &Captures<'_>| "ALLOC$ID".to_string())
2685 .into_owned();
2686 }
2687 _ => {
2690 let mut seen_allocs = indexmap::IndexSet::new();
2691 normalized = static_regex!(
2693 r"╾─*a(lloc)?([0-9]+)(\+0x[0-9a-f]+)?(<imm>)?( \([0-9]+ ptr bytes\))?─*╼"
2694 )
2695 .replace_all(&normalized, |caps: &Captures<'_>| {
2696 let index = caps.get(2).unwrap().as_str().to_string();
2698 let (index, _) = seen_allocs.insert_full(index);
2699 let offset = caps.get(3).map_or("", |c| c.as_str());
2700 let imm = caps.get(4).map_or("", |c| c.as_str());
2701 format!("╾ALLOC{index}{offset}{imm}╼")
2703 })
2704 .into_owned();
2705
2706 normalized = static_regex!(r"\balloc([0-9]+)\b")
2708 .replace_all(&normalized, |caps: &Captures<'_>| {
2709 let index = caps.get(1).unwrap().as_str().to_string();
2710 let (index, _) = seen_allocs.insert_full(index);
2711 format!("ALLOC{index}")
2712 })
2713 .into_owned();
2714 }
2715 }
2716 }
2717
2718 for rule in custom_rules {
2720 let re = Regex::new(&rule.0).expect("bad regex in custom normalization rule");
2721 normalized = re.replace_all(&normalized, &rule.1[..]).into_owned();
2722 }
2723 normalized
2724 }
2725
2726 fn normalize_platform_differences(output: &str) -> String {
2732 let output = output.replace(r"\\", r"\");
2733
2734 let re = static_regex!(
2739 r#"(?x)
2740 (?:
2741 # Match paths that don't include spaces.
2742 (?:\\[\pL\pN\.\-_']+)+\.\pL+
2743 |
2744 # If the path starts with a well-known root, then allow spaces and no file extension.
2745 \$(?:DIR|SRC_DIR|TEST_BUILD_DIR|BUILD_DIR|LIB_DIR)(?:\\[\pL\pN\.\-_'\ ]+)+
2746 )"#
2747 );
2748 re.replace_all(&output, |caps: &Captures<'_>| caps[0].replace(r"\", "/"))
2749 .replace("\r\n", "\n")
2750 }
2751
2752 fn expected_output_path(&self, kind: &str) -> Utf8PathBuf {
2753 let mut path = expected_output_path(
2754 &self.testpaths,
2755 self.variant.revision(),
2756 &self.config.compare_mode,
2757 kind,
2758 );
2759
2760 if !path.exists() {
2761 if let Some(CompareMode::Polonius) = self.config.compare_mode {
2762 path = expected_output_path(&self.testpaths, self.variant.revision(), &None, kind);
2763 }
2764 }
2765
2766 if !path.exists() {
2767 path = expected_output_path(&self.testpaths, self.variant.revision(), &None, kind);
2768 }
2769
2770 path
2771 }
2772
2773 fn load_expected_output(&self, kind: &str) -> String {
2774 let path = self.expected_output_path(kind);
2775 if path.exists() {
2776 match self.load_expected_output_from_path(&path) {
2777 Ok(x) => x,
2778 Err(x) => self.fatal(&x),
2779 }
2780 } else {
2781 String::new()
2782 }
2783 }
2784
2785 fn load_expected_output_from_path(&self, path: &Utf8Path) -> Result<String, String> {
2786 fs::read_to_string(path)
2787 .map_err(|err| format!("failed to load expected output from `{}`: {}", path, err))
2788 }
2789
2790 fn delete_file(&self, file: &Utf8Path) {
2792 if let Err(e) = fs::remove_file(file.as_std_path())
2793 && e.kind() != io::ErrorKind::NotFound
2794 {
2795 self.fatal(&format!("failed to delete `{}`: {}", file, e,));
2796 }
2797 }
2798
2799 fn compare_output(
2800 &self,
2801 stream: &str,
2802 actual: &str,
2803 actual_unnormalized: &str,
2804 expected: &str,
2805 ) -> CompareOutcome {
2806 let expected_path = expected_output_path(
2807 self.testpaths,
2808 self.variant.revision(),
2809 &self.config.compare_mode,
2810 stream,
2811 );
2812
2813 if self.config.bless && actual.is_empty() && expected_path.exists() {
2814 self.delete_file(&expected_path);
2815 }
2816
2817 let are_different = match (self.force_color_svg(), expected.find('\n'), actual.find('\n')) {
2818 (true, Some(nl_e), Some(nl_a)) => expected[nl_e..] != actual[nl_a..],
2821 _ => expected != actual,
2822 };
2823 if !are_different {
2824 return CompareOutcome::Same;
2825 }
2826
2827 let compare_output_by_lines_subset = self.config.runner.is_some();
2831
2832 let compare_output_by_lines = self.props.compare_output_by_lines;
2835
2836 let tmp;
2837 let (expected, actual): (&str, &str) = if compare_output_by_lines_subset {
2838 let actual_lines: HashSet<_> = actual.lines().collect();
2839 let expected_lines: Vec<_> = expected.lines().collect();
2840 let mut used = expected_lines.clone();
2841 used.retain(|line| actual_lines.contains(line));
2842
2843 if used.len() == expected_lines.len() && (expected.is_empty() == actual.is_empty()) {
2845 return CompareOutcome::Same;
2846 }
2847 if expected_lines.is_empty() {
2848 ("", actual)
2850 } else {
2851 tmp = (expected_lines.join("\n"), used.join("\n"));
2853 (&tmp.0, &tmp.1)
2854 }
2855 } else if compare_output_by_lines {
2856 let mut actual_lines = self.lines_for_comparison(actual);
2857 let mut expected_lines = self.lines_for_comparison(expected);
2858 actual_lines.sort_unstable();
2859 expected_lines.sort_unstable();
2860 if actual_lines == expected_lines {
2861 return CompareOutcome::Same;
2862 } else {
2863 (expected, actual)
2864 }
2865 } else {
2866 (expected, actual)
2867 };
2868
2869 let actual_path = self
2871 .output_base_name()
2872 .with_extra_extension(self.variant.revision().unwrap_or(""))
2873 .with_extra_extension(
2874 self.config.compare_mode.as_ref().map(|cm| cm.to_str()).unwrap_or(""),
2875 )
2876 .with_extra_extension(stream);
2877
2878 if let Err(err) = fs::write(&actual_path, &actual) {
2879 self.fatal(&format!("failed to write {stream} to `{actual_path}`: {err}",));
2880 }
2881 writeln!(self.stdout, "Saved the actual {stream} to `{actual_path}`");
2882
2883 if !self.config.bless {
2884 if expected.is_empty() {
2885 writeln!(self.stdout, "normalized {}:\n{}\n", stream, actual);
2886 } else {
2887 self.show_diff(
2888 stream,
2889 &expected_path,
2890 &actual_path,
2891 expected,
2892 actual,
2893 actual_unnormalized,
2894 compare_output_by_lines || compare_output_by_lines_subset,
2895 );
2896 }
2897 } else {
2898 if self.variant.revision().is_some() {
2901 let old =
2902 expected_output_path(self.testpaths, None, &self.config.compare_mode, stream);
2903 self.delete_file(&old);
2904 }
2905
2906 if !actual.is_empty() {
2907 if let Err(err) = fs::write(&expected_path, &actual) {
2908 self.fatal(&format!("failed to write {stream} to `{expected_path}`: {err}"));
2909 }
2910 writeln!(
2911 self.stdout,
2912 "Blessing the {stream} of `{test_name}` as `{expected_path}`",
2913 test_name = self.testpaths.file
2914 );
2915 }
2916 }
2917
2918 writeln!(self.stdout, "\nThe actual {stream} differed from the expected {stream}");
2919
2920 if self.config.bless { CompareOutcome::Blessed } else { CompareOutcome::Differed }
2921 }
2922
2923 fn show_diff(
2925 &self,
2926 stream: &str,
2927 expected_path: &Utf8Path,
2928 actual_path: &Utf8Path,
2929 expected: &str,
2930 actual: &str,
2931 actual_unnormalized: &str,
2932 show_diff_by_lines: bool,
2933 ) {
2934 writeln!(self.stderr, "diff of {stream}:\n");
2935 if let Some(diff_command) = self.config.diff_command.as_deref() {
2936 let mut args = diff_command.split_whitespace();
2937 let name = args.next().unwrap();
2938 match Command::new(name).args(args).args([expected_path, actual_path]).output() {
2939 Err(err) => {
2940 self.fatal(&format!(
2941 "failed to call custom diff command `{diff_command}`: {err}"
2942 ));
2943 }
2944 Ok(output) => {
2945 let output = String::from_utf8_lossy(&output.stdout);
2946 write!(self.stderr, "{output}");
2947 }
2948 }
2949 } else {
2950 write!(self.stderr, "{}", write_diff(expected, actual, 3));
2951 }
2952
2953 let diff_results = make_diff(actual, expected, 0);
2955
2956 let (mut mismatches_normalized, mut mismatch_line_nos) = (String::new(), vec![]);
2957 for hunk in diff_results {
2958 let mut line_no = hunk.line_number;
2959 for line in hunk.lines {
2960 if let DiffLine::Expected(normalized) = line {
2962 mismatches_normalized += &normalized;
2963 mismatches_normalized += "\n";
2964 mismatch_line_nos.push(line_no);
2965 line_no += 1;
2966 }
2967 }
2968 }
2969 let mut mismatches_unnormalized = String::new();
2970 let diff_normalized = make_diff(actual, actual_unnormalized, 0);
2971 for hunk in diff_normalized {
2972 if mismatch_line_nos.contains(&hunk.line_number) {
2973 for line in hunk.lines {
2974 if let DiffLine::Resulting(unnormalized) = line {
2975 mismatches_unnormalized += &unnormalized;
2976 mismatches_unnormalized += "\n";
2977 }
2978 }
2979 }
2980 }
2981
2982 let normalized_diff = make_diff(&mismatches_normalized, &mismatches_unnormalized, 0);
2983 if !normalized_diff.is_empty()
2985 && !mismatches_unnormalized.is_empty()
2986 && !mismatches_normalized.is_empty()
2987 {
2988 writeln!(
2989 self.stderr,
2990 "Note: some mismatched output was normalized before being compared"
2991 );
2992 write!(
2994 self.stderr,
2995 "{}",
2996 write_diff(&mismatches_unnormalized, &mismatches_normalized, 0)
2997 );
2998 }
2999
3000 if show_diff_by_lines {
3001 let expected_lines = self.lines_for_comparison(expected);
3002 let actual_lines = self.lines_for_comparison(actual);
3003 write!(self.stderr, "{}", diff_by_lines(&expected_lines, &actual_lines));
3004 }
3005 }
3006
3007 fn check_and_prune_duplicate_outputs(
3008 &self,
3009 proc_res: &ProcRes,
3010 modes: &[CompareMode],
3011 require_same_modes: &[CompareMode],
3012 ) {
3013 for kind in UI_EXTENSIONS {
3014 let canon_comparison_path =
3015 expected_output_path(&self.testpaths, self.variant.revision(), &None, kind);
3016
3017 let canon = match self.load_expected_output_from_path(&canon_comparison_path) {
3018 Ok(canon) => canon,
3019 _ => continue,
3020 };
3021 let bless = self.config.bless;
3022 let check_and_prune_duplicate_outputs = |mode: &CompareMode, require_same: bool| {
3023 let examined_path = expected_output_path(
3024 &self.testpaths,
3025 self.variant.revision(),
3026 &Some(mode.clone()),
3027 kind,
3028 );
3029
3030 let examined_content = match self.load_expected_output_from_path(&examined_path) {
3032 Ok(content) => content,
3033 _ => return,
3034 };
3035
3036 let is_duplicate = canon == examined_content;
3037
3038 match (bless, require_same, is_duplicate) {
3039 (true, _, true) => {
3041 self.delete_file(&examined_path);
3042 }
3043 (_, true, false) => {
3046 self.fatal_proc_rec(
3047 &format!("`{}` should not have different output from base test!", kind),
3048 proc_res,
3049 );
3050 }
3051 _ => {}
3052 }
3053 };
3054 for mode in modes {
3055 check_and_prune_duplicate_outputs(mode, false);
3056 }
3057 for mode in require_same_modes {
3058 check_and_prune_duplicate_outputs(mode, true);
3059 }
3060 }
3061 }
3062
3063 fn create_stamp(&self) {
3064 let stamp_file_path = stamp_file_path(&self.config, self.testpaths, self.variant);
3065 fs::write(&stamp_file_path, compute_stamp_hash(&self.config, self.variant)).unwrap();
3066 }
3067
3068 fn init_incremental_test(&self) {
3069 let incremental_dir = self.props.incremental_dir.as_ref().unwrap();
3076 if incremental_dir.exists() {
3077 let canonicalized = incremental_dir.canonicalize().unwrap();
3080 fs::remove_dir_all(canonicalized).unwrap();
3081 }
3082 fs::create_dir_all(&incremental_dir).unwrap();
3083
3084 if self.config.verbose {
3085 writeln!(self.stdout, "init_incremental_test: incremental_dir={incremental_dir}");
3086 }
3087 }
3088}
3089
3090struct ProcArgs {
3091 prog: OsString,
3092 args: Vec<OsString>,
3093}
3094
3095#[derive(Debug)]
3096pub(crate) struct ProcRes {
3097 status: ExitStatus,
3098 stdout: String,
3099 stderr: String,
3100 truncated: Truncated,
3101 cmdline: String,
3102}
3103
3104impl ProcRes {
3105 #[must_use]
3106 pub(crate) fn format_info(&self) -> String {
3107 fn render(name: &str, contents: &str) -> String {
3108 let contents = json::extract_rendered(contents);
3109 let contents = contents.trim_end();
3110 if contents.is_empty() {
3111 format!("{name}: none")
3112 } else {
3113 format!(
3114 "\
3115 --- {name} -------------------------------\n\
3116 {contents}\n\
3117 ------------------------------------------",
3118 )
3119 }
3120 }
3121
3122 format!(
3123 "status: {}\ncommand: {}\n{}\n{}\n",
3124 self.status,
3125 self.cmdline,
3126 render("stdout", &self.stdout),
3127 render("stderr", &self.stderr),
3128 )
3129 }
3130}
3131
3132#[derive(Debug)]
3133enum TargetLocation {
3134 ThisFile(Utf8PathBuf),
3135 ThisDirectory(Utf8PathBuf),
3136}
3137
3138enum AllowUnused {
3139 Yes,
3140 No,
3141}
3142
3143enum LinkToAux {
3144 Yes,
3145 No,
3146}
3147
3148#[derive(Debug, PartialEq)]
3149enum AuxType {
3150 Bin,
3151 Lib,
3152 Dylib,
3153 ProcMacro,
3154}
3155
3156#[derive(Copy, Clone, Debug, PartialEq, Eq)]
3159enum CompareOutcome {
3160 Same,
3162 Blessed,
3164 Differed,
3166}
3167
3168#[derive(Clone, Copy, Debug, PartialEq, Eq)]
3169enum DocKind {
3170 Html,
3171 Json,
3172}
3173
3174impl CompareOutcome {
3175 fn should_error(&self) -> bool {
3176 matches!(self, CompareOutcome::Differed)
3177 }
3178}