compiletest/
common.rs

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