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        Rustdoc => "rustdoc",
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        Rustdoc => "rustdoc",
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    /// Only run tests that match these filters (using `libtest` "test name contains" filter logic).
442    ///
443    /// FIXME(#139660): the current hand-rolled test executor intentionally mimics the `libtest`
444    /// "test name contains" filter matching logic to preserve previous `libtest` executor behavior,
445    /// but this is often not intuitive. We should consider changing that behavior with an MCP to do
446    /// test path *prefix* matching which better corresponds to how `compiletest` `tests/` are
447    /// organized, and how users would intuitively expect the filtering logic to work like.
448    pub filters: Vec<String>,
449
450    /// Skip tests matching these substrings. The matching logic exactly corresponds to
451    /// [`Self::filters`] but inverted.
452    ///
453    /// FIXME(#139660): ditto on test matching behavior.
454    pub skip: Vec<String>,
455
456    /// Exactly match the filter, rather than a substring.
457    ///
458    /// FIXME(#139660): ditto on test matching behavior.
459    pub filter_exact: bool,
460
461    /// Force the pass mode of a check/build/run test to instead use this mode instead.
462    ///
463    /// FIXME: make it even more obvious (especially in PR CI where `--pass=check` is used) when a
464    /// pass mode is forced when the test fails, because it can be very non-obvious when e.g. an
465    /// error is emitted only when `//@ build-pass` but not `//@ check-pass`.
466    pub force_pass_mode: Option<PassMode>,
467
468    /// Explicitly enable or disable running of the target test binary.
469    ///
470    /// FIXME: this scheme is a bit confusing, and at times questionable. Re-evaluate this run
471    /// scheme.
472    ///
473    /// FIXME: Currently `--run` is a tri-state, it can be `--run={auto,always,never}`, and when
474    /// `--run=auto` is specified, it's run if the platform doesn't end with `-fuchsia`. See
475    /// [`Config::run_enabled`].
476    pub run: Option<bool>,
477
478    /// A command line to prefix target program execution with, for running under valgrind for
479    /// example, i.e. `$runner target.exe [args..]`. Similar to `CARGO_*_RUNNER` configuration.
480    ///
481    /// Note: this is not to be confused with [`Self::remote_test_client`], which is a different
482    /// scheme.
483    ///
484    /// FIXME: the runner scheme is very under-documented.
485    pub runner: Option<String>,
486
487    /// Compiler flags to pass to the *staged* `rustc`-under-test when building for the **host**
488    /// platform.
489    pub host_rustcflags: Vec<String>,
490
491    /// Compiler flags to pass to the *staged* `rustc`-under-test when building for the **target**
492    /// platform.
493    pub target_rustcflags: Vec<String>,
494
495    /// Whether the *staged* `rustc`-under-test and the associated *staged* `std` has been built
496    /// with randomized struct layouts.
497    pub rust_randomized_layout: bool,
498
499    /// Whether tests should be optimized by default (`-O`). Individual test suites and test files
500    /// may override this setting.
501    ///
502    /// FIXME: this flag / config option is somewhat misleading. For instance, in ui tests, it's
503    /// *only* applied to the [`PassMode::Run`] test crate and not its auxiliaries.
504    pub optimize_tests: bool,
505
506    /// Target platform tuple.
507    pub target: String,
508
509    /// Host platform tuple.
510    pub host: String,
511
512    /// Path to / name of the Microsoft Console Debugger (CDB) executable.
513    ///
514    /// FIXME: this is an *opt-in* "override" option. When this isn't provided, we try to conjure a
515    /// cdb by looking at the user's program files on Windows... See `debuggers::find_cdb`.
516    pub cdb: Option<Utf8PathBuf>,
517
518    /// Version of CDB.
519    ///
520    /// FIXME: `cdb_version` is *derived* from cdb, but it's *not* technically a config!
521    ///
522    /// FIXME: audit cdb version gating.
523    pub cdb_version: Option<[u16; 4]>,
524
525    /// Path to / name of the GDB executable.
526    ///
527    /// FIXME: the fallback path when `gdb` isn't provided tries to find *a* `gdb` or `gdb.exe` from
528    /// `PATH`, which is... arguably questionable.
529    ///
530    /// FIXME: we are propagating a python from `PYTHONPATH`, not from an explicit config for gdb
531    /// debugger script.
532    pub gdb: Option<Utf8PathBuf>,
533
534    /// Version of GDB, encoded as ((major * 1000) + minor) * 1000 + patch
535    ///
536    /// FIXME: this gdb version gating scheme is possibly questionable -- gdb does not use semver,
537    /// only its major version is likely materially meaningful, cf.
538    /// <https://sourceware.org/gdb/wiki/Internals%20Versions>. Even the major version I'm not sure
539    /// is super meaningful. Maybe min gdb `major.minor` version gating is sufficient for the
540    /// purposes of debuginfo tests?
541    ///
542    /// FIXME: `gdb_version` is *derived* from gdb, but it's *not* technically a config!
543    pub gdb_version: Option<u32>,
544
545    /// Path to or name of the LLDB executable to use for debuginfo tests.
546    pub lldb: Option<Utf8PathBuf>,
547
548    /// Version of LLDB.
549    ///
550    /// FIXME: `lldb_version` is *derived* from lldb, but it's *not* technically a config!
551    pub lldb_version: Option<u32>,
552
553    /// Version of LLVM.
554    ///
555    /// FIXME: Audit the fallback derivation of
556    /// [`crate::directives::extract_llvm_version_from_binary`], that seems very questionable?
557    pub llvm_version: Option<Version>,
558
559    /// Is LLVM a system LLVM.
560    pub system_llvm: bool,
561
562    /// Path to the android tools.
563    ///
564    /// Note: this is only used for android gdb debugger script in the debuginfo test suite.
565    ///
566    /// FIXME: take a look at this; this is piggy-backing off of gdb code paths but only for
567    /// `arm-linux-androideabi` target.
568    pub android_cross_path: Option<Utf8PathBuf>,
569
570    /// Extra parameter to run adb on `arm-linux-androideabi`.
571    ///
572    /// FIXME: is this *only* `arm-linux-androideabi`, or is it also for other Tier 2/3 android
573    /// targets?
574    ///
575    /// FIXME: take a look at this; this is piggy-backing off of gdb code paths but only for
576    /// `arm-linux-androideabi` target.
577    pub adb_path: Option<Utf8PathBuf>,
578
579    /// Extra parameter to run test suite on `arm-linux-androideabi`.
580    ///
581    /// FIXME: is this *only* `arm-linux-androideabi`, or is it also for other Tier 2/3 android
582    /// targets?
583    ///
584    /// FIXME: take a look at this; this is piggy-backing off of gdb code paths but only for
585    /// `arm-linux-androideabi` target.
586    pub adb_test_dir: Option<Utf8PathBuf>,
587
588    /// Status whether android device available or not. When unavailable, this will cause tests to
589    /// panic when the test binary is attempted to be run.
590    ///
591    /// FIXME: take a look at this; this also influences adb in gdb code paths in a strange way.
592    pub adb_device_status: bool,
593
594    /// Verbose dump a lot of info.
595    ///
596    /// FIXME: this is *way* too coarse; the user can't select *which* info to verbosely dump.
597    pub verbose: bool,
598
599    /// Where to find the remote test client process, if we're using it.
600    ///
601    /// Note: this is *only* used for target platform executables created by `run-make` test
602    /// recipes.
603    ///
604    /// Note: this is not to be confused with [`Self::runner`], which is a different scheme.
605    ///
606    /// FIXME: the `remote_test_client` scheme is very under-documented.
607    pub remote_test_client: Option<Utf8PathBuf>,
608
609    /// [`CompareMode`] describing what file the actual ui output will be compared to.
610    ///
611    /// FIXME: currently, [`CompareMode`] is a mishmash of lot of things (different borrow-checker
612    /// model, different trait solver, different debugger, etc.).
613    pub compare_mode: Option<CompareMode>,
614
615    /// If true, this will generate a coverage file with UI test files that run `MachineApplicable`
616    /// diagnostics but are missing `run-rustfix` annotations. The generated coverage file is
617    /// created in `$test_suite_build_root/rustfix_missing_coverage.txt`
618    pub rustfix_coverage: bool,
619
620    /// Whether to run `enzyme` autodiff tests.
621    pub has_enzyme: bool,
622
623    /// The current Rust channel info.
624    ///
625    /// FIXME: treat this more carefully; "stable", "beta" and "nightly" are definitely valid, but
626    /// channel might also be "dev" or such, which should be treated as "nightly".
627    pub channel: String,
628
629    /// Whether adding git commit information such as the commit hash has been enabled for building.
630    ///
631    /// FIXME: `compiletest` cannot trust `bootstrap` for this information, because `bootstrap` can
632    /// have bugs and had bugs on that logic. We need to figure out how to obtain this e.g. directly
633    /// from CI or via git locally.
634    pub git_hash: bool,
635
636    /// The default Rust edition.
637    pub edition: Option<Edition>,
638
639    // Configuration for various run-make tests frobbing things like C compilers or querying about
640    // various LLVM component information.
641    //
642    // FIXME: this really should be better packaged together.
643    // FIXME: these need better docs, e.g. for *host*, or for *target*?
644    pub cc: String,
645    pub cxx: String,
646    pub cflags: String,
647    pub cxxflags: String,
648    pub ar: String,
649    pub target_linker: Option<String>,
650    pub host_linker: Option<String>,
651    pub llvm_components: String,
652
653    /// Path to a NodeJS executable. Used for JS doctests, emscripten and WASM tests.
654    pub nodejs: Option<Utf8PathBuf>,
655
656    /// Whether to rerun tests even if the inputs are unchanged.
657    pub force_rerun: bool,
658
659    /// Only rerun the tests that result has been modified according to `git status`.
660    ///
661    /// FIXME: this is undocumented.
662    ///
663    /// FIXME: how does this interact with [`Self::force_rerun`]?
664    pub only_modified: bool,
665
666    // FIXME: these are really not "config"s, but rather are information derived from
667    // `rustc`-under-test. This poses an interesting conundrum: if we're testing the
668    // `rustc`-under-test, can we trust its print request outputs and target cfgs? In theory, this
669    // itself can break or be unreliable -- ideally, we'd be sharing these kind of information not
670    // through `rustc`-under-test's execution output. In practice, however, print requests are very
671    // unlikely to completely break (we also have snapshot ui tests for them). Furthermore, even if
672    // we share them via some kind of static config, that static config can still be wrong! Who
673    // tests the tester? Therefore, we make a pragmatic compromise here, and use information derived
674    // from print requests produced by the `rustc`-under-test.
675    //
676    // FIXME: move them out from `Config`, because they are *not* configs.
677    pub target_cfgs: OnceLock<TargetCfgs>,
678    pub builtin_cfg_names: OnceLock<HashSet<String>>,
679    pub supported_crate_types: OnceLock<HashSet<String>>,
680
681    /// Should we capture console output that would be printed by test runners via their `stdout`
682    /// and `stderr` trait objects, or via the custom panic hook.
683    ///
684    /// The default is `true`. This can be disabled via the compiletest cli flag `--no-capture`
685    /// (which mirrors the libtest `--no-capture` flag).
686    pub capture: bool,
687
688    /// Needed both to construct [`build_helper::git::GitConfig`].
689    pub nightly_branch: String,
690    pub git_merge_commit_email: String,
691
692    /// True if the profiler runtime is enabled for this target. Used by the
693    /// `needs-profiler-runtime` directive in test files.
694    pub profiler_runtime: bool,
695
696    /// Command for visual diff display, e.g. `diff-tool --color=always`.
697    pub diff_command: Option<String>,
698
699    /// Path to minicore aux library (`tests/auxiliary/minicore.rs`), used for `no_core` tests that
700    /// need `core` stubs in cross-compilation scenarios that do not otherwise want/need to
701    /// `-Zbuild-std`. Used in e.g. ABI tests.
702    pub minicore_path: Utf8PathBuf,
703
704    /// Current codegen backend used.
705    pub default_codegen_backend: CodegenBackend,
706    /// Name/path of the backend to use instead of `default_codegen_backend`.
707    pub override_codegen_backend: Option<String>,
708    /// Whether to ignore `//@ ignore-backends`.
709    pub bypass_ignore_backends: bool,
710}
711
712impl Config {
713    /// FIXME: this run scheme is... confusing.
714    pub fn run_enabled(&self) -> bool {
715        self.run.unwrap_or_else(|| {
716            // Auto-detect whether to run based on the platform.
717            !self.target.ends_with("-fuchsia")
718        })
719    }
720
721    pub fn target_cfgs(&self) -> &TargetCfgs {
722        self.target_cfgs.get_or_init(|| TargetCfgs::new(self))
723    }
724
725    pub fn target_cfg(&self) -> &TargetCfg {
726        &self.target_cfgs().current
727    }
728
729    pub fn matches_arch(&self, arch: &str) -> bool {
730        self.target_cfg().arch == arch
731            || {
732                // Matching all the thumb variants as one can be convenient.
733                // (thumbv6m, thumbv7em, thumbv7m, etc.)
734                arch == "thumb" && self.target.starts_with("thumb")
735            }
736            || (arch == "i586" && self.target.starts_with("i586-"))
737    }
738
739    pub fn matches_os(&self, os: &str) -> bool {
740        self.target_cfg().os == os
741    }
742
743    pub fn matches_env(&self, env: &str) -> bool {
744        self.target_cfg().env == env
745    }
746
747    pub fn matches_abi(&self, abi: &str) -> bool {
748        self.target_cfg().abi == abi
749    }
750
751    #[cfg_attr(not(test), expect(dead_code, reason = "only used by tests for `ignore-{family}`"))]
752    pub(crate) fn matches_family(&self, family: &str) -> bool {
753        self.target_cfg().families.iter().any(|f| f == family)
754    }
755
756    pub fn is_big_endian(&self) -> bool {
757        self.target_cfg().endian == Endian::Big
758    }
759
760    pub fn get_pointer_width(&self) -> u32 {
761        *&self.target_cfg().pointer_width
762    }
763
764    pub fn can_unwind(&self) -> bool {
765        self.target_cfg().panic == PanicStrategy::Unwind
766    }
767
768    /// Get the list of builtin, 'well known' cfg names
769    pub fn builtin_cfg_names(&self) -> &HashSet<String> {
770        self.builtin_cfg_names.get_or_init(|| builtin_cfg_names(self))
771    }
772
773    /// Get the list of crate types that the target platform supports.
774    pub fn supported_crate_types(&self) -> &HashSet<String> {
775        self.supported_crate_types.get_or_init(|| supported_crate_types(self))
776    }
777
778    pub fn has_threads(&self) -> bool {
779        // Wasm targets don't have threads unless `-threads` is in the target
780        // name, such as `wasm32-wasip1-threads`.
781        if self.target.starts_with("wasm") {
782            return self.target.contains("threads");
783        }
784        true
785    }
786
787    pub fn has_asm_support(&self) -> bool {
788        // This should match the stable list in `LoweringContext::lower_inline_asm`.
789        static ASM_SUPPORTED_ARCHS: &[&str] = &[
790            "x86",
791            "x86_64",
792            "arm",
793            "aarch64",
794            "arm64ec",
795            "riscv32",
796            "riscv64",
797            "loongarch32",
798            "loongarch64",
799            "s390x",
800            // These targets require an additional asm_experimental_arch feature.
801            // "nvptx64", "hexagon", "mips", "mips64", "spirv", "wasm32",
802        ];
803        ASM_SUPPORTED_ARCHS.contains(&self.target_cfg().arch.as_str())
804    }
805
806    pub fn git_config(&self) -> GitConfig<'_> {
807        GitConfig {
808            nightly_branch: &self.nightly_branch,
809            git_merge_commit_email: &self.git_merge_commit_email,
810        }
811    }
812
813    pub fn has_subprocess_support(&self) -> bool {
814        // FIXME(#135928): compiletest is always a **host** tool. Building and running an
815        // capability detection executable against the **target** is not trivial. The short term
816        // solution here is to hard-code some targets to allow/deny, unfortunately.
817
818        let unsupported_target = self.target_cfg().env == "sgx"
819            || matches!(self.target_cfg().arch.as_str(), "wasm32" | "wasm64")
820            || self.target_cfg().os == "emscripten";
821        !unsupported_target
822    }
823}
824
825/// Known widths of `target_has_atomic`.
826pub const KNOWN_TARGET_HAS_ATOMIC_WIDTHS: &[&str] = &["8", "16", "32", "64", "128", "ptr"];
827
828#[derive(Debug, Clone)]
829pub struct TargetCfgs {
830    pub current: TargetCfg,
831    pub all_targets: HashSet<String>,
832    pub all_archs: HashSet<String>,
833    pub all_oses: HashSet<String>,
834    pub all_oses_and_envs: HashSet<String>,
835    pub all_envs: HashSet<String>,
836    pub all_abis: HashSet<String>,
837    pub all_families: HashSet<String>,
838    pub all_pointer_widths: HashSet<String>,
839    pub all_rustc_abis: HashSet<String>,
840}
841
842impl TargetCfgs {
843    fn new(config: &Config) -> TargetCfgs {
844        let mut targets: HashMap<String, TargetCfg> = serde_json::from_str(&query_rustc_output(
845            config,
846            &["--print=all-target-specs-json", "-Zunstable-options"],
847            Default::default(),
848        ))
849        .unwrap();
850
851        let mut all_targets = HashSet::new();
852        let mut all_archs = HashSet::new();
853        let mut all_oses = HashSet::new();
854        let mut all_oses_and_envs = HashSet::new();
855        let mut all_envs = HashSet::new();
856        let mut all_abis = HashSet::new();
857        let mut all_families = HashSet::new();
858        let mut all_pointer_widths = HashSet::new();
859        // NOTE: for distinction between `abi` and `rustc_abi`, see comment on
860        // `TargetCfg::rustc_abi`.
861        let mut all_rustc_abis = HashSet::new();
862
863        // If current target is not included in the `--print=all-target-specs-json` output,
864        // we check whether it is a custom target from the user or a synthetic target from bootstrap.
865        if !targets.contains_key(&config.target) {
866            let mut envs: HashMap<String, String> = HashMap::new();
867
868            if let Ok(t) = std::env::var("RUST_TARGET_PATH") {
869                envs.insert("RUST_TARGET_PATH".into(), t);
870            }
871
872            // This returns false only when the target is neither a synthetic target
873            // nor a custom target from the user, indicating it is most likely invalid.
874            if config.target.ends_with(".json") || !envs.is_empty() {
875                targets.insert(
876                    config.target.clone(),
877                    serde_json::from_str(&query_rustc_output(
878                        config,
879                        &[
880                            "--print=target-spec-json",
881                            "-Zunstable-options",
882                            "--target",
883                            &config.target,
884                        ],
885                        envs,
886                    ))
887                    .unwrap(),
888                );
889            }
890        }
891
892        for (target, cfg) in targets.iter() {
893            all_archs.insert(cfg.arch.clone());
894            all_oses.insert(cfg.os.clone());
895            all_oses_and_envs.insert(cfg.os_and_env());
896            all_envs.insert(cfg.env.clone());
897            all_abis.insert(cfg.abi.clone());
898            for family in &cfg.families {
899                all_families.insert(family.clone());
900            }
901            all_pointer_widths.insert(format!("{}bit", cfg.pointer_width));
902            if let Some(rustc_abi) = &cfg.rustc_abi {
903                all_rustc_abis.insert(rustc_abi.clone());
904            }
905            all_targets.insert(target.clone());
906        }
907
908        Self {
909            current: Self::get_current_target_config(config, &targets),
910            all_targets,
911            all_archs,
912            all_oses,
913            all_oses_and_envs,
914            all_envs,
915            all_abis,
916            all_families,
917            all_pointer_widths,
918            all_rustc_abis,
919        }
920    }
921
922    fn get_current_target_config(
923        config: &Config,
924        targets: &HashMap<String, TargetCfg>,
925    ) -> TargetCfg {
926        let mut cfg = targets[&config.target].clone();
927
928        // To get the target information for the current target, we take the target spec obtained
929        // from `--print=all-target-specs-json`, and then we enrich it with the information
930        // gathered from `--print=cfg --target=$target`.
931        //
932        // This is done because some parts of the target spec can be overridden with `-C` flags,
933        // which are respected for `--print=cfg` but not for `--print=all-target-specs-json`. The
934        // code below extracts them from `--print=cfg`: make sure to only override fields that can
935        // actually be changed with `-C` flags.
936        for config in query_rustc_output(
937            config,
938            &["--print=cfg", "--target", &config.target],
939            Default::default(),
940        )
941        .trim()
942        .lines()
943        {
944            let (name, value) = config
945                .split_once("=\"")
946                .map(|(name, value)| {
947                    (
948                        name,
949                        Some(
950                            value
951                                .strip_suffix('\"')
952                                .expect("key-value pair should be properly quoted"),
953                        ),
954                    )
955                })
956                .unwrap_or_else(|| (config, None));
957
958            match (name, value) {
959                // Can be overridden with `-C panic=$strategy`.
960                ("panic", Some("abort")) => cfg.panic = PanicStrategy::Abort,
961                ("panic", Some("unwind")) => cfg.panic = PanicStrategy::Unwind,
962                ("panic", other) => panic!("unexpected value for panic cfg: {other:?}"),
963
964                ("target_has_atomic", Some(width))
965                    if KNOWN_TARGET_HAS_ATOMIC_WIDTHS.contains(&width) =>
966                {
967                    cfg.target_has_atomic.insert(width.to_string());
968                }
969                ("target_has_atomic", Some(other)) => {
970                    panic!("unexpected value for `target_has_atomic` cfg: {other:?}")
971                }
972                // Nightly-only std-internal impl detail.
973                ("target_has_atomic", None) => {}
974                _ => {}
975            }
976        }
977
978        cfg
979    }
980}
981
982#[derive(Clone, Debug, serde::Deserialize)]
983#[serde(rename_all = "kebab-case")]
984pub struct TargetCfg {
985    pub(crate) arch: String,
986    #[serde(default = "default_os")]
987    pub(crate) os: String,
988    #[serde(default)]
989    pub(crate) env: String,
990    #[serde(default)]
991    pub(crate) abi: String,
992    #[serde(rename = "target-family", default)]
993    pub(crate) families: Vec<String>,
994    #[serde(rename = "target-pointer-width")]
995    pub(crate) pointer_width: u32,
996    #[serde(rename = "target-endian", default)]
997    endian: Endian,
998    #[serde(rename = "panic-strategy", default)]
999    pub(crate) panic: PanicStrategy,
1000    #[serde(default)]
1001    pub(crate) dynamic_linking: bool,
1002    #[serde(rename = "supported-sanitizers", default)]
1003    pub(crate) sanitizers: Vec<Sanitizer>,
1004    #[serde(rename = "supports-xray", default)]
1005    pub(crate) xray: bool,
1006    #[serde(default = "default_reloc_model")]
1007    pub(crate) relocation_model: String,
1008    // NOTE: `rustc_abi` should not be confused with `abi`. `rustc_abi` was introduced in #137037 to
1009    // make SSE2 *required* by the ABI (kind of a hack to make a target feature *required* via the
1010    // target spec).
1011    pub(crate) rustc_abi: Option<String>,
1012
1013    /// ELF is the "default" binary format, so the compiler typically doesn't
1014    /// emit a `"binary-format"` field for ELF targets.
1015    ///
1016    /// See `impl ToJson for Target` in `compiler/rustc_target/src/spec/json.rs`.
1017    #[serde(default = "default_binary_format_elf")]
1018    pub(crate) binary_format: Cow<'static, str>,
1019
1020    // Not present in target cfg json output, additional derived information.
1021    #[serde(skip)]
1022    /// Supported target atomic widths: e.g. `8` to `128` or `ptr`. This is derived from the builtin
1023    /// `target_has_atomic` `cfg`s e.g. `target_has_atomic="8"`.
1024    pub(crate) target_has_atomic: BTreeSet<String>,
1025}
1026
1027impl TargetCfg {
1028    pub(crate) fn os_and_env(&self) -> String {
1029        format!("{}-{}", self.os, self.env)
1030    }
1031}
1032
1033fn default_os() -> String {
1034    "none".into()
1035}
1036
1037fn default_reloc_model() -> String {
1038    "pic".into()
1039}
1040
1041fn default_binary_format_elf() -> Cow<'static, str> {
1042    Cow::Borrowed("elf")
1043}
1044
1045#[derive(Eq, PartialEq, Clone, Debug, Default, serde::Deserialize)]
1046#[serde(rename_all = "kebab-case")]
1047pub enum Endian {
1048    #[default]
1049    Little,
1050    Big,
1051}
1052
1053fn builtin_cfg_names(config: &Config) -> HashSet<String> {
1054    query_rustc_output(
1055        config,
1056        &["--print=check-cfg", "-Zunstable-options", "--check-cfg=cfg()"],
1057        Default::default(),
1058    )
1059    .lines()
1060    .map(|l| if let Some((name, _)) = l.split_once('=') { name.to_string() } else { l.to_string() })
1061    .chain(std::iter::once(String::from("test")))
1062    .collect()
1063}
1064
1065pub const KNOWN_CRATE_TYPES: &[&str] =
1066    &["bin", "cdylib", "dylib", "lib", "proc-macro", "rlib", "staticlib"];
1067
1068fn supported_crate_types(config: &Config) -> HashSet<String> {
1069    let crate_types: HashSet<_> = query_rustc_output(
1070        config,
1071        &["--target", &config.target, "--print=supported-crate-types", "-Zunstable-options"],
1072        Default::default(),
1073    )
1074    .lines()
1075    .map(|l| l.to_string())
1076    .collect();
1077
1078    for crate_type in crate_types.iter() {
1079        assert!(
1080            KNOWN_CRATE_TYPES.contains(&crate_type.as_str()),
1081            "unexpected crate type `{}`: known crate types are {:?}",
1082            crate_type,
1083            KNOWN_CRATE_TYPES
1084        );
1085    }
1086
1087    crate_types
1088}
1089
1090pub(crate) fn query_rustc_output(
1091    config: &Config,
1092    args: &[&str],
1093    envs: HashMap<String, String>,
1094) -> String {
1095    let query_rustc_path = config.query_rustc_path.as_deref().unwrap_or(&config.rustc_path);
1096
1097    let mut command = Command::new(query_rustc_path);
1098    add_dylib_path(&mut command, iter::once(&config.host_compile_lib_path));
1099    command.args(&config.target_rustcflags).args(args);
1100    command.env("RUSTC_BOOTSTRAP", "1");
1101    command.envs(envs);
1102
1103    let output = match command.output() {
1104        Ok(output) => output,
1105        Err(e) => {
1106            fatal!("failed to run {command:?}: {e}");
1107        }
1108    };
1109    if !output.status.success() {
1110        fatal!(
1111            "failed to run {command:?}\n--- stdout\n{}\n--- stderr\n{}",
1112            String::from_utf8(output.stdout).unwrap(),
1113            String::from_utf8(output.stderr).unwrap(),
1114        );
1115    }
1116    String::from_utf8(output.stdout).unwrap()
1117}
1118
1119/// Path information for a single test file.
1120#[derive(Debug, Clone)]
1121pub(crate) struct TestPaths {
1122    /// Full path to the test file.
1123    ///
1124    /// For example:
1125    /// - `/home/ferris/rust/tests/ui/warnings/hello-world.rs`
1126    ///
1127    /// ---
1128    ///
1129    /// For `run-make` tests, this path is the _directory_ that contains
1130    /// `rmake.rs`.
1131    ///
1132    /// For example:
1133    /// - `/home/ferris/rust/tests/run-make/emit`
1134    pub(crate) file: Utf8PathBuf,
1135
1136    /// Subset of the full path that excludes the suite directory and the
1137    /// test filename. For tests in the root of their test suite directory,
1138    /// this is blank.
1139    ///
1140    /// For example:
1141    /// - `file`: `/home/ferris/rust/tests/ui/warnings/hello-world.rs`
1142    /// - `relative_dir`: `warnings`
1143    pub(crate) relative_dir: Utf8PathBuf,
1144}
1145
1146/// Used by `ui` tests to generate things like `foo.stderr` from `foo.rs`.
1147pub fn expected_output_path(
1148    testpaths: &TestPaths,
1149    revision: Option<&str>,
1150    compare_mode: &Option<CompareMode>,
1151    kind: &str,
1152) -> Utf8PathBuf {
1153    assert!(UI_EXTENSIONS.contains(&kind));
1154    let mut parts = Vec::new();
1155
1156    if let Some(x) = revision {
1157        parts.push(x);
1158    }
1159    if let Some(ref x) = *compare_mode {
1160        parts.push(x.to_str());
1161    }
1162    parts.push(kind);
1163
1164    let extension = parts.join(".");
1165    testpaths.file.with_extension(extension)
1166}
1167
1168pub const UI_EXTENSIONS: &[&str] = &[
1169    UI_STDERR,
1170    UI_SVG,
1171    UI_WINDOWS_SVG,
1172    UI_STDOUT,
1173    UI_FIXED,
1174    UI_RUN_STDERR,
1175    UI_RUN_STDOUT,
1176    UI_STDERR_64,
1177    UI_STDERR_32,
1178    UI_STDERR_16,
1179    UI_COVERAGE,
1180    UI_COVERAGE_MAP,
1181];
1182pub const UI_STDERR: &str = "stderr";
1183pub const UI_SVG: &str = "svg";
1184pub const UI_WINDOWS_SVG: &str = "windows.svg";
1185pub const UI_STDOUT: &str = "stdout";
1186pub const UI_FIXED: &str = "fixed";
1187pub const UI_RUN_STDERR: &str = "run.stderr";
1188pub const UI_RUN_STDOUT: &str = "run.stdout";
1189pub const UI_STDERR_64: &str = "64bit.stderr";
1190pub const UI_STDERR_32: &str = "32bit.stderr";
1191pub const UI_STDERR_16: &str = "16bit.stderr";
1192pub const UI_COVERAGE: &str = "coverage";
1193pub const UI_COVERAGE_MAP: &str = "cov-map";
1194
1195/// Absolute path to the directory where all output for all tests in the given `relative_dir` group
1196/// should reside. Example:
1197///
1198/// ```text
1199/// /path/to/build/host-tuple/test/ui/relative/
1200/// ```
1201///
1202/// This is created early when tests are collected to avoid race conditions.
1203pub fn output_relative_path(config: &Config, relative_dir: &Utf8Path) -> Utf8PathBuf {
1204    config.build_test_suite_root.join(relative_dir)
1205}
1206
1207/// Generates a unique name for the test, such as `testname.revision.mode`.
1208pub fn output_testname_unique(
1209    config: &Config,
1210    testpaths: &TestPaths,
1211    revision: Option<&str>,
1212) -> Utf8PathBuf {
1213    let mode = config.compare_mode.as_ref().map_or("", |m| m.to_str());
1214    let debugger = config.debugger.as_ref().map_or("", |m| m.to_str());
1215    Utf8PathBuf::from(&testpaths.file.file_stem().unwrap())
1216        .with_extra_extension(config.mode.output_dir_disambiguator())
1217        .with_extra_extension(revision.unwrap_or(""))
1218        .with_extra_extension(mode)
1219        .with_extra_extension(debugger)
1220}
1221
1222/// Absolute path to the directory where all output for the given
1223/// test/revision should reside. Example:
1224///   /path/to/build/host-tuple/test/ui/relative/testname.revision.mode/
1225pub fn output_base_dir(
1226    config: &Config,
1227    testpaths: &TestPaths,
1228    revision: Option<&str>,
1229) -> Utf8PathBuf {
1230    output_relative_path(config, &testpaths.relative_dir)
1231        .join(output_testname_unique(config, testpaths, revision))
1232}
1233
1234/// Absolute path to the base filename used as output for the given
1235/// test/revision. Example:
1236///   /path/to/build/host-tuple/test/ui/relative/testname.revision.mode/testname
1237pub fn output_base_name(
1238    config: &Config,
1239    testpaths: &TestPaths,
1240    revision: Option<&str>,
1241) -> Utf8PathBuf {
1242    output_base_dir(config, testpaths, revision).join(testpaths.file.file_stem().unwrap())
1243}
1244
1245/// Absolute path to the directory to use for incremental compilation. Example:
1246///   /path/to/build/host-tuple/test/ui/relative/testname.mode/testname.inc
1247pub fn incremental_dir(
1248    config: &Config,
1249    testpaths: &TestPaths,
1250    revision: Option<&str>,
1251) -> Utf8PathBuf {
1252    output_base_name(config, testpaths, revision).with_extension("inc")
1253}