compiletest/
common.rs

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