Skip to main content

compiletest/
cli.rs

1//! Isolates the APIs used by `bin/main.rs`, to help minimize the surface area
2//! of public exports from the compiletest library crate.
3
4use std::fmt::Write;
5use std::io::IsTerminal;
6use std::sync::{Arc, OnceLock};
7use std::{env, fs};
8
9use camino::{Utf8Path, Utf8PathBuf};
10use clap::Parser;
11
12use crate::common::{CodegenBackend, CompareMode, Config, ForcePassMode, TestMode, TestSuite};
13use crate::edition::Edition;
14use crate::{
15    debuggers, directives, discovery, executor, help, panic_hook, raise_fd_limit, warning,
16};
17
18pub fn main() {
19    // sadly osx needs some file descriptor limits raised for running tests in
20    // parallel (especially when we have lots and lots of child processes).
21    // For context, see #8904
22    unsafe { raise_fd_limit::raise_fd_limit() };
23
24    // Prevent issue #21352 UAC blocking .exe containing 'patch' etc. on Windows
25    // If #11207 is resolved (adding manifest to .exe) this becomes unnecessary
26    //
27    // SAFETY: at this point we're still single-threaded.
28    unsafe { env::set_var("__COMPAT_LAYER", "RunAsInvoker") };
29
30    tracing_subscriber::fmt::init();
31    panic_hook::install_panic_hook();
32
33    // colored checks stdout by default, but for some reason only stderr is a terminal.
34    // compiletest *does* print many things to stdout, but it doesn't really matter.
35    if std::io::stderr().is_terminal()
36        && matches!(env::var("NO_COLOR").as_deref(), Err(_) | Ok("0"))
37    {
38        colored::control::set_override(true);
39    }
40
41    let config = Arc::new(parse_config(env::args().collect()));
42    early_config_check(&config);
43
44    // If we want to collect rustfix coverage information,
45    // we first make sure that the coverage file does not exist.
46    // It will be created later on.
47    if config.rustfix_coverage {
48        let mut coverage_file_path = config.build_test_suite_root.clone();
49        coverage_file_path.push("rustfix_missing_coverage.txt");
50        if coverage_file_path.exists() {
51            fs::remove_file(&coverage_file_path)
52                .unwrap_or_else(|e| panic!("Could not delete {coverage_file_path} due to {e}"));
53        }
54    }
55
56    // FIXME: this should ideally happen somewhere else..
57    if config.mode == TestMode::DebugInfo && config.target.contains("android") {
58        println!("{} debug-info test uses tcp 5039 port. please reserve it", config.target);
59
60        // android debug-info test uses remote debugger so, we test 1 thread
61        // at once as they're all sharing the same TCP port to communicate
62        // over.
63        //
64        // we should figure out how to lift this restriction! (run them all
65        // on different ports allocated dynamically).
66        //
67        // SAFETY: at this point we are still single-threaded.
68        unsafe { env::set_var("RUST_TEST_THREADS", "1") };
69    }
70
71    // Scan the test directory for tests, and create a test struct for each test/variant.
72    let tests = discovery::discover_tests(&config);
73
74    // Delegate to the executor to filter and run the big list of test structures
75    // created during test discovery. When the executor decides to run a test,
76    // it will return control to the rest of compiletest by calling `runtest::run`.
77    let ok = executor::run_tests(&config, tests);
78
79    // Check the outcome reported by the executor.
80    if !ok {
81        // We want to report that the tests failed, but we also want to give
82        // some indication of just what tests we were running. Especially on
83        // CI, where there can be cross-compiled tests for a lot of
84        // architectures, without this critical information it can be quite
85        // easy to miss which tests failed, and as such fail to reproduce
86        // the failure locally.
87
88        let mut msg = String::from("Some tests failed in compiletest");
89        write!(msg, " suite={}", config.suite).unwrap();
90
91        if let Some(compare_mode) = config.compare_mode.as_ref() {
92            write!(msg, " compare_mode={}", compare_mode).unwrap();
93        }
94
95        if let Some(pass_mode) = config.force_pass_mode.as_ref() {
96            write!(msg, " pass_mode={}", pass_mode).unwrap();
97        }
98
99        write!(msg, " mode={}", config.mode).unwrap();
100        write!(msg, " host={}", config.host).unwrap();
101        write!(msg, " target={}", config.target).unwrap();
102
103        println!("{msg}");
104
105        std::process::exit(1);
106    }
107}
108
109fn early_config_check(config: &Config) {
110    if !config.profiler_runtime && config.mode == TestMode::CoverageRun {
111        let actioned = if config.bless { "blessed" } else { "checked" };
112        warning!("profiler runtime is not available, so `.coverage` files won't be {actioned}");
113        help!("try setting `profiler = true` in the `[build]` section of `bootstrap.toml`");
114    }
115
116    // `RUST_TEST_NOCAPTURE` is a libtest env var, but we don't callout to libtest.
117    if env::var("RUST_TEST_NOCAPTURE").is_ok() {
118        warning!("`RUST_TEST_NOCAPTURE` is not supported; use the `--no-capture` flag instead");
119    }
120}
121
122/// Compiletest command-line arguments.
123#[derive(clap::Parser)]
124struct Args {
125    // Required options
126    /// Path to host shared libraries.
127    #[arg(long)]
128    compile_lib_path: Utf8PathBuf,
129    /// Path to target shared libraries.
130    #[arg(long)]
131    run_lib_path: Utf8PathBuf,
132    /// Path to rustc to use for compiling.
133    #[arg(long)]
134    rustc_path: Utf8PathBuf,
135    /// Path to the aux-lint rustc driver.
136    #[arg(long)]
137    rustc_lint_driver_path: Option<Utf8PathBuf>,
138    /// Path to the aux-lint rustc driver libdir.
139    #[arg(long)]
140    rustc_lint_driver_lib_path: Option<Utf8PathBuf>,
141    /// Path to the aux-lint rustc driver sysroot.
142    #[arg(long)]
143    rustc_lint_driver_sysroot: Option<Utf8PathBuf>,
144    /// Path to python to use for doc tests.
145    #[arg(long)]
146    python: String,
147    /// Directory containing sources.
148    #[arg(long)]
149    src_root: Utf8PathBuf,
150    /// Directory containing test suite sources.
151    #[arg(long)]
152    src_test_suite_root: Utf8PathBuf,
153    /// Path to root build directory.
154    #[arg(long)]
155    build_root: Utf8PathBuf,
156    /// Path to test suite specific build directory.
157    #[arg(long)]
158    build_test_suite_root: Utf8PathBuf,
159    /// Directory containing the compiler sysroot.
160    #[arg(long)]
161    sysroot_base: Utf8PathBuf,
162    /// Stage number under test.
163    #[arg(long)]
164    stage: u32,
165    /// The target-stage identifier.
166    #[arg(long)]
167    stage_id: String,
168    /// Which sort of compile tests to run.
169    #[arg(long)]
170    mode: TestMode,
171    /// Which suite of compile tests to run.
172    #[arg(long)]
173    suite: TestSuite,
174    /// Path to a C compiler.
175    #[arg(long)]
176    cc: String,
177    /// Path to a C++ compiler.
178    #[arg(long)]
179    cxx: String,
180    /// Flags for the C compiler.
181    #[arg(long, allow_hyphen_values = true)]
182    cflags: String,
183    /// Flags for the CXX compiler.
184    #[arg(long, allow_hyphen_values = true)]
185    cxxflags: String,
186    /// List of LLVM components built in.
187    #[arg(long)]
188    llvm_components: String,
189    /// Current Rust channel.
190    #[arg(long)]
191    channel: String,
192    /// Name of the git branch for nightly.
193    #[arg(long)]
194    nightly_branch: String,
195    /// Email address used for finding merge commits.
196    #[arg(long)]
197    git_merge_commit_email: String,
198    /// Path to minicore aux library.
199    #[arg(long)]
200    minicore_path: Utf8PathBuf,
201    /// Number of parallel jobs bootstrap was configured with.
202    #[arg(long)]
203    jobs: u32,
204    /// The host to build for.
205    #[arg(long)]
206    host: String,
207    /// The target to build for.
208    #[arg(long)]
209    target: String,
210
211    // Optional options
212    /// Path to cargo to use for compiling.
213    #[arg(long)]
214    cargo_path: Option<Utf8PathBuf>,
215    /// Path to rustc to use for compiling run-make recipes.
216    #[arg(long)]
217    stage0_rustc_path: Option<Utf8PathBuf>,
218    /// Path to librun-make-support .rlib to use for compiling run-make recipes.
219    #[arg(long)]
220    run_make_support_rlib: Option<Utf8PathBuf>,
221    /// Path to librun-make-support .rmeta to use for compiling run-make recipes.
222    #[arg(long)]
223    run_make_support_rmeta: Option<Utf8PathBuf>,
224    /// Path to rustc to use for querying target information.
225    #[arg(long)]
226    query_rustc_path: Option<Utf8PathBuf>,
227    /// Path to shared libraries for querying target information.
228    #[arg(long)]
229    query_rustc_lib_path: Option<Utf8PathBuf>,
230    /// Path to rustdoc to use for compiling.
231    #[arg(long)]
232    rustdoc_path: Option<Utf8PathBuf>,
233    /// Path to coverage-dump to use in tests.
234    #[arg(long)]
235    coverage_dump_path: Option<Utf8PathBuf>,
236    /// Path to jsondocck to use for doc tests.
237    #[arg(long)]
238    jsondocck_path: Option<Utf8PathBuf>,
239    /// Path to jsondoclint to use for doc tests.
240    #[arg(long)]
241    jsondoclint_path: Option<Utf8PathBuf>,
242    /// Path to Clang executable.
243    #[arg(long)]
244    run_clang_based_tests_with: Option<Utf8PathBuf>,
245    /// Path to LLVM's FileCheck binary.
246    #[arg(long)]
247    llvm_filecheck: Option<Utf8PathBuf>,
248    /// Path to LLVM's bin directory.
249    #[arg(long)]
250    llvm_bin_dir: Option<Utf8PathBuf>,
251    /// The name of nodejs.
252    #[arg(long)]
253    nodejs: Option<Utf8PathBuf>,
254    /// The name of npm.
255    #[arg(long)]
256    npm: Option<Utf8PathBuf>,
257    /// Path to the remote test client.
258    #[arg(long)]
259    remote_test_client: Option<Utf8PathBuf>,
260    /// Path to CDB to use for CDB debuginfo tests.
261    #[arg(long)]
262    cdb: Option<Utf8PathBuf>,
263    /// Path to GDB to use for GDB debuginfo tests.
264    #[arg(long)]
265    gdb: Option<Utf8PathBuf>,
266    /// Path to LLDB to use for LLDB debuginfo tests.
267    #[arg(long)]
268    lldb: Option<Utf8PathBuf>,
269    /// The version of LLDB used.
270    #[arg(long)]
271    lldb_version: Option<String>,
272    /// The version of LLVM used.
273    #[arg(long)]
274    llvm_version: Option<String>,
275    /// Android NDK standalone path.
276    #[arg(long)]
277    android_cross_path: Option<Utf8PathBuf>,
278    /// Path to the android debugger.
279    #[arg(long)]
280    adb_path: Option<Utf8PathBuf>,
281    /// Path to tests for the android debugger.
282    #[arg(long)]
283    adb_test_dir: Option<Utf8PathBuf>,
284    /// Path to an archiver.
285    #[arg(long, default_value = "ar")]
286    ar: String,
287    /// Path to a linker for the target.
288    #[arg(long)]
289    target_linker: Option<String>,
290    /// Path to a linker for the host.
291    #[arg(long)]
292    host_linker: Option<String>,
293    /// Force {check,build,run}-pass tests to this mode.
294    #[arg(long)]
295    pass: Option<ForcePassMode>,
296    /// Whether to execute run-* tests.
297    #[arg(long)]
298    run: Option<String>,
299    /// Supervisor program to run tests under (eg. emulator, valgrind).
300    #[arg(long)]
301    runner: Option<String>,
302    /// Mode describing what file the actual ui output will be compared to.
303    #[arg(long)]
304    compare_mode: Option<CompareMode>,
305    /// Default Rust edition.
306    #[arg(long)]
307    edition: Option<Edition>,
308    /// The codegen backend currently used.
309    #[arg(long)]
310    default_codegen_backend: Option<CodegenBackend>,
311    /// The codegen backend to use instead of the default one.
312    #[arg(long)]
313    override_codegen_backend: Option<String>,
314    /// Custom diff tool to use for displaying compiletest tests.
315    #[arg(long)]
316    compiletest_diff_tool: Option<String>,
317    /// Number of parallel threads to use for the frontend when building test artifacts
318    #[arg(long)]
319    parallel_frontend_threads: Option<u32>,
320    /// Number of times to execute each test.
321    #[arg(long)]
322    iteration_count: Option<u32>,
323
324    // Flags
325    /// Overwrite stderr/stdout files instead of complaining about a mismatch.
326    #[arg(long)]
327    bless: bool,
328    /// Stop as soon as possible after any test fails.
329    #[arg(long)]
330    fail_fast: bool,
331    /// Run tests marked as ignored.
332    #[arg(long)]
333    ignored: bool,
334    /// Run tests that require enzyme.
335    #[arg(long)]
336    has_enzyme: bool,
337    /// Run tests that require offload.
338    #[arg(long)]
339    has_offload: bool,
340    #[arg(long)]
341    has_tpde: bool,
342    /// Whether rustc was built with debug assertions.
343    #[arg(long)]
344    with_rustc_debug_assertions: bool,
345    /// Whether std was built with debug assertions.
346    #[arg(long)]
347    with_std_debug_assertions: bool,
348    /// Whether std was built with remapping.
349    #[arg(long)]
350    with_std_remap_debuginfo: bool,
351    /// Filters match exactly.
352    #[arg(long)]
353    exact: bool,
354    /// Set this when rustc/stdlib were compiled with randomized layouts.
355    #[arg(long)]
356    rust_randomized_layout: bool,
357    /// Run tests with optimizations enabled.
358    #[arg(long)]
359    optimize_tests: bool,
360    /// Pass `--disable-minification` to rustdoc when generating docs for tests.
361    #[arg(long)]
362    disable_minification: bool,
363    /// Run tests verbosely, showing all output.
364    #[arg(long)]
365    verbose: bool,
366    /// Show verbose subprocess output for successful run-make tests.
367    #[arg(long)]
368    verbose_run_make_subprocess_output: bool,
369    /// Is LLVM the system LLVM.
370    #[arg(long)]
371    system_llvm: bool,
372    /// Rerun tests even if the inputs are unchanged.
373    #[arg(long)]
374    force_rerun: bool,
375    /// Only run tests that result been modified.
376    #[arg(long)]
377    only_modified: bool,
378    // Backcompat option
379    #[arg(long, hide = true)]
380    nocapture: bool,
381    /// Don't capture stdout/stderr of tests.
382    #[arg(long)]
383    no_capture: bool,
384    /// Is the profiler runtime enabled for this target.
385    #[arg(long)]
386    profiler_runtime: bool,
387    /// Run tests which rely on commit version being compiled into the binaries.
388    #[arg(long)]
389    git_hash: bool,
390    /// Enable this to generate a Rustfix coverage file.
391    #[arg(long)]
392    rustfix_coverage: bool,
393    /// Ignore `//@ ignore-backends` directives.
394    #[arg(long)]
395    bypass_ignore_backends: bool,
396    /// Build proc-macros for wasm. Assumes environment is configured to support this; e.g., std is
397    /// already built appropriately.
398    #[arg(long)]
399    wasm_proc_macros: bool,
400
401    // These values can be entered multiple times, for example:
402    // --skip foo --skip bar
403    /// Skip tests matching SUBSTRING.
404    #[arg(long)]
405    skip: Vec<String>,
406    /// Flags to pass to rustc for host.
407    #[arg(long, allow_hyphen_values = true)]
408    host_rustcflags: Vec<String>,
409    /// Flags to pass to rustc for target.
410    #[arg(long, allow_hyphen_values = true)]
411    target_rustcflags: Vec<String>,
412
413    // Positional arguments
414    /// Test name filters.
415    /// All leftover arguments will be stored in this list.
416    filters: Vec<String>,
417}
418
419pub(crate) fn parse_config(args: Vec<String>) -> Config {
420    let args = Args::parse_from(args);
421
422    fn make_absolute(path: Utf8PathBuf) -> Utf8PathBuf {
423        if path.is_relative() {
424            Utf8PathBuf::try_from(env::current_dir().unwrap()).unwrap().join(path)
425        } else {
426            path
427        }
428    }
429
430    if args.nocapture {
431        panic!("`--nocapture` is deprecated; please use `--no-capture`");
432    }
433
434    let adb_device_status = args.target.contains("android") && args.adb_test_dir.is_some();
435
436    // FIXME: `cdb_version` is *derived* from cdb, but it's *not* technically a config!
437    let cdb_version = args.cdb.as_deref().and_then(debuggers::query_cdb_version);
438    // FIXME: `gdb_version` is *derived* from gdb, but it's *not* technically a config!
439    let gdb_version = args.gdb.as_deref().and_then(debuggers::query_gdb_version);
440    // FIXME: `lldb_version` is *derived* from lldb, but it's *not* technically a config!
441    let lldb_version = args.lldb_version.as_deref().and_then(debuggers::extract_lldb_version);
442    // FIXME: this is very questionable, we really should be obtaining LLVM version info from
443    // `bootstrap`, and not trying to be figuring out that in `compiletest` by running the
444    // `FileCheck` binary.
445    let llvm_version =
446        args.llvm_version.as_deref().map(directives::extract_llvm_version).or_else(|| {
447            directives::extract_llvm_version_from_binary(args.llvm_filecheck.as_ref()?.as_str())
448        });
449
450    let default_codegen_backend = args.default_codegen_backend.unwrap_or(CodegenBackend::Llvm);
451
452    let mode = args.mode;
453    let filters = if mode == TestMode::RunMake {
454        args.filters
455            .iter()
456            .map(|f| {
457                // Here `f` is relative to `./tests/run-make`. So if you run
458                //
459                //   ./x test tests/run-make/crate-loading
460                //
461                //  then `f` is "crate-loading".
462                let path = Utf8Path::new(f);
463                let mut iter = path.iter().skip(1);
464
465                if iter.next().is_some_and(|s| s == "rmake.rs") && iter.next().is_none() {
466                    // Strip the "rmake.rs" suffix. For example, if `f` is
467                    // "crate-loading/rmake.rs" then this gives us "crate-loading".
468                    path.parent().unwrap().to_string()
469                } else {
470                    f.to_string()
471                }
472            })
473            .collect::<Vec<_>>()
474    } else {
475        // Note that the filters are relative to the root dir of the different test
476        // suites. For example, with:
477        //
478        //   ./x test tests/ui/lint/unused
479        //
480        // the filter is "lint/unused".
481        args.filters.clone()
482    };
483
484    let compare_mode = args.compare_mode;
485
486    let src_root = args.src_root;
487    let src_test_suite_root = args.src_test_suite_root;
488    assert!(
489        src_test_suite_root.starts_with(&src_root),
490        "`src-root` must be a parent of `src-test-suite-root`: `src-root`=`{}`, `src-test-suite-root` = `{}`",
491        src_root,
492        src_test_suite_root
493    );
494
495    let build_root = args.build_root;
496    let build_test_suite_root = args.build_test_suite_root;
497    assert!(build_test_suite_root.starts_with(&build_root));
498
499    let parallel_frontend_threads =
500        args.parallel_frontend_threads.unwrap_or(Config::DEFAULT_PARALLEL_FRONTEND_THREADS);
501    let iteration_count = args.iteration_count.unwrap_or(Config::DEFAULT_ITERATION_COUNT);
502    assert!(iteration_count > 0, "`--iteration-count` must be a positive integer");
503
504    // FIXME: this run scheme is... confusing.
505    let run = args.run.and_then(|mode| match mode.as_str() {
506        "auto" => None,
507        "always" => Some(true),
508        "never" => Some(false),
509        _ => panic!("unknown `--run` option `{}` given", mode),
510    });
511
512    Config {
513        // tidy-alphabetical-start
514        adb_device_status,
515        adb_path: args.adb_path,
516        adb_test_dir: args.adb_test_dir,
517        android_cross_path: args.android_cross_path,
518        ar: args.ar,
519        bless: args.bless,
520        build_root,
521        build_test_suite_root,
522
523        builtin_cfg_names: OnceLock::new(),
524        bypass_ignore_backends: args.bypass_ignore_backends,
525
526        capture: !args.no_capture,
527
528        cargo_path: args.cargo_path,
529        cc: args.cc,
530        cdb: args.cdb,
531        cdb_version,
532        cflags: args.cflags,
533        channel: args.channel,
534        compare_mode,
535        coverage_dump_path: args.coverage_dump_path,
536        cxx: args.cxx,
537        cxxflags: args.cxxflags,
538        default_codegen_backend,
539        diff_command: args.compiletest_diff_tool,
540        disable_minification: args.disable_minification,
541
542        edition: args.edition,
543
544        fail_fast: args.fail_fast || env::var_os("RUSTC_TEST_FAIL_FAST").is_some(),
545
546        filter_exact: args.exact,
547        filters,
548        force_pass_mode: args.pass,
549        force_rerun: args.force_rerun,
550
551        gdb: args.gdb,
552        gdb_version,
553        git_hash: args.git_hash,
554        git_merge_commit_email: args.git_merge_commit_email,
555
556        has_enzyme: args.has_enzyme,
557        has_offload: args.has_offload,
558        has_tpde: args.has_tpde,
559        host: args.host,
560        host_compile_lib_path: make_absolute(args.compile_lib_path),
561        host_linker: args.host_linker,
562        host_rustcflags: args.host_rustcflags,
563        iteration_count,
564        jobs: args.jobs,
565
566        jsondocck_path: args.jsondocck_path,
567        jsondoclint_path: args.jsondoclint_path,
568        lldb: args.lldb,
569        lldb_version,
570        llvm_bin_dir: args.llvm_bin_dir,
571
572        llvm_components: args.llvm_components,
573        llvm_filecheck: args.llvm_filecheck,
574        llvm_version,
575        minicore_path: args.minicore_path,
576
577        mode,
578        nightly_branch: args.nightly_branch,
579        nodejs: args.nodejs,
580
581        only_modified: args.only_modified,
582        optimize_tests: args.optimize_tests,
583        override_codegen_backend: args.override_codegen_backend,
584        parallel_frontend_threads,
585        profiler_runtime: args.profiler_runtime,
586
587        python: args.python,
588        query_rustc_lib_path: args.query_rustc_lib_path,
589        query_rustc_path: args.query_rustc_path,
590        remote_test_client: args.remote_test_client,
591        run,
592        run_clang_based_tests_with: args.run_clang_based_tests_with,
593        run_ignored: args.ignored,
594        run_make_support_rlib: args.run_make_support_rlib,
595        run_make_support_rmeta: args.run_make_support_rmeta,
596        runner: args.runner,
597        rust_randomized_layout: args.rust_randomized_layout,
598        rustc_lint_driver_lib_path: args.rustc_lint_driver_lib_path,
599        rustc_lint_driver_path: args.rustc_lint_driver_path,
600        rustc_lint_driver_sysroot: args.rustc_lint_driver_sysroot,
601        rustc_path: args.rustc_path,
602        rustdoc_path: args.rustdoc_path,
603        rustfix_coverage: args.rustfix_coverage,
604        skip: args.skip,
605        src_root,
606        src_test_suite_root,
607
608        stage0_rustc_path: args.stage0_rustc_path,
609        stage: args.stage,
610        stage_id: args.stage_id,
611
612        suite: args.suite,
613        supported_crate_types: OnceLock::new(),
614
615        sysroot_base: args.sysroot_base,
616
617        system_llvm: args.system_llvm,
618        target: args.target,
619        target_cfgs: OnceLock::new(),
620        target_linker: args.target_linker,
621        target_run_lib_path: make_absolute(args.run_lib_path),
622        target_rustcflags: args.target_rustcflags,
623        verbose: args.verbose,
624        verbose_run_make_subprocess_output: args.verbose_run_make_subprocess_output,
625        wasm_proc_macros: args.wasm_proc_macros,
626
627        with_rustc_debug_assertions: args.with_rustc_debug_assertions,
628        with_std_debug_assertions: args.with_std_debug_assertions,
629        with_std_remap_debuginfo: args.with_std_remap_debuginfo,
630        // tidy-alphabetical-end
631    }
632}