Skip to main content

compiletest/
common.rs

1use std::borrow::Cow;
2use std::collections::{BTreeSet, HashMap, HashSet};
3use std::iter;
4use std::process::Command;
5use std::str::FromStr;
6use std::sync::OnceLock;
7
8use build_helper::git::GitConfig;
9use camino::{Utf8Path, Utf8PathBuf};
10use semver::Version;
11
12use crate::edition::Edition;
13use crate::fatal;
14use crate::util::{Utf8PathBufExt, add_dylib_path, string_enum};
15
16string_enum! {
17    #[derive(Clone, Copy, PartialEq, Debug)]
18    pub(crate) enum TestMode {
19        Pretty => "pretty",
20        DebugInfo => "debuginfo",
21        Codegen => "codegen",
22        RustdocHtml => "rustdoc-html",
23        RustdocJson => "rustdoc-json",
24        CodegenUnits => "codegen-units",
25        Incremental => "incremental",
26        RunMake => "run-make",
27        Ui => "ui",
28        RustdocJs => "rustdoc-js",
29        MirOpt => "mir-opt",
30        Assembly => "assembly",
31        CoverageMap => "coverage-map",
32        CoverageRun => "coverage-run",
33        Crashes => "crashes",
34    }
35}
36
37impl TestMode {
38    pub(crate) fn aux_dir_disambiguator(self) -> &'static str {
39        // Pretty-printing tests could run concurrently, and if they do,
40        // they need to keep their output segregated.
41        match self {
42            TestMode::Pretty => ".pretty",
43            _ => "",
44        }
45    }
46
47    pub(crate) fn output_dir_disambiguator(self) -> &'static str {
48        // Coverage tests use the same test files for multiple test modes,
49        // so each mode should have a separate output directory.
50        match self {
51            TestMode::CoverageMap | TestMode::CoverageRun => self.to_str(),
52            _ => "",
53        }
54    }
55}
56
57// Note that coverage tests use the same test files for multiple test modes.
58string_enum! {
59    #[derive(Clone, Copy, PartialEq, Debug)]
60    pub(crate) enum TestSuite {
61        AssemblyLlvm => "assembly-llvm",
62        CodegenLlvm => "codegen-llvm",
63        CodegenUnits => "codegen-units",
64        Coverage => "coverage",
65        CoverageRunRustdoc => "coverage-run-rustdoc",
66        Crashes => "crashes",
67        Debuginfo => "debuginfo",
68        Incremental => "incremental",
69        MirOpt => "mir-opt",
70        Pretty => "pretty",
71        RunMake => "run-make",
72        RunMakeCargo => "run-make-cargo",
73        RustdocHtml => "rustdoc-html",
74        RustdocGui => "rustdoc-gui",
75        RustdocJs => "rustdoc-js",
76        RustdocJsStd=> "rustdoc-js-std",
77        RustdocJson => "rustdoc-json",
78        RustdocUi => "rustdoc-ui",
79        Ui => "ui",
80        UiFullDeps => "ui-fulldeps",
81        BuildStd => "build-std",
82    }
83}
84
85string_enum! {
86    #[derive(Clone, Copy, PartialEq, Eq, Debug)]
87    pub(crate) enum PassFailMode {
88        CheckFail => "check-fail",
89        CheckPass => "check-pass",
90        BuildFail => "build-fail",
91        BuildPass => "build-pass",
92        /// Running the program must make it exit with a regular failure exit code
93        /// in the range `1..=127`. If the program is terminated by e.g. a signal
94        /// the test will fail.
95        RunFail => "run-fail",
96        /// Running the program must result in a crash, e.g. by `SIGABRT` or
97        /// `SIGSEGV` on Unix or on Windows by having an appropriate NTSTATUS high
98        /// bit in the exit code.
99        RunCrash => "run-crash",
100        /// Running the program must either fail or crash. Useful for e.g. sanitizer
101        /// tests since some sanitizer implementations exit the process with code 1
102        /// to in the face of memory errors while others abort (crash) the process
103        /// in the face of memory errors.
104        RunFailOrCrash => "run-fail-or-crash",
105        RunPass => "run-pass",
106    }
107}
108
109impl PassFailMode {
110    pub(crate) fn is_pass(&self) -> bool {
111        match self {
112            PassFailMode::CheckPass | PassFailMode::BuildPass | PassFailMode::RunPass => true,
113
114            PassFailMode::CheckFail
115            | PassFailMode::BuildFail
116            | PassFailMode::RunFail
117            | PassFailMode::RunCrash
118            | PassFailMode::RunFailOrCrash => false,
119        }
120    }
121
122    pub(crate) fn is_check(&self) -> bool {
123        match self {
124            PassFailMode::CheckFail | PassFailMode::CheckPass => true,
125
126            PassFailMode::BuildFail
127            | PassFailMode::BuildPass
128            | PassFailMode::RunFail
129            | PassFailMode::RunCrash
130            | PassFailMode::RunFailOrCrash
131            | PassFailMode::RunPass => false,
132        }
133    }
134
135    pub(crate) fn is_run(&self) -> bool {
136        match self {
137            PassFailMode::CheckFail
138            | PassFailMode::CheckPass
139            | PassFailMode::BuildFail
140            | PassFailMode::BuildPass => false,
141
142            PassFailMode::RunFail
143            | PassFailMode::RunCrash
144            | PassFailMode::RunFailOrCrash
145            | PassFailMode::RunPass => true,
146        }
147    }
148}
149
150string_enum! {
151    #[derive(Clone, Copy, PartialEq, Debug, Hash)]
152    pub(crate) enum ForcePassMode {
153        Check => "check",
154        Build => "build",
155        Run => "run",
156    }
157}
158
159string_enum! {
160    #[derive(Clone, Copy, PartialEq, Debug, Hash)]
161    pub(crate) enum RunResult {
162        Pass => "run-pass",
163        Fail => "run-fail",
164        Crash => "run-crash",
165    }
166}
167
168string_enum! {
169    #[derive(Clone, Debug, PartialEq)]
170    pub(crate) enum CompareMode {
171        Polonius => "polonius",
172        NextSolver => "next-solver",
173        NextSolverCoherence => "next-solver-coherence",
174        SplitDwarf => "split-dwarf",
175        SplitDwarfSingle => "split-dwarf-single",
176    }
177}
178
179string_enum! {
180    #[derive(Clone, Copy, Debug, PartialEq)]
181    pub(crate) enum Debugger {
182        Cdb => "cdb",
183        Gdb => "gdb",
184        Lldb => "lldb",
185    }
186}
187
188#[derive(Clone, Copy, Debug, PartialEq, Default, serde::Deserialize)]
189#[serde(rename_all = "kebab-case")]
190pub(crate) enum PanicStrategy {
191    #[default]
192    Unwind,
193    Abort,
194}
195
196impl PanicStrategy {
197    pub(crate) fn for_miropt_test_tools(&self) -> miropt_test_tools::PanicStrategy {
198        match self {
199            PanicStrategy::Unwind => miropt_test_tools::PanicStrategy::Unwind,
200            PanicStrategy::Abort => miropt_test_tools::PanicStrategy::Abort,
201        }
202    }
203}
204
205#[derive(Clone, Debug, PartialEq, serde::Deserialize)]
206#[serde(rename_all = "kebab-case")]
207pub(crate) enum Sanitizer {
208    Address,
209    Cfi,
210    Dataflow,
211    Kcfi,
212    KernelAddress,
213    KernelHwaddress,
214    Leak,
215    Memory,
216    Memtag,
217    Safestack,
218    ShadowCallStack,
219    Thread,
220    Hwaddress,
221    Realtime,
222}
223
224#[derive(Clone, Copy, Debug, PartialEq)]
225pub(crate) enum CodegenBackend {
226    Cranelift,
227    Gcc,
228    Llvm,
229}
230
231impl FromStr for CodegenBackend {
232    type Err = &'static str;
233
234    fn from_str(value: &str) -> Result<Self, Self::Err> {
235        match value.to_lowercase().as_str() {
236            "cranelift" => Ok(Self::Cranelift),
237            "gcc" => Ok(Self::Gcc),
238            "llvm" => Ok(Self::Llvm),
239            _ => Err("unknown codegen backend"),
240        }
241    }
242}
243
244impl CodegenBackend {
245    pub(crate) fn as_str(self) -> &'static str {
246        match self {
247            Self::Cranelift => "cranelift",
248            Self::Gcc => "gcc",
249            Self::Llvm => "llvm",
250        }
251    }
252
253    pub(crate) fn is_llvm(self) -> bool {
254        matches!(self, Self::Llvm)
255    }
256}
257
258/// Configuration for `compiletest` *per invocation*.
259///
260/// In terms of `bootstrap`, this means that `./x test tests/ui tests/run-make` actually correspond
261/// to *two* separate invocations of `compiletest`.
262///
263/// FIXME: this `Config` struct should be broken up into smaller logically contained sub-config
264/// structs, it's too much of a "soup" of everything at the moment.
265///
266/// # Configuration sources
267///
268/// Configuration values for `compiletest` comes from several sources:
269///
270/// - CLI args passed from `bootstrap` while running the `compiletest` binary.
271/// - Env vars.
272/// - Discovery (e.g. trying to identify a suitable debugger based on filesystem discovery).
273/// - Cached output of running the `rustc` under test (e.g. output of `rustc` print requests).
274///
275/// FIXME: make sure we *clearly* account for sources of *all* config options.
276///
277/// FIXME: audit these options to make sure we are not hashing less than necessary for build stamp
278/// (for changed test detection).
279#[derive(Debug, Clone)]
280pub(crate) struct Config {
281    /// Some [`TestMode`]s support [snapshot testing], where a *reference snapshot* of outputs (of
282    /// `stdout`, `stderr`, or other form of artifacts) can be compared to the *actual output*.
283    ///
284    /// This option can be set to `true` to update the *reference snapshots* in-place, otherwise
285    /// `compiletest` will only try to compare.
286    ///
287    /// [snapshot testing]: https://jestjs.io/docs/snapshot-testing
288    pub(crate) bless: bool,
289
290    /// Attempt to stop as soon as possible after any test fails. We may still run a few more tests
291    /// before stopping when multiple test threads are used.
292    pub(crate) fail_fast: bool,
293
294    /// Path to libraries needed to run the *staged* `rustc`-under-test on the **host** platform.
295    ///
296    /// For example:
297    /// - `/home/ferris/rust/build/x86_64-unknown-linux-gnu/stage1/bin/lib`
298    pub(crate) host_compile_lib_path: Utf8PathBuf,
299
300    /// Path to libraries needed to run the compiled executable for the **target** platform. This
301    /// corresponds to the **target** sysroot libraries, including the **target** standard library.
302    ///
303    /// For example:
304    /// - `/home/ferris/rust/build/x86_64-unknown-linux-gnu/stage1/lib/rustlib/i686-unknown-linux-gnu/lib`
305    ///
306    /// FIXME: this is very under-documented in conjunction with the `remote-test-client` scheme and
307    /// `RUNNER` scheme to actually run the target executable under the target platform environment,
308    /// cf. [`Self::remote_test_client`] and [`Self::runner`].
309    pub(crate) target_run_lib_path: Utf8PathBuf,
310
311    /// Path to the `rustc`-under-test.
312    ///
313    /// For `ui-fulldeps` test suite specifically:
314    ///
315    /// - This is the **stage 0** compiler when testing `ui-fulldeps` under `--stage=1`.
316    /// - This is the **stage 2** compiler when testing `ui-fulldeps` under `--stage=2`.
317    ///
318    /// See [`Self::query_rustc_path`] for the `--stage=1` `ui-fulldeps` scenario where a separate
319    /// in-tree `rustc` is used for querying target information.
320    ///
321    /// For example:
322    /// - `/home/ferris/rust/build/x86_64-unknown-linux-gnu/stage1/bin/rustc`
323    ///
324    /// # Note on forced stage0
325    ///
326    /// It is possible for this `rustc` to be a stage 0 `rustc` if explicitly configured with the
327    /// bootstrap option `build.compiletest-allow-stage0=true` and specifying `--stage=0`.
328    pub(crate) rustc_path: Utf8PathBuf,
329
330    /// Path to a *staged* **host** platform cargo executable (unless stage 0 is forced). This
331    /// staged `cargo` is only used within `run-make` test recipes during recipe run time (and is
332    /// *not* used to compile the test recipes), and so must be staged as there may be differences
333    /// between e.g. beta `cargo` vs in-tree `cargo`.
334    ///
335    /// For example:
336    /// - `/home/ferris/rust/build/x86_64-unknown-linux-gnu/stage1-tools-bin/cargo`
337    ///
338    /// FIXME: maybe rename this to reflect that this is a *staged* host cargo.
339    pub(crate) cargo_path: Option<Utf8PathBuf>,
340
341    /// Path to the stage 0 `rustc` used to build `run-make` recipes. This must not be confused with
342    /// [`Self::rustc_path`].
343    ///
344    /// For example:
345    /// - `/home/ferris/rust/build/x86_64-unknown-linux-gnu/stage0/bin/rustc`
346    pub(crate) stage0_rustc_path: Option<Utf8PathBuf>,
347
348    /// Path to the stage 1 or higher `rustc` used to obtain target information via
349    /// `--print=all-target-specs-json` and similar queries.
350    ///
351    /// Normally this is unset, because [`Self::rustc_path`] can be used instead.
352    /// But when running "stage 1" ui-fulldeps tests, `rustc_path` is a stage 0
353    /// compiler, whereas target specs must be obtained from a stage 1+ compiler
354    /// (in case the JSON format has changed since the last bootstrap bump).
355    pub(crate) query_rustc_path: Option<Utf8PathBuf>,
356
357    /// Path to the `rustdoc`-under-test. Like [`Self::rustc_path`], this `rustdoc` is *staged*.
358    pub(crate) rustdoc_path: Option<Utf8PathBuf>,
359
360    /// Path to the `src/tools/coverage-dump/` bootstrap tool executable.
361    pub(crate) coverage_dump_path: Option<Utf8PathBuf>,
362
363    /// Path to the Python 3 executable to use for htmldocck and some run-make tests.
364    pub(crate) python: String,
365
366    /// Path to the `src/tools/jsondocck/` bootstrap tool executable.
367    pub(crate) jsondocck_path: Option<Utf8PathBuf>,
368
369    /// Path to the `src/tools/jsondoclint/` bootstrap tool executable.
370    pub(crate) jsondoclint_path: Option<Utf8PathBuf>,
371
372    /// Path to a host LLVM `FileCheck` executable.
373    pub(crate) llvm_filecheck: Option<Utf8PathBuf>,
374
375    /// Path to a host LLVM bintools directory.
376    ///
377    /// For example:
378    /// - `/home/ferris/rust/build/x86_64-unknown-linux-gnu/llvm/bin`
379    pub(crate) llvm_bin_dir: Option<Utf8PathBuf>,
380
381    /// The path to the **target** `clang` executable to run `clang`-based tests with. If `None`,
382    /// then these tests will be ignored.
383    pub(crate) run_clang_based_tests_with: Option<Utf8PathBuf>,
384
385    /// Path to the directory containing the sources. This corresponds to the root folder of a
386    /// `rust-lang/rust` checkout.
387    ///
388    /// For example:
389    /// - `/home/ferris/rust`
390    ///
391    /// FIXME: this name is confusing, because this is actually `$checkout_root`, **not** the
392    /// `$checkout_root/src/` folder.
393    pub(crate) src_root: Utf8PathBuf,
394
395    /// Absolute path to the test suite directory.
396    ///
397    /// For example:
398    /// - `/home/ferris/rust/tests/ui`
399    /// - `/home/ferris/rust/tests/coverage`
400    pub(crate) src_test_suite_root: Utf8PathBuf,
401
402    /// Path to the top-level build directory used by bootstrap.
403    ///
404    /// For example:
405    /// - `/home/ferris/rust/build`
406    pub(crate) build_root: Utf8PathBuf,
407
408    /// Path to the build directory used by the current test suite.
409    ///
410    /// For example:
411    /// - `/home/ferris/rust/build/x86_64-unknown-linux-gnu/test/ui`
412    /// - `/home/ferris/rust/build/x86_64-unknown-linux-gnu/test/coverage`
413    pub(crate) build_test_suite_root: Utf8PathBuf,
414
415    /// Path to the directory containing the sysroot of the `rustc`-under-test.
416    ///
417    /// For example:
418    /// - `/home/ferris/rust/build/x86_64-unknown-linux-gnu/stage1`
419    /// - `/home/ferris/rust/build/x86_64-unknown-linux-gnu/stage2`
420    ///
421    /// When stage 0 is forced, this will correspond to the sysroot *of* that specified stage 0
422    /// `rustc`.
423    ///
424    /// FIXME: this name is confusing, because it doesn't specify *which* compiler this sysroot
425    /// corresponds to. It's actually the `rustc`-under-test, and not the bootstrap `rustc`, unless
426    /// stage 0 is forced and no custom stage 0 `rustc` was otherwise specified (so that it
427    /// *happens* to run against the bootstrap `rustc`, but this non-custom bootstrap `rustc` case
428    /// is not really supported).
429    pub(crate) sysroot_base: Utf8PathBuf,
430
431    /// The number of the stage under test.
432    pub(crate) stage: u32,
433
434    /// The id of the stage under test (stage1-xxx, etc).
435    ///
436    /// FIXME: reconsider this string; this is hashed for test build stamp.
437    pub(crate) stage_id: String,
438
439    /// The [`TestMode`]. E.g. [`TestMode::Ui`]. Each test mode can correspond to one or more test
440    /// suites.
441    ///
442    /// FIXME: stop using stringly-typed test suites!
443    pub(crate) mode: TestMode,
444
445    /// The test suite.
446    ///
447    /// Example: `tests/ui/` is [`TestSuite::Ui`] test *suite*, which happens to also be of the
448    /// [`TestMode::Ui`] test *mode*.
449    ///
450    /// Note that the same test suite (e.g. `tests/coverage/`) may correspond to multiple test
451    /// modes, e.g. `tests/coverage/` can be run under both [`TestMode::CoverageRun`] and
452    /// [`TestMode::CoverageMap`].
453    pub(crate) suite: TestSuite,
454
455    /// When specified, **only** the specified [`Debugger`] will be used to run against the
456    /// `tests/debuginfo` test suite. When unspecified, `compiletest` will attempt to find all three
457    /// of {`lldb`, `cdb`, `gdb`} implicitly, and then try to run the `debuginfo` test suite against
458    /// all three debuggers.
459    ///
460    /// FIXME: this implicit behavior is really nasty, in that it makes it hard for the user to
461    /// control *which* debugger(s) are available and used to run the debuginfo test suite. We
462    /// should have `bootstrap` allow the user to *explicitly* configure the debuggers, and *not*
463    /// try to implicitly discover some random debugger from the user environment. This makes the
464    /// debuginfo test suite particularly hard to work with.
465    pub(crate) debugger: Option<Debugger>,
466
467    /// Run ignored tests *unconditionally*, overriding their ignore reason.
468    ///
469    /// FIXME: this is wired up through the test execution logic, but **not** accessible from
470    /// `bootstrap` directly; `compiletest` exposes this as `--ignored`. I.e. you'd have to use `./x
471    /// test $test_suite -- --ignored=true`.
472    pub(crate) run_ignored: bool,
473
474    /// Whether *staged* `rustc`-under-test was built with debug assertions.
475    ///
476    /// FIXME: make it clearer that this refers to the staged `rustc`-under-test, not stage 0
477    /// `rustc`.
478    pub(crate) with_rustc_debug_assertions: bool,
479
480    /// Whether *staged* `std` was built with debug assertions.
481    ///
482    /// FIXME: make it clearer that this refers to the staged `std`, not stage 0 `std`.
483    pub(crate) with_std_debug_assertions: bool,
484
485    /// Whether *staged* `std` was built with remapping of debuginfo.
486    ///
487    /// FIXME: make it clearer that this refers to the staged `std`, not stage 0 `std`.
488    pub(crate) with_std_remap_debuginfo: bool,
489
490    /// Only run tests that match these filters (using `libtest` "test name contains" filter logic).
491    ///
492    /// FIXME(#139660): the current hand-rolled test executor intentionally mimics the `libtest`
493    /// "test name contains" filter matching logic to preserve previous `libtest` executor behavior,
494    /// but this is often not intuitive. We should consider changing that behavior with an MCP to do
495    /// test path *prefix* matching which better corresponds to how `compiletest` `tests/` are
496    /// organized, and how users would intuitively expect the filtering logic to work like.
497    pub(crate) filters: Vec<String>,
498
499    /// Skip tests matching these substrings. The matching logic exactly corresponds to
500    /// [`Self::filters`] but inverted.
501    ///
502    /// FIXME(#139660): ditto on test matching behavior.
503    pub(crate) skip: Vec<String>,
504
505    /// Exactly match the filter, rather than a substring.
506    ///
507    /// FIXME(#139660): ditto on test matching behavior.
508    pub(crate) filter_exact: bool,
509
510    /// Force the pass mode of a check/build/run test to instead use this mode instead.
511    ///
512    /// FIXME: make it even more obvious (especially in PR CI where `--pass=check` is used) when a
513    /// pass mode is forced when the test fails, because it can be very non-obvious when e.g. an
514    /// error is emitted only when `//@ build-pass` but not `//@ check-pass`.
515    pub(crate) force_pass_mode: Option<ForcePassMode>,
516
517    /// Explicitly enable or disable running of the target test binary.
518    ///
519    /// FIXME: this scheme is a bit confusing, and at times questionable. Re-evaluate this run
520    /// scheme.
521    ///
522    /// FIXME: Currently `--run` is a tri-state, it can be `--run={auto,always,never}`, and when
523    /// `--run=auto` is specified, it's run if the platform doesn't end with `-fuchsia`. See
524    /// [`Config::run_enabled`].
525    pub(crate) run: Option<bool>,
526
527    /// A command line to prefix target program execution with, for running under valgrind for
528    /// example, i.e. `$runner target.exe [args..]`. Similar to `CARGO_*_RUNNER` configuration.
529    ///
530    /// Note: this is not to be confused with [`Self::remote_test_client`], which is a different
531    /// scheme.
532    ///
533    /// FIXME: the runner scheme is very under-documented.
534    pub(crate) runner: Option<String>,
535
536    /// Compiler flags to pass to the *staged* `rustc`-under-test when building for the **host**
537    /// platform.
538    pub(crate) host_rustcflags: Vec<String>,
539
540    /// Compiler flags to pass to the *staged* `rustc`-under-test when building for the **target**
541    /// platform.
542    pub(crate) target_rustcflags: Vec<String>,
543
544    /// Whether the *staged* `rustc`-under-test and the associated *staged* `std` has been built
545    /// with randomized struct layouts.
546    pub(crate) rust_randomized_layout: bool,
547
548    /// Whether tests should be optimized by default (`-O`). Individual test suites and test files
549    /// may override this setting.
550    ///
551    /// FIXME: this flag / config option is somewhat misleading. For instance, in ui tests, it's
552    /// *only* applied to the [`PassFailMode::RunPass`] test crate and not its auxiliaries.
553    pub(crate) optimize_tests: bool,
554
555    /// Target platform tuple.
556    pub(crate) target: String,
557
558    /// Host platform tuple.
559    pub(crate) host: String,
560
561    /// Path to / name of the Microsoft Console Debugger (CDB) executable.
562    ///
563    /// FIXME: this is an *opt-in* "override" option. When this isn't provided, we try to conjure a
564    /// cdb by looking at the user's program files on Windows... See `debuggers::find_cdb`.
565    pub(crate) cdb: Option<Utf8PathBuf>,
566
567    /// Version of CDB.
568    ///
569    /// FIXME: `cdb_version` is *derived* from cdb, but it's *not* technically a config!
570    ///
571    /// FIXME: audit cdb version gating.
572    pub(crate) cdb_version: Option<[u16; 4]>,
573
574    /// Path to / name of the GDB executable.
575    ///
576    /// FIXME: the fallback path when `gdb` isn't provided tries to find *a* `gdb` or `gdb.exe` from
577    /// `PATH`, which is... arguably questionable.
578    ///
579    /// FIXME: we are propagating a python from `PYTHONPATH`, not from an explicit config for gdb
580    /// debugger script.
581    pub(crate) gdb: Option<Utf8PathBuf>,
582
583    /// Version of GDB, encoded as ((major * 1000) + minor) * 1000 + patch
584    ///
585    /// FIXME: this gdb version gating scheme is possibly questionable -- gdb does not use semver,
586    /// only its major version is likely materially meaningful, cf.
587    /// <https://sourceware.org/gdb/wiki/Internals%20Versions>. Even the major version I'm not sure
588    /// is super meaningful. Maybe min gdb `major.minor` version gating is sufficient for the
589    /// purposes of debuginfo tests?
590    ///
591    /// FIXME: `gdb_version` is *derived* from gdb, but it's *not* technically a config!
592    pub(crate) gdb_version: Option<u32>,
593
594    /// Path to or name of the LLDB executable to use for debuginfo tests.
595    pub(crate) lldb: Option<Utf8PathBuf>,
596
597    /// Version of LLDB.
598    ///
599    /// FIXME: `lldb_version` is *derived* from lldb, but it's *not* technically a config!
600    pub(crate) lldb_version: Option<u32>,
601
602    /// Version of LLVM.
603    ///
604    /// FIXME: Audit the fallback derivation of
605    /// [`crate::directives::extract_llvm_version_from_binary`], that seems very questionable?
606    pub(crate) llvm_version: Option<Version>,
607
608    /// Is LLVM a system LLVM.
609    pub(crate) system_llvm: bool,
610
611    /// Path to the android tools.
612    ///
613    /// Note: this is only used for android gdb debugger script in the debuginfo test suite.
614    ///
615    /// FIXME: take a look at this; this is piggy-backing off of gdb code paths but only for
616    /// `arm-linux-androideabi` target.
617    pub(crate) android_cross_path: Option<Utf8PathBuf>,
618
619    /// Extra parameter to run adb on `arm-linux-androideabi`.
620    ///
621    /// FIXME: is this *only* `arm-linux-androideabi`, or is it also for other Tier 2/3 android
622    /// targets?
623    ///
624    /// FIXME: take a look at this; this is piggy-backing off of gdb code paths but only for
625    /// `arm-linux-androideabi` target.
626    pub(crate) adb_path: Option<Utf8PathBuf>,
627
628    /// Extra parameter to run test suite on `arm-linux-androideabi`.
629    ///
630    /// FIXME: is this *only* `arm-linux-androideabi`, or is it also for other Tier 2/3 android
631    /// targets?
632    ///
633    /// FIXME: take a look at this; this is piggy-backing off of gdb code paths but only for
634    /// `arm-linux-androideabi` target.
635    pub(crate) adb_test_dir: Option<Utf8PathBuf>,
636
637    /// Status whether android device available or not. When unavailable, this will cause tests to
638    /// panic when the test binary is attempted to be run.
639    ///
640    /// FIXME: take a look at this; this also influences adb in gdb code paths in a strange way.
641    pub(crate) adb_device_status: bool,
642
643    /// Verbose dump a lot of info.
644    ///
645    /// FIXME: this is *way* too coarse; the user can't select *which* info to verbosely dump.
646    pub(crate) verbose: bool,
647
648    /// Whether to enable verbose subprocess output for run-make tests.
649    /// Set to false to suppress output for passing tests (e.g. for cg_clif with --no-capture).
650    pub verbose_run_make_subprocess_output: bool,
651
652    /// Where to find the remote test client process, if we're using it.
653    ///
654    /// Note: this is *only* used for target platform executables created by `run-make` test
655    /// recipes.
656    ///
657    /// Note: this is not to be confused with [`Self::runner`], which is a different scheme.
658    ///
659    /// FIXME: the `remote_test_client` scheme is very under-documented.
660    pub(crate) remote_test_client: Option<Utf8PathBuf>,
661
662    /// [`CompareMode`] describing what file the actual ui output will be compared to.
663    ///
664    /// FIXME: currently, [`CompareMode`] is a mishmash of lot of things (different borrow-checker
665    /// model, different trait solver, different debugger, etc.).
666    pub(crate) compare_mode: Option<CompareMode>,
667
668    /// If true, this will generate a coverage file with UI test files that run `MachineApplicable`
669    /// diagnostics but are missing `run-rustfix` annotations. The generated coverage file is
670    /// created in `$test_suite_build_root/rustfix_missing_coverage.txt`
671    pub(crate) rustfix_coverage: bool,
672
673    /// Whether to run `enzyme` autodiff tests.
674    pub(crate) has_enzyme: bool,
675
676    /// Whether to run `offload` autodiff tests.
677    pub(crate) has_offload: bool,
678
679    /// The current Rust channel info.
680    ///
681    /// FIXME: treat this more carefully; "stable", "beta" and "nightly" are definitely valid, but
682    /// channel might also be "dev" or such, which should be treated as "nightly".
683    pub(crate) channel: String,
684
685    /// Whether adding git commit information such as the commit hash has been enabled for building.
686    ///
687    /// FIXME: `compiletest` cannot trust `bootstrap` for this information, because `bootstrap` can
688    /// have bugs and had bugs on that logic. We need to figure out how to obtain this e.g. directly
689    /// from CI or via git locally.
690    pub(crate) git_hash: bool,
691
692    /// The default Rust edition.
693    pub(crate) edition: Option<Edition>,
694
695    // Configuration for various run-make tests frobbing things like C compilers or querying about
696    // various LLVM component information.
697    //
698    // FIXME: this really should be better packaged together.
699    // FIXME: these need better docs, e.g. for *host*, or for *target*?
700    pub(crate) cc: String,
701    pub(crate) cxx: String,
702    pub(crate) cflags: String,
703    pub(crate) cxxflags: String,
704    pub(crate) ar: String,
705    pub(crate) target_linker: Option<String>,
706    pub(crate) host_linker: Option<String>,
707    pub(crate) llvm_components: String,
708
709    /// Path to a NodeJS executable. Used for JS doctests, emscripten and WASM tests.
710    pub(crate) nodejs: Option<Utf8PathBuf>,
711
712    /// Whether to rerun tests even if the inputs are unchanged.
713    pub(crate) force_rerun: bool,
714
715    /// Only rerun the tests that result has been modified according to `git status`.
716    ///
717    /// FIXME: this is undocumented.
718    ///
719    /// FIXME: how does this interact with [`Self::force_rerun`]?
720    pub(crate) only_modified: bool,
721
722    // FIXME: these are really not "config"s, but rather are information derived from
723    // `rustc`-under-test. This poses an interesting conundrum: if we're testing the
724    // `rustc`-under-test, can we trust its print request outputs and target cfgs? In theory, this
725    // itself can break or be unreliable -- ideally, we'd be sharing these kind of information not
726    // through `rustc`-under-test's execution output. In practice, however, print requests are very
727    // unlikely to completely break (we also have snapshot ui tests for them). Furthermore, even if
728    // we share them via some kind of static config, that static config can still be wrong! Who
729    // tests the tester? Therefore, we make a pragmatic compromise here, and use information derived
730    // from print requests produced by the `rustc`-under-test.
731    //
732    // FIXME: move them out from `Config`, because they are *not* configs.
733    pub(crate) target_cfgs: OnceLock<TargetCfgs>,
734    pub(crate) builtin_cfg_names: OnceLock<HashSet<String>>,
735    pub(crate) supported_crate_types: OnceLock<HashSet<String>>,
736
737    /// Should we capture console output that would be printed by test runners via their `stdout`
738    /// and `stderr` trait objects, or via the custom panic hook.
739    ///
740    /// The default is `true`. This can be disabled via the compiletest cli flag `--no-capture`
741    /// (which mirrors the libtest `--no-capture` flag).
742    pub(crate) capture: bool,
743
744    /// Needed both to construct [`build_helper::git::GitConfig`].
745    pub(crate) nightly_branch: String,
746    pub(crate) git_merge_commit_email: String,
747
748    /// True if the profiler runtime is enabled for this target. Used by the
749    /// `needs-profiler-runtime` directive in test files.
750    pub(crate) profiler_runtime: bool,
751
752    /// Command for visual diff display, e.g. `diff-tool --color=always`.
753    pub(crate) diff_command: Option<String>,
754
755    /// Path to minicore aux library (`tests/auxiliary/minicore.rs`), used for `no_core` tests that
756    /// need `core` stubs in cross-compilation scenarios that do not otherwise want/need to
757    /// `-Zbuild-std`. Used in e.g. ABI tests.
758    pub(crate) minicore_path: Utf8PathBuf,
759
760    /// Current codegen backend used.
761    pub(crate) default_codegen_backend: CodegenBackend,
762    /// Name/path of the backend to use instead of `default_codegen_backend`.
763    pub(crate) override_codegen_backend: Option<String>,
764    /// Whether to ignore `//@ ignore-backends`.
765    pub(crate) bypass_ignore_backends: bool,
766
767    /// Number of parallel jobs configured for the build.
768    ///
769    /// This is forwarded from bootstrap's `jobs` configuration.
770    pub(crate) jobs: u32,
771
772    /// Number of parallel threads to use for the frontend when building test artifacts.
773    pub(crate) parallel_frontend_threads: u32,
774    /// Number of times to execute each test.
775    pub(crate) iteration_count: u32,
776}
777
778impl Config {
779    pub(crate) const DEFAULT_PARALLEL_FRONTEND_THREADS: u32 = 1;
780    pub(crate) const DEFAULT_ITERATION_COUNT: u32 = 1;
781
782    /// FIXME: this run scheme is... confusing.
783    pub(crate) fn run_enabled(&self) -> bool {
784        self.run.unwrap_or_else(|| {
785            // Auto-detect whether to run based on the platform.
786            !self.target.ends_with("-fuchsia")
787        })
788    }
789
790    pub(crate) fn target_cfgs(&self) -> &TargetCfgs {
791        self.target_cfgs.get_or_init(|| TargetCfgs::new(self))
792    }
793
794    pub(crate) fn target_cfg(&self) -> &TargetCfg {
795        &self.target_cfgs().current
796    }
797
798    pub(crate) fn matches_arch(&self, arch: &str) -> bool {
799        self.target_cfg().arch == arch
800            || {
801                // Matching all the thumb variants as one can be convenient.
802                // (thumbv6m, thumbv7em, thumbv7m, etc.)
803                arch == "thumb" && self.target.starts_with("thumb")
804            }
805            || (arch == "i586" && self.target.starts_with("i586-"))
806    }
807
808    pub(crate) fn matches_os(&self, os: &str) -> bool {
809        self.target_cfg().os == os
810    }
811
812    pub(crate) fn matches_env(&self, env: &str) -> bool {
813        self.target_cfg().env == env
814    }
815
816    pub(crate) fn matches_abi(&self, abi: &str) -> bool {
817        self.target_cfg().abi == abi
818    }
819
820    #[cfg_attr(not(test), expect(dead_code, reason = "only used by tests for `ignore-{family}`"))]
821    pub(crate) fn matches_family(&self, family: &str) -> bool {
822        self.target_cfg().families.iter().any(|f| f == family)
823    }
824
825    pub(crate) fn is_big_endian(&self) -> bool {
826        self.target_cfg().endian == Endian::Big
827    }
828
829    pub(crate) fn get_pointer_width(&self) -> u32 {
830        *&self.target_cfg().pointer_width
831    }
832
833    pub(crate) fn can_unwind(&self) -> bool {
834        self.target_cfg().panic == PanicStrategy::Unwind
835    }
836
837    /// Get the list of builtin, 'well known' cfg names
838    pub(crate) fn builtin_cfg_names(&self) -> &HashSet<String> {
839        self.builtin_cfg_names.get_or_init(|| builtin_cfg_names(self))
840    }
841
842    /// Get the list of crate types that the target platform supports.
843    pub(crate) fn supported_crate_types(&self) -> &HashSet<String> {
844        self.supported_crate_types.get_or_init(|| supported_crate_types(self))
845    }
846
847    pub(crate) fn has_threads(&self) -> bool {
848        // Wasm targets don't have threads unless `-threads` is in the target
849        // name, such as `wasm32-wasip1-threads`.
850        if self.target.starts_with("wasm") {
851            return self.target.contains("threads");
852        }
853        true
854    }
855
856    pub(crate) fn has_asm_support(&self) -> bool {
857        // This should match the stable list in `LoweringContext::lower_inline_asm`.
858        static ASM_SUPPORTED_ARCHS: &[&str] = &[
859            "x86",
860            "x86_64",
861            "arm",
862            "aarch64",
863            "arm64ec",
864            "riscv32",
865            "riscv64",
866            "loongarch32",
867            "loongarch64",
868            "s390x",
869            // These targets require an additional asm_experimental_arch feature.
870            // "nvptx64", "hexagon", "mips", "mips64", "spirv", "wasm32",
871        ];
872        ASM_SUPPORTED_ARCHS.contains(&self.target_cfg().arch.as_str())
873    }
874
875    pub(crate) fn git_config(&self) -> GitConfig<'_> {
876        GitConfig {
877            nightly_branch: &self.nightly_branch,
878            git_merge_commit_email: &self.git_merge_commit_email,
879        }
880    }
881
882    pub(crate) fn has_subprocess_support(&self) -> bool {
883        // FIXME(#135928): compiletest is always a **host** tool. Building and running an
884        // capability detection executable against the **target** is not trivial. The short term
885        // solution here is to hard-code some targets to allow/deny, unfortunately.
886
887        let unsupported_target = self.target_cfg().env == "sgx"
888            || matches!(self.target_cfg().arch.as_str(), "wasm32" | "wasm64")
889            || self.target_cfg().os == "emscripten";
890        !unsupported_target
891    }
892
893    /// Whether the parallel frontend is enabled,
894    /// which is the case when `parallel_frontend_threads` is not set to `1`.
895    ///
896    /// - `0` means auto-detect: use the number of available hardware threads on the host.
897    ///   But we treat it as the parallel frontend being enabled in this case.
898    /// - `1` means single-threaded (parallel frontend disabled).
899    /// - `>1` means an explicitly configured thread count.
900    pub(crate) fn parallel_frontend_enabled(&self) -> bool {
901        self.parallel_frontend_threads != 1
902    }
903}
904
905/// Known widths of `target_has_atomic`.
906pub(crate) const KNOWN_TARGET_HAS_ATOMIC_WIDTHS: &[&str] = &["8", "16", "32", "64", "128", "ptr"];
907
908#[derive(Debug, Clone)]
909pub(crate) struct TargetCfgs {
910    pub(crate) current: TargetCfg,
911    pub(crate) all_targets: HashSet<String>,
912    pub(crate) all_archs: HashSet<String>,
913    pub(crate) all_oses: HashSet<String>,
914    pub(crate) all_oses_and_envs: HashSet<String>,
915    pub(crate) all_envs: HashSet<String>,
916    pub(crate) all_abis: HashSet<String>,
917    pub(crate) all_families: HashSet<String>,
918    pub(crate) all_pointer_widths: HashSet<String>,
919    pub(crate) all_rustc_abis: HashSet<String>,
920}
921
922impl TargetCfgs {
923    fn new(config: &Config) -> TargetCfgs {
924        let mut targets: HashMap<String, TargetCfg> = serde_json::from_str(&query_rustc_output(
925            config,
926            &["--print=all-target-specs-json", "-Zunstable-options"],
927            Default::default(),
928        ))
929        .unwrap();
930
931        let mut all_targets = HashSet::new();
932        let mut all_archs = HashSet::new();
933        let mut all_oses = HashSet::new();
934        let mut all_oses_and_envs = HashSet::new();
935        let mut all_envs = HashSet::new();
936        let mut all_abis = HashSet::new();
937        let mut all_families = HashSet::new();
938        let mut all_pointer_widths = HashSet::new();
939        // NOTE: for distinction between `abi` and `rustc_abi`, see comment on
940        // `TargetCfg::rustc_abi`.
941        let mut all_rustc_abis = HashSet::new();
942
943        // If current target is not included in the `--print=all-target-specs-json` output,
944        // we check whether it is a custom target from the user or a synthetic target from bootstrap.
945        if !targets.contains_key(&config.target) {
946            let mut envs: HashMap<String, String> = HashMap::new();
947
948            if let Ok(t) = std::env::var("RUST_TARGET_PATH") {
949                envs.insert("RUST_TARGET_PATH".into(), t);
950            }
951
952            // This returns false only when the target is neither a synthetic target
953            // nor a custom target from the user, indicating it is most likely invalid.
954            if config.target.ends_with(".json") || !envs.is_empty() {
955                targets.insert(
956                    config.target.clone(),
957                    serde_json::from_str(&query_rustc_output(
958                        config,
959                        &[
960                            "--print=target-spec-json",
961                            "-Zunstable-options",
962                            "--target",
963                            &config.target,
964                        ],
965                        envs,
966                    ))
967                    .unwrap(),
968                );
969            }
970        }
971
972        for (target, cfg) in targets.iter() {
973            all_archs.insert(cfg.arch.clone());
974            all_oses.insert(cfg.os.clone());
975            all_oses_and_envs.insert(cfg.os_and_env());
976            all_envs.insert(cfg.env.clone());
977            all_abis.insert(cfg.abi.clone());
978            for family in &cfg.families {
979                all_families.insert(family.clone());
980            }
981            all_pointer_widths.insert(format!("{}bit", cfg.pointer_width));
982            if let Some(rustc_abi) = &cfg.rustc_abi {
983                all_rustc_abis.insert(rustc_abi.clone());
984            }
985            all_targets.insert(target.clone());
986        }
987
988        Self {
989            current: Self::get_current_target_config(config, &targets),
990            all_targets,
991            all_archs,
992            all_oses,
993            all_oses_and_envs,
994            all_envs,
995            all_abis,
996            all_families,
997            all_pointer_widths,
998            all_rustc_abis,
999        }
1000    }
1001
1002    fn get_current_target_config(
1003        config: &Config,
1004        targets: &HashMap<String, TargetCfg>,
1005    ) -> TargetCfg {
1006        let mut cfg = targets[&config.target].clone();
1007
1008        // To get the target information for the current target, we take the target spec obtained
1009        // from `--print=all-target-specs-json`, and then we enrich it with the information
1010        // gathered from `--print=cfg --target=$target`.
1011        //
1012        // This is done because some parts of the target spec can be overridden with `-C` flags,
1013        // which are respected for `--print=cfg` but not for `--print=all-target-specs-json`. The
1014        // code below extracts them from `--print=cfg`: make sure to only override fields that can
1015        // actually be changed with `-C` flags.
1016        for config in query_rustc_output(
1017            config,
1018            // `-Zunstable-options` is necessary when compiletest is running with custom targets
1019            // (such as synthetic targets used to bless mir-opt tests).
1020            &["-Zunstable-options", "--print=cfg", "--target", &config.target],
1021            Default::default(),
1022        )
1023        .trim()
1024        .lines()
1025        {
1026            let (name, value) = config
1027                .split_once("=\"")
1028                .map(|(name, value)| {
1029                    (
1030                        name,
1031                        Some(
1032                            value
1033                                .strip_suffix('\"')
1034                                .expect("key-value pair should be properly quoted"),
1035                        ),
1036                    )
1037                })
1038                .unwrap_or_else(|| (config, None));
1039
1040            match (name, value) {
1041                // Can be overridden with `-C panic=$strategy`.
1042                ("panic", Some("abort")) => cfg.panic = PanicStrategy::Abort,
1043                ("panic", Some("unwind")) => cfg.panic = PanicStrategy::Unwind,
1044                ("panic", other) => panic!("unexpected value for panic cfg: {other:?}"),
1045
1046                ("target_has_atomic", Some(width))
1047                    if KNOWN_TARGET_HAS_ATOMIC_WIDTHS.contains(&width) =>
1048                {
1049                    cfg.target_has_atomic.insert(width.to_string());
1050                }
1051                ("target_has_atomic", Some(other)) => {
1052                    panic!("unexpected value for `target_has_atomic` cfg: {other:?}")
1053                }
1054                // Nightly-only std-internal impl detail.
1055                ("target_has_atomic", None) => {}
1056                _ => {}
1057            }
1058        }
1059
1060        cfg
1061    }
1062}
1063
1064#[derive(Clone, Debug, serde::Deserialize)]
1065#[serde(rename_all = "kebab-case")]
1066pub(crate) struct TargetCfg {
1067    pub(crate) arch: String,
1068    #[serde(default = "default_os")]
1069    pub(crate) os: String,
1070    #[serde(default)]
1071    pub(crate) env: String,
1072    #[serde(default)]
1073    pub(crate) abi: String,
1074    #[serde(rename = "target-family", default)]
1075    pub(crate) families: Vec<String>,
1076    #[serde(rename = "target-pointer-width")]
1077    pub(crate) pointer_width: u32,
1078    #[serde(rename = "target-endian", default)]
1079    endian: Endian,
1080    #[serde(rename = "panic-strategy", default)]
1081    pub(crate) panic: PanicStrategy,
1082    #[serde(default)]
1083    pub(crate) dynamic_linking: bool,
1084    #[serde(rename = "supported-sanitizers", default)]
1085    pub(crate) sanitizers: Vec<Sanitizer>,
1086    #[serde(rename = "supports-xray", default)]
1087    pub(crate) xray: bool,
1088    #[serde(default = "default_reloc_model")]
1089    pub(crate) relocation_model: String,
1090    // NOTE: `rustc_abi` should not be confused with `abi`. `rustc_abi` was introduced in #137037 to
1091    // make SSE2 *required* by the ABI (kind of a hack to make a target feature *required* via the
1092    // target spec).
1093    pub(crate) rustc_abi: Option<String>,
1094
1095    /// ELF is the "default" binary format, so the compiler typically doesn't
1096    /// emit a `"binary-format"` field for ELF targets.
1097    ///
1098    /// See `impl ToJson for Target` in `compiler/rustc_target/src/spec/json.rs`.
1099    #[serde(default = "default_binary_format_elf")]
1100    pub(crate) binary_format: Cow<'static, str>,
1101
1102    // Not present in target cfg json output, additional derived information.
1103    #[serde(skip)]
1104    /// Supported target atomic widths: e.g. `8` to `128` or `ptr`. This is derived from the builtin
1105    /// `target_has_atomic` `cfg`s e.g. `target_has_atomic="8"`.
1106    pub(crate) target_has_atomic: BTreeSet<String>,
1107}
1108
1109impl TargetCfg {
1110    pub(crate) fn os_and_env(&self) -> String {
1111        format!("{}-{}", self.os, self.env)
1112    }
1113}
1114
1115fn default_os() -> String {
1116    "none".into()
1117}
1118
1119fn default_reloc_model() -> String {
1120    "pic".into()
1121}
1122
1123fn default_binary_format_elf() -> Cow<'static, str> {
1124    Cow::Borrowed("elf")
1125}
1126
1127#[derive(Eq, PartialEq, Clone, Debug, Default, serde::Deserialize)]
1128#[serde(rename_all = "kebab-case")]
1129pub(crate) enum Endian {
1130    #[default]
1131    Little,
1132    Big,
1133}
1134
1135fn builtin_cfg_names(config: &Config) -> HashSet<String> {
1136    query_rustc_output(
1137        config,
1138        &["--print=check-cfg", "-Zunstable-options", "--check-cfg=cfg()"],
1139        Default::default(),
1140    )
1141    .lines()
1142    .map(|l| extract_cfg_name(&l).unwrap().to_string())
1143    .chain(std::iter::once(String::from("test")))
1144    .collect()
1145}
1146
1147/// Extract the cfg name from `cfg(name, values(...))` lines
1148fn extract_cfg_name(check_cfg_line: &str) -> Result<&str, &'static str> {
1149    let trimmed = check_cfg_line.trim();
1150
1151    #[rustfmt::skip]
1152    let inner = trimmed
1153        .strip_prefix("cfg(")
1154        .ok_or("missing cfg(")?
1155        .strip_suffix(")")
1156        .ok_or("missing )")?;
1157
1158    let first_comma = inner.find(',').ok_or("no comma found")?;
1159
1160    Ok(inner[..first_comma].trim())
1161}
1162
1163pub(crate) const KNOWN_CRATE_TYPES: &[&str] =
1164    &["bin", "cdylib", "dylib", "lib", "proc-macro", "rlib", "staticlib"];
1165
1166fn supported_crate_types(config: &Config) -> HashSet<String> {
1167    let crate_types: HashSet<_> = query_rustc_output(
1168        config,
1169        &["--target", &config.target, "--print=supported-crate-types", "-Zunstable-options"],
1170        Default::default(),
1171    )
1172    .lines()
1173    .map(|l| l.to_string())
1174    .collect();
1175
1176    for crate_type in crate_types.iter() {
1177        assert!(
1178            KNOWN_CRATE_TYPES.contains(&crate_type.as_str()),
1179            "unexpected crate type `{}`: known crate types are {:?}",
1180            crate_type,
1181            KNOWN_CRATE_TYPES
1182        );
1183    }
1184
1185    crate_types
1186}
1187
1188pub(crate) fn query_rustc_output(
1189    config: &Config,
1190    args: &[&str],
1191    envs: HashMap<String, String>,
1192) -> String {
1193    let query_rustc_path = config.query_rustc_path.as_deref().unwrap_or(&config.rustc_path);
1194
1195    let mut command = Command::new(query_rustc_path);
1196    add_dylib_path(&mut command, iter::once(&config.host_compile_lib_path));
1197    command.args(&config.target_rustcflags).args(args);
1198    command.env("RUSTC_BOOTSTRAP", "1");
1199    command.envs(envs);
1200
1201    let output = match command.output() {
1202        Ok(output) => output,
1203        Err(e) => {
1204            fatal!("failed to run {command:?}: {e}");
1205        }
1206    };
1207    if !output.status.success() {
1208        fatal!(
1209            "failed to run {command:?}\n--- stdout\n{}\n--- stderr\n{}",
1210            String::from_utf8(output.stdout).unwrap(),
1211            String::from_utf8(output.stderr).unwrap(),
1212        );
1213    }
1214    String::from_utf8(output.stdout).unwrap()
1215}
1216
1217/// Path information for a single test file.
1218#[derive(Debug, Clone)]
1219pub(crate) struct TestPaths {
1220    /// Full path to the test file.
1221    ///
1222    /// For example:
1223    /// - `/home/ferris/rust/tests/ui/warnings/hello-world.rs`
1224    ///
1225    /// ---
1226    ///
1227    /// For `run-make` tests, this path is the _directory_ that contains
1228    /// `rmake.rs`.
1229    ///
1230    /// For example:
1231    /// - `/home/ferris/rust/tests/run-make/emit`
1232    pub(crate) file: Utf8PathBuf,
1233
1234    /// Subset of the full path that excludes the suite directory and the
1235    /// test filename. For tests in the root of their test suite directory,
1236    /// this is blank.
1237    ///
1238    /// For example:
1239    /// - `file`: `/home/ferris/rust/tests/ui/warnings/hello-world.rs`
1240    /// - `relative_dir`: `warnings`
1241    pub(crate) relative_dir: Utf8PathBuf,
1242}
1243
1244/// Used by `ui` tests to generate things like `foo.stderr` from `foo.rs`.
1245pub(crate) fn expected_output_path(
1246    testpaths: &TestPaths,
1247    revision: Option<&str>,
1248    compare_mode: &Option<CompareMode>,
1249    kind: &str,
1250) -> Utf8PathBuf {
1251    assert!(UI_EXTENSIONS.contains(&kind));
1252    let mut parts = Vec::new();
1253
1254    if let Some(x) = revision {
1255        parts.push(x);
1256    }
1257    if let Some(ref x) = *compare_mode {
1258        parts.push(x.to_str());
1259    }
1260    parts.push(kind);
1261
1262    let extension = parts.join(".");
1263    testpaths.file.with_extension(extension)
1264}
1265
1266pub(crate) const UI_EXTENSIONS: &[&str] = &[
1267    UI_STDERR,
1268    UI_SVG,
1269    UI_WINDOWS_SVG,
1270    UI_STDOUT,
1271    UI_FIXED,
1272    UI_RUN_STDERR,
1273    UI_RUN_STDOUT,
1274    UI_STDERR_64,
1275    UI_STDERR_32,
1276    UI_STDERR_16,
1277    UI_COVERAGE,
1278    UI_COVERAGE_MAP,
1279];
1280pub(crate) const UI_STDERR: &str = "stderr";
1281pub(crate) const UI_SVG: &str = "svg";
1282pub(crate) const UI_WINDOWS_SVG: &str = "windows.svg";
1283pub(crate) const UI_STDOUT: &str = "stdout";
1284pub(crate) const UI_FIXED: &str = "fixed";
1285pub(crate) const UI_RUN_STDERR: &str = "run.stderr";
1286pub(crate) const UI_RUN_STDOUT: &str = "run.stdout";
1287pub(crate) const UI_STDERR_64: &str = "64bit.stderr";
1288pub(crate) const UI_STDERR_32: &str = "32bit.stderr";
1289pub(crate) const UI_STDERR_16: &str = "16bit.stderr";
1290pub(crate) const UI_COVERAGE: &str = "coverage";
1291pub(crate) const UI_COVERAGE_MAP: &str = "cov-map";
1292
1293/// Absolute path to the directory where all output for all tests in the given `relative_dir` group
1294/// should reside. Example:
1295///
1296/// ```text
1297/// /path/to/build/host-tuple/test/ui/relative/
1298/// ```
1299///
1300/// This is created early when tests are collected to avoid race conditions.
1301pub(crate) fn output_relative_path(config: &Config, relative_dir: &Utf8Path) -> Utf8PathBuf {
1302    config.build_test_suite_root.join(relative_dir)
1303}
1304
1305/// Generates a unique name for the test, such as `testname.revision.mode`.
1306pub(crate) fn output_testname_unique(
1307    config: &Config,
1308    testpaths: &TestPaths,
1309    revision: Option<&str>,
1310) -> Utf8PathBuf {
1311    let mode = config.compare_mode.as_ref().map_or("", |m| m.to_str());
1312    let debugger = config.debugger.as_ref().map_or("", |m| m.to_str());
1313    Utf8PathBuf::from(&testpaths.file.file_stem().unwrap())
1314        .with_extra_extension(config.mode.output_dir_disambiguator())
1315        .with_extra_extension(revision.unwrap_or(""))
1316        .with_extra_extension(mode)
1317        .with_extra_extension(debugger)
1318}
1319
1320/// Absolute path to the directory where all output for the given
1321/// test/revision should reside. Example:
1322///   /path/to/build/host-tuple/test/ui/relative/testname.revision.mode/
1323pub(crate) fn output_base_dir(
1324    config: &Config,
1325    testpaths: &TestPaths,
1326    revision: Option<&str>,
1327) -> Utf8PathBuf {
1328    output_relative_path(config, &testpaths.relative_dir)
1329        .join(output_testname_unique(config, testpaths, revision))
1330}
1331
1332/// Absolute path to the base filename used as output for the given
1333/// test/revision. Example:
1334///   /path/to/build/host-tuple/test/ui/relative/testname.revision.mode/testname
1335pub(crate) fn output_base_name(
1336    config: &Config,
1337    testpaths: &TestPaths,
1338    revision: Option<&str>,
1339) -> Utf8PathBuf {
1340    output_base_dir(config, testpaths, revision).join(testpaths.file.file_stem().unwrap())
1341}
1342
1343/// Absolute path to the directory to use for incremental compilation. Example:
1344///   /path/to/build/host-tuple/test/ui/relative/testname.mode/testname.inc
1345pub(crate) fn incremental_dir(
1346    config: &Config,
1347    testpaths: &TestPaths,
1348    revision: Option<&str>,
1349) -> Utf8PathBuf {
1350    output_base_name(config, testpaths, revision).with_extension("inc")
1351}