Skip to main content

compiletest/
directives.rs

1use std::collections::HashSet;
2use std::process::Command;
3use std::{env, fs};
4
5use camino::{Utf8Path, Utf8PathBuf};
6use semver::Version;
7use tracing::*;
8
9use crate::common::{CodegenBackend, Config, Debugger, FailMode, PassMode, RunFailMode, TestMode};
10use crate::debuggers::{extract_cdb_version, extract_gdb_version};
11use crate::directives::auxiliary::parse_and_update_aux;
12pub(crate) use crate::directives::auxiliary::{AuxCrate, AuxProps};
13use crate::directives::directive_names::{
14    KNOWN_DIRECTIVE_NAMES_SET, KNOWN_HTMLDOCCK_DIRECTIVE_NAMES, KNOWN_JSONDOCCK_DIRECTIVE_NAMES,
15};
16pub(crate) use crate::directives::file::FileDirectives;
17use crate::directives::handlers::DIRECTIVE_HANDLERS_MAP;
18use crate::directives::line::DirectiveLine;
19use crate::directives::needs::CachedNeedsConditions;
20use crate::edition::{Edition, parse_edition};
21use crate::errors::ErrorKind;
22use crate::executor::{CollectedTestDesc, ShouldFail};
23use crate::util::static_regex;
24use crate::{fatal, help};
25
26mod auxiliary;
27mod cfg;
28mod directive_names;
29mod file;
30mod handlers;
31mod line;
32pub(crate) use line::line_directive;
33mod line_number;
34pub(crate) use line_number::LineNumber;
35mod needs;
36#[cfg(test)]
37mod tests;
38
39pub(crate) struct DirectivesCache {
40    /// "Conditions" used by `ignore-*` and `only-*` directives, prepared in
41    /// advance so that they don't have to be evaluated repeatedly.
42    cfg_conditions: cfg::PreparedConditions,
43    needs: CachedNeedsConditions,
44}
45
46impl DirectivesCache {
47    pub(crate) fn load(config: &Config) -> Self {
48        Self {
49            cfg_conditions: cfg::prepare_conditions(config),
50            needs: CachedNeedsConditions::load(config),
51        }
52    }
53}
54
55/// Properties which must be known very early, before actually running
56/// the test.
57#[derive(Default)]
58pub(crate) struct EarlyProps {
59    pub(crate) revisions: Vec<String>,
60}
61
62impl EarlyProps {
63    pub(crate) fn from_file_directives(
64        config: &Config,
65        file_directives: &FileDirectives<'_>,
66    ) -> Self {
67        let mut props = EarlyProps::default();
68
69        iter_directives(
70            config,
71            file_directives,
72            // (dummy comment to force args into vertical layout)
73            &mut |ln: &DirectiveLine<'_>| {
74                config.parse_and_update_revisions(ln, &mut props.revisions);
75            },
76        );
77
78        props
79    }
80}
81
82#[derive(Clone, Debug)]
83pub(crate) struct TestProps {
84    // Lines that should be expected, in order, on standard out
85    pub(crate) error_patterns: Vec<String>,
86    // Regexes that should be expected, in order, on standard out
87    pub(crate) regex_error_patterns: Vec<String>,
88    /// Edition selected by an `//@ edition` directive, if any.
89    ///
90    /// Automatically added to `compile_flags` during directive processing.
91    pub(crate) edition: Option<Edition>,
92    // Extra flags to pass to the compiler
93    pub(crate) compile_flags: Vec<String>,
94    // Extra flags to pass when the compiled code is run (such as --bench)
95    pub(crate) run_flags: Vec<String>,
96    /// Extra flags to pass to rustdoc but not the compiler.
97    pub(crate) doc_flags: Vec<String>,
98    // If present, the name of a file that this test should match when
99    // pretty-printed
100    pub(crate) pp_exact: Option<Utf8PathBuf>,
101    /// Auxiliary crates that should be built and made available to this test.
102    pub(crate) aux: AuxProps,
103    // Environment settings to use for compiling
104    pub(crate) rustc_env: Vec<(String, String)>,
105    // Environment variables to unset prior to compiling.
106    // Variables are unset before applying 'rustc_env'.
107    pub(crate) unset_rustc_env: Vec<String>,
108    // Environment settings to use during execution
109    pub(crate) exec_env: Vec<(String, String)>,
110    // Environment variables to unset prior to execution.
111    // Variables are unset before applying 'exec_env'
112    pub(crate) unset_exec_env: Vec<String>,
113    // Build documentation for all specified aux-builds as well
114    pub(crate) build_aux_docs: bool,
115    /// Build the documentation for each crate in a unique output directory.
116    /// Uses `<root output directory>/docs/<test name>/doc`.
117    pub(crate) unique_doc_out_dir: bool,
118    // Flag to force a crate to be built with the host architecture
119    pub(crate) force_host: bool,
120    // Check stdout for error-pattern output as well as stderr
121    pub(crate) check_stdout: bool,
122    // Check stdout & stderr for output of run-pass test
123    pub(crate) check_run_results: bool,
124    // For UI tests, allows compiler to generate arbitrary output to stdout
125    pub(crate) dont_check_compiler_stdout: bool,
126    // For UI tests, allows compiler to generate arbitrary output to stderr
127    pub(crate) dont_check_compiler_stderr: bool,
128    // Don't force a --crate-type=dylib flag on the command line
129    //
130    // Set this for example if you have an auxiliary test file that contains
131    // a proc-macro and needs `#![crate_type = "proc-macro"]`. This ensures
132    // that the aux file is compiled as a `proc-macro` and not as a `dylib`.
133    pub(crate) no_prefer_dynamic: bool,
134    // Which pretty mode are we testing with, default to 'normal'
135    pub(crate) pretty_mode: String,
136    // Only compare pretty output and don't try compiling
137    pub(crate) pretty_compare_only: bool,
138    /// Strings that must not appear in compile/run output.
139    pub(crate) forbid_output: Vec<String>,
140    // Revisions to test for incremental compilation.
141    pub(crate) revisions: Vec<String>,
142    // Directory (if any) to use for incremental compilation.  This is
143    // not set by end-users; rather it is set by the incremental
144    // testing harness and used when generating compilation
145    // arguments. (In particular, it propagates to the aux-builds.)
146    pub(crate) incremental_dir: Option<Utf8PathBuf>,
147    // If `true`, this test will use incremental compilation.
148    //
149    // This can be set manually with the `incremental` directive, or implicitly
150    // by being a part of an incremental mode test. Using the `incremental`
151    // directive should be avoided if possible; using an incremental mode test is
152    // preferred. Incremental mode tests support multiple passes, which can
153    // verify that the incremental cache can be loaded properly after being
154    // created. Just setting the directive will only verify the behavior with
155    // creating an incremental cache, but doesn't check that it is created
156    // correctly.
157    //
158    // Compiletest will create the incremental directory, and ensure it is
159    // empty before the test starts. Incremental mode tests will reuse the
160    // incremental directory between passes in the same test.
161    pub(crate) incremental: bool,
162    // If `true`, this test is a known bug.
163    //
164    // When set, some requirements are relaxed. Currently, this only means no
165    // error annotations are needed, but this may be updated in the future to
166    // include other relaxations.
167    pub(crate) known_bug: bool,
168    // How far should the test proceed while still passing.
169    pass_mode: Option<PassMode>,
170    // Ignore `--pass` overrides from the command line for this test.
171    ignore_pass: bool,
172    // How far this test should proceed to start failing.
173    pub(crate) fail_mode: Option<FailMode>,
174    // rustdoc will test the output of the `--test` option
175    pub(crate) check_test_line_numbers_match: bool,
176    // customized normalization rules
177    pub(crate) normalize_stdout: Vec<(String, String)>,
178    pub(crate) normalize_stderr: Vec<(String, String)>,
179    pub(crate) failure_status: Option<i32>,
180    // For UI tests, allows compiler to exit with arbitrary failure status
181    pub(crate) dont_check_failure_status: bool,
182    // Whether or not `rustfix` should apply the `CodeSuggestion`s of this test and compile the
183    // resulting Rust code.
184    pub(crate) run_rustfix: bool,
185    // If true, `rustfix` will only apply `MachineApplicable` suggestions.
186    pub(crate) rustfix_only_machine_applicable: bool,
187    pub(crate) assembly_output: Option<String>,
188    // If true, the stderr is expected to be different across bit-widths.
189    pub(crate) stderr_per_bitwidth: bool,
190    // The MIR opt to unit test, if any
191    pub(crate) mir_unit_test: Option<String>,
192    // Whether to tell `rustc` to remap the "src base" directory to a fake
193    // directory.
194    pub(crate) remap_src_base: bool,
195    /// Extra flags to pass to `llvm-cov` when producing coverage reports.
196    /// Only used by the "coverage-run" test mode.
197    pub(crate) llvm_cov_flags: Vec<String>,
198    /// Don't run LLVM's `filecheck` tool to check compiler output,
199    /// in tests that would normally run it.
200    pub(crate) skip_filecheck: bool,
201    /// Extra flags to pass to LLVM's `filecheck` tool, in tests that use it.
202    pub(crate) filecheck_flags: Vec<String>,
203    /// Don't automatically insert any `--check-cfg` args
204    pub(crate) no_auto_check_cfg: bool,
205    /// Build and use `minicore` as `core` stub for `no_core` tests in cross-compilation scenarios
206    /// that don't otherwise want/need `-Z build-std`.
207    pub(crate) add_minicore: bool,
208    /// Add these flags to the build of `minicore`.
209    pub(crate) minicore_compile_flags: Vec<String>,
210    /// Whether line annotations are required for the given error kind.
211    pub(crate) dont_require_annotations: HashSet<ErrorKind>,
212    /// Whether pretty printers should be disabled in gdb.
213    pub(crate) disable_gdb_pretty_printers: bool,
214    /// Compare the output by lines, rather than as a single string.
215    pub(crate) compare_output_by_lines: bool,
216}
217
218mod directives {
219    pub(crate) const ERROR_PATTERN: &str = "error-pattern";
220    pub(crate) const REGEX_ERROR_PATTERN: &str = "regex-error-pattern";
221    pub(crate) const COMPILE_FLAGS: &str = "compile-flags";
222    pub(crate) const RUN_FLAGS: &str = "run-flags";
223    pub(crate) const DOC_FLAGS: &str = "doc-flags";
224    pub(crate) const BUILD_AUX_DOCS: &str = "build-aux-docs";
225    pub(crate) const UNIQUE_DOC_OUT_DIR: &str = "unique-doc-out-dir";
226    pub(crate) const FORCE_HOST: &str = "force-host";
227    pub(crate) const CHECK_STDOUT: &str = "check-stdout";
228    pub(crate) const CHECK_RUN_RESULTS: &str = "check-run-results";
229    pub(crate) const DONT_CHECK_COMPILER_STDOUT: &str = "dont-check-compiler-stdout";
230    pub(crate) const DONT_CHECK_COMPILER_STDERR: &str = "dont-check-compiler-stderr";
231    pub(crate) const DONT_REQUIRE_ANNOTATIONS: &str = "dont-require-annotations";
232    pub(crate) const NO_PREFER_DYNAMIC: &str = "no-prefer-dynamic";
233    pub(crate) const PRETTY_MODE: &str = "pretty-mode";
234    pub(crate) const PRETTY_COMPARE_ONLY: &str = "pretty-compare-only";
235    pub(crate) const AUX_BIN: &str = "aux-bin";
236    pub(crate) const AUX_BUILD: &str = "aux-build";
237    pub(crate) const AUX_CRATE: &str = "aux-crate";
238    pub(crate) const PROC_MACRO: &str = "proc-macro";
239    pub(crate) const AUX_CODEGEN_BACKEND: &str = "aux-codegen-backend";
240    pub(crate) const EXEC_ENV: &str = "exec-env";
241    pub(crate) const RUSTC_ENV: &str = "rustc-env";
242    pub(crate) const UNSET_EXEC_ENV: &str = "unset-exec-env";
243    pub(crate) const UNSET_RUSTC_ENV: &str = "unset-rustc-env";
244    pub(crate) const FORBID_OUTPUT: &str = "forbid-output";
245    pub(crate) const CHECK_TEST_LINE_NUMBERS_MATCH: &str = "check-test-line-numbers-match";
246    pub(crate) const IGNORE_PASS: &str = "ignore-pass";
247    pub(crate) const FAILURE_STATUS: &str = "failure-status";
248    pub(crate) const DONT_CHECK_FAILURE_STATUS: &str = "dont-check-failure-status";
249    pub(crate) const RUN_RUSTFIX: &str = "run-rustfix";
250    pub(crate) const RUSTFIX_ONLY_MACHINE_APPLICABLE: &str = "rustfix-only-machine-applicable";
251    pub(crate) const ASSEMBLY_OUTPUT: &str = "assembly-output";
252    pub(crate) const STDERR_PER_BITWIDTH: &str = "stderr-per-bitwidth";
253    pub(crate) const INCREMENTAL: &str = "incremental";
254    pub(crate) const KNOWN_BUG: &str = "known-bug";
255    pub(crate) const TEST_MIR_PASS: &str = "test-mir-pass";
256    pub(crate) const REMAP_SRC_BASE: &str = "remap-src-base";
257    pub(crate) const LLVM_COV_FLAGS: &str = "llvm-cov-flags";
258    pub(crate) const FILECHECK_FLAGS: &str = "filecheck-flags";
259    pub(crate) const NO_AUTO_CHECK_CFG: &str = "no-auto-check-cfg";
260    pub(crate) const ADD_MINICORE: &str = "add-minicore";
261    pub(crate) const MINICORE_COMPILE_FLAGS: &str = "minicore-compile-flags";
262    pub(crate) const DISABLE_GDB_PRETTY_PRINTERS: &str = "disable-gdb-pretty-printers";
263    pub(crate) const COMPARE_OUTPUT_BY_LINES: &str = "compare-output-by-lines";
264}
265
266impl TestProps {
267    pub(crate) fn new() -> Self {
268        TestProps {
269            error_patterns: vec![],
270            regex_error_patterns: vec![],
271            edition: None,
272            compile_flags: vec![],
273            run_flags: vec![],
274            doc_flags: vec![],
275            pp_exact: None,
276            aux: Default::default(),
277            revisions: vec![],
278            rustc_env: vec![
279                ("RUSTC_ICE".to_string(), "0".to_string()),
280                ("RUST_BACKTRACE".to_string(), "short".to_string()),
281            ],
282            unset_rustc_env: vec![("RUSTC_LOG_COLOR".to_string())],
283            exec_env: vec![],
284            unset_exec_env: vec![],
285            build_aux_docs: false,
286            unique_doc_out_dir: false,
287            force_host: false,
288            check_stdout: false,
289            check_run_results: false,
290            dont_check_compiler_stdout: false,
291            dont_check_compiler_stderr: false,
292            no_prefer_dynamic: false,
293            pretty_mode: "normal".to_string(),
294            pretty_compare_only: false,
295            forbid_output: vec![],
296            incremental_dir: None,
297            incremental: false,
298            known_bug: false,
299            pass_mode: None,
300            fail_mode: None,
301            ignore_pass: false,
302            check_test_line_numbers_match: false,
303            normalize_stdout: vec![],
304            normalize_stderr: vec![],
305            failure_status: None,
306            dont_check_failure_status: false,
307            run_rustfix: false,
308            rustfix_only_machine_applicable: false,
309            assembly_output: None,
310            stderr_per_bitwidth: false,
311            mir_unit_test: None,
312            remap_src_base: false,
313            llvm_cov_flags: vec![],
314            skip_filecheck: false,
315            filecheck_flags: vec![],
316            no_auto_check_cfg: false,
317            add_minicore: false,
318            minicore_compile_flags: vec![],
319            dont_require_annotations: Default::default(),
320            disable_gdb_pretty_printers: false,
321            compare_output_by_lines: false,
322        }
323    }
324
325    pub(crate) fn from_aux_file(
326        &self,
327        testfile: &Utf8Path,
328        revision: Option<&str>,
329        config: &Config,
330    ) -> Self {
331        let mut props = TestProps::new();
332
333        // copy over select properties to the aux build:
334        props.incremental_dir = self.incremental_dir.clone();
335        props.ignore_pass = true;
336        props.load_from(testfile, revision, config);
337
338        props
339    }
340
341    pub(crate) fn from_file(testfile: &Utf8Path, revision: Option<&str>, config: &Config) -> Self {
342        let mut props = TestProps::new();
343        props.load_from(testfile, revision, config);
344        props.exec_env.push(("RUSTC".to_string(), config.rustc_path.to_string()));
345
346        match (props.pass_mode, props.fail_mode) {
347            (None, None) if config.mode == TestMode::Ui => props.fail_mode = Some(FailMode::Check),
348            (Some(_), Some(_)) => panic!("cannot use a *-fail and *-pass mode together"),
349            _ => {}
350        }
351
352        props
353    }
354
355    /// Loads properties from `testfile` into `props`. If a property is
356    /// tied to a particular revision `foo` (indicated by writing
357    /// `//@[foo]`), then the property is ignored unless `test_revision` is
358    /// `Some("foo")`.
359    fn load_from(&mut self, testfile: &Utf8Path, test_revision: Option<&str>, config: &Config) {
360        if !testfile.is_dir() {
361            let file_contents = fs::read_to_string(testfile).unwrap();
362            let file_directives = FileDirectives::from_file_contents(testfile, &file_contents);
363
364            iter_directives(
365                config,
366                &file_directives,
367                // (dummy comment to force args into vertical layout)
368                &mut |ln: &DirectiveLine<'_>| {
369                    if !ln.applies_to_test_revision(test_revision) {
370                        return;
371                    }
372
373                    if let Some(handler) = DIRECTIVE_HANDLERS_MAP.get(ln.name) {
374                        handler.handle(config, ln, self);
375                    }
376                },
377            );
378        }
379
380        if config.mode == TestMode::Incremental {
381            self.incremental = true;
382        }
383
384        if config.mode == TestMode::Crashes {
385            // we don't want to pollute anything with backtrace-files
386            // also turn off backtraces in order to save some execution
387            // time on the tests; we only need to know IF it crashes
388            self.rustc_env = vec![
389                ("RUST_BACKTRACE".to_string(), "0".to_string()),
390                ("RUSTC_ICE".to_string(), "0".to_string()),
391            ];
392        }
393
394        for key in &["RUST_TEST_NOCAPTURE", "RUST_TEST_THREADS"] {
395            if let Ok(val) = env::var(key) {
396                if !self.exec_env.iter().any(|&(ref x, _)| x == key) {
397                    self.exec_env.push(((*key).to_owned(), val))
398                }
399            }
400        }
401
402        if let Some(edition) = self.edition.or(config.edition) {
403            // The edition is added at the start, since flags from //@compile-flags must be passed
404            // to rustc last.
405            self.compile_flags.insert(0, format!("--edition={edition}"));
406        }
407    }
408
409    fn update_fail_mode(&mut self, ln: &DirectiveLine<'_>, config: &Config) {
410        let check_ui = |mode: &str| {
411            if config.mode != TestMode::Ui {
412                panic!("`{}-fail` directive is only supported in UI tests", mode);
413            }
414        };
415        let fail_mode = if config.parse_name_directive(ln, "check-fail") {
416            check_ui("check");
417            Some(FailMode::Check)
418        } else if config.parse_name_directive(ln, "build-fail") {
419            check_ui("build");
420            Some(FailMode::Build)
421        } else if config.parse_name_directive(ln, "run-fail") {
422            check_ui("run");
423            Some(FailMode::Run(RunFailMode::Fail))
424        } else if config.parse_name_directive(ln, "run-crash") {
425            check_ui("run");
426            Some(FailMode::Run(RunFailMode::Crash))
427        } else if config.parse_name_directive(ln, "run-fail-or-crash") {
428            check_ui("run");
429            Some(FailMode::Run(RunFailMode::FailOrCrash))
430        } else {
431            None
432        };
433        match (self.fail_mode, fail_mode) {
434            (None, Some(_)) => self.fail_mode = fail_mode,
435            (Some(_), Some(_)) => panic!("multiple `*-fail` directives in a single test"),
436            (_, None) => {}
437        }
438    }
439
440    fn update_pass_mode(&mut self, ln: &DirectiveLine<'_>, config: &Config) {
441        let check_no_run = |s| match (config.mode, s) {
442            (TestMode::Ui, _) => (),
443            (mode, _) => panic!("`{s}` directive is not supported in `{mode}` tests"),
444        };
445        let pass_mode = if config.parse_name_directive(ln, "check-pass") {
446            check_no_run("check-pass");
447            Some(PassMode::Check)
448        } else if config.parse_name_directive(ln, "build-pass") {
449            check_no_run("build-pass");
450            Some(PassMode::Build)
451        } else if config.parse_name_directive(ln, "run-pass") {
452            check_no_run("run-pass");
453            Some(PassMode::Run)
454        } else {
455            None
456        };
457        match (self.pass_mode, pass_mode) {
458            (None, Some(_)) => self.pass_mode = pass_mode,
459            (Some(_), Some(_)) => panic!("multiple `*-pass` directives in a single test"),
460            (_, None) => {}
461        }
462    }
463
464    pub(crate) fn pass_mode(&self, config: &Config) -> Option<PassMode> {
465        if !self.ignore_pass && self.fail_mode.is_none() {
466            if let mode @ Some(_) = config.force_pass_mode {
467                return mode;
468            }
469        }
470        self.pass_mode
471    }
472
473    // does not consider CLI override for pass mode
474    pub(crate) fn local_pass_mode(&self) -> Option<PassMode> {
475        self.pass_mode
476    }
477
478    fn update_add_minicore(&mut self, ln: &DirectiveLine<'_>, config: &Config) {
479        let add_minicore = config.parse_name_directive(ln, directives::ADD_MINICORE);
480        if add_minicore {
481            if !matches!(
482                config.mode,
483                TestMode::Ui | TestMode::Codegen | TestMode::Assembly | TestMode::MirOpt
484            ) {
485                panic!(
486                    "`add-minicore` is currently only supported for ui, codegen, assembly and mir-opt test modes"
487                );
488            }
489
490            // FIXME(jieyouxu): this check is currently order-dependent, but we should probably
491            // collect all directives in one go then perform a validation pass after that.
492            if self.local_pass_mode().is_some_and(|pm| pm == PassMode::Run) {
493                // `minicore` can only be used with non-run modes, because it's `core` prelude stubs
494                // and can't run.
495                panic!("`add-minicore` cannot be used to run the test binary");
496            }
497
498            self.add_minicore = add_minicore;
499        }
500    }
501}
502
503pub(crate) fn do_early_directives_check(
504    mode: TestMode,
505    file_directives: &FileDirectives<'_>,
506) -> Result<(), String> {
507    let testfile = file_directives.path;
508
509    for directive_line @ DirectiveLine { line_number, .. } in &file_directives.lines {
510        let CheckDirectiveResult { is_known_directive, trailing_directive } =
511            check_directive(directive_line, mode);
512
513        if !is_known_directive {
514            return Err(format!(
515                "ERROR: unknown compiletest directive `{directive}` at {testfile}:{line_number}",
516                directive = directive_line.display(),
517            ));
518        }
519
520        if let Some(trailing_directive) = &trailing_directive {
521            return Err(format!(
522                "ERROR: detected trailing compiletest directive `{trailing_directive}` at {testfile}:{line_number}\n\
523                HELP: put the directive on its own line: `//@ {trailing_directive}`"
524            ));
525        }
526    }
527
528    Ok(())
529}
530
531pub(crate) struct CheckDirectiveResult<'ln> {
532    is_known_directive: bool,
533    trailing_directive: Option<&'ln str>,
534}
535
536fn check_directive<'a>(
537    directive_ln: &DirectiveLine<'a>,
538    mode: TestMode,
539) -> CheckDirectiveResult<'a> {
540    let &DirectiveLine { name: directive_name, .. } = directive_ln;
541
542    let is_known_directive = KNOWN_DIRECTIVE_NAMES_SET.contains(&directive_name)
543        || match mode {
544            TestMode::RustdocHtml => KNOWN_HTMLDOCCK_DIRECTIVE_NAMES.contains(&directive_name),
545            TestMode::RustdocJson => KNOWN_JSONDOCCK_DIRECTIVE_NAMES.contains(&directive_name),
546            _ => false,
547        };
548
549    // If it looks like the user tried to put two directives on the same line
550    // (e.g. `//@ only-linux only-x86_64`), signal an error, because the
551    // second "directive" would actually be ignored with no effect.
552    let trailing_directive = directive_ln
553        .remark_after_space()
554        .map(|remark| remark.trim_start().split(' ').next().unwrap())
555        .filter(|token| KNOWN_DIRECTIVE_NAMES_SET.contains(token));
556
557    // FIXME(Zalathar): Consider emitting specialized error/help messages for
558    // bogus directive names that are similar to real ones, e.g.:
559    // - *`compiler-flags` => `compile-flags`
560    // - *`compile-fail` => `check-fail` or `build-fail`
561
562    CheckDirectiveResult { is_known_directive, trailing_directive }
563}
564
565fn iter_directives(
566    config: &Config,
567    file_directives: &FileDirectives<'_>,
568    it: &mut dyn FnMut(&DirectiveLine<'_>),
569) {
570    let testfile = file_directives.path;
571
572    let extra_directives = match config.mode {
573        TestMode::CoverageRun => {
574            // Coverage tests in coverage-run mode always have these extra directives, without needing to
575            // specify them manually in every test file.
576            //
577            // FIXME(jieyouxu): I feel like there's a better way to do this, leaving for later.
578            vec![
579                "//@ needs-profiler-runtime",
580                // FIXME(pietroalbini): this test currently does not work on cross-compiled targets
581                // because remote-test is not capable of sending back the *.profraw files generated by
582                // the LLVM instrumentation.
583                "//@ ignore-cross-compile",
584            ]
585        }
586        TestMode::Codegen if !file_directives.has_explicit_no_std_core_attribute => {
587            // Note: affects all codegen test suites under test mode `codegen`, e.g. `codegen-llvm`.
588            //
589            // Codegen tests automatically receive implied `//@ needs-target-std`, unless
590            // `#![no_std]`/`#![no_core]` attribute was explicitly seen. The rationale is basically to avoid
591            // having to manually maintain a bunch of `//@ needs-target-std` directives esp. for targets
592            // tested/built out-of-tree.
593            vec!["//@ needs-target-std"]
594        }
595        TestMode::Ui if config.parallel_frontend_enabled() => {
596            // UI tests in parallel-frontend mode always have this extra directive, without needing to
597            // specify it manually in every test file.
598            vec!["//@ compare-output-by-lines"]
599        }
600
601        _ => {
602            // No extra directives for other test modes.
603            vec![]
604        }
605    };
606
607    for directive_str in extra_directives {
608        let directive_line = line_directive(testfile, LineNumber::ZERO, directive_str)
609            .unwrap_or_else(|| panic!("bad extra-directive line: {directive_str:?}"));
610        it(&directive_line);
611    }
612
613    for directive_line in &file_directives.lines {
614        it(directive_line);
615    }
616}
617
618impl Config {
619    fn parse_and_update_revisions(&self, line: &DirectiveLine<'_>, existing: &mut Vec<String>) {
620        const FORBIDDEN_REVISION_NAMES: [&str; 2] = [
621            // `//@ revisions: true false` Implying `--cfg=true` and `--cfg=false` makes it very
622            // weird for the test, since if the test writer wants a cfg of the same revision name
623            // they'd have to use `cfg(r#true)` and `cfg(r#false)`.
624            "true", "false",
625        ];
626
627        const FILECHECK_FORBIDDEN_REVISION_NAMES: [&str; 9] =
628            ["CHECK", "COM", "NEXT", "SAME", "EMPTY", "NOT", "COUNT", "DAG", "LABEL"];
629
630        if let Some(raw) = self.parse_name_value_directive(line, "revisions") {
631            let &DirectiveLine { file_path: testfile, .. } = line;
632
633            if self.mode == TestMode::RunMake {
634                panic!("`run-make` mode tests do not support revisions: {}", testfile);
635            }
636
637            let mut duplicates: HashSet<_> = existing.iter().cloned().collect();
638            for revision in raw.split_whitespace() {
639                if !duplicates.insert(revision.to_string()) {
640                    panic!("duplicate revision: `{}` in line `{}`: {}", revision, raw, testfile);
641                }
642
643                if FORBIDDEN_REVISION_NAMES.contains(&revision) {
644                    panic!(
645                        "revision name `{revision}` is not permitted: `{}` in line `{}`: {}",
646                        revision, raw, testfile
647                    );
648                }
649
650                if matches!(self.mode, TestMode::Assembly | TestMode::Codegen | TestMode::MirOpt)
651                    && FILECHECK_FORBIDDEN_REVISION_NAMES.contains(&revision)
652                {
653                    panic!(
654                        "revision name `{revision}` is not permitted in a test suite that uses \
655                        `FileCheck` annotations as it is confusing when used as custom `FileCheck` \
656                        prefix: `{revision}` in line `{}`: {}",
657                        raw, testfile
658                    );
659                }
660
661                existing.push(revision.to_string());
662            }
663        }
664    }
665
666    fn parse_env(nv: String) -> (String, String) {
667        // nv is either FOO or FOO=BAR
668        // FIXME(Zalathar): The form without `=` seems to be unused; should
669        // we drop support for it?
670        let (name, value) = nv.split_once('=').unwrap_or((&nv, ""));
671        // Trim whitespace from the name, so that `//@ exec-env: FOO=BAR`
672        // sees the name as `FOO` and not ` FOO`.
673        let name = name.trim();
674        (name.to_owned(), value.to_owned())
675    }
676
677    fn parse_pp_exact(&self, line: &DirectiveLine<'_>) -> Option<Utf8PathBuf> {
678        if let Some(s) = self.parse_name_value_directive(line, "pp-exact") {
679            Some(Utf8PathBuf::from(&s))
680        } else if self.parse_name_directive(line, "pp-exact") {
681            line.file_path.file_name().map(Utf8PathBuf::from)
682        } else {
683            None
684        }
685    }
686
687    fn parse_custom_normalization(&self, line: &DirectiveLine<'_>) -> Option<NormalizeRule> {
688        let &DirectiveLine { name, .. } = line;
689
690        let kind = match name {
691            "normalize-stdout" => NormalizeKind::Stdout,
692            "normalize-stderr" => NormalizeKind::Stderr,
693            "normalize-stderr-32bit" => NormalizeKind::Stderr32bit,
694            "normalize-stderr-64bit" => NormalizeKind::Stderr64bit,
695            _ => return None,
696        };
697
698        let Some((regex, replacement)) = line.value_after_colon().and_then(parse_normalize_rule)
699        else {
700            error!("couldn't parse custom normalization rule: `{}`", line.display());
701            help!("expected syntax is: `{name}: \"REGEX\" -> \"REPLACEMENT\"`");
702            panic!("invalid normalization rule detected");
703        };
704        Some(NormalizeRule { kind, regex, replacement })
705    }
706
707    fn parse_name_directive(&self, line: &DirectiveLine<'_>, directive: &str) -> bool {
708        // FIXME(Zalathar): Ideally, this should raise an error if a name-only
709        // directive is followed by a colon, since that's the wrong syntax.
710        // But we would need to fix tests that rely on the current behaviour.
711        line.name == directive
712    }
713
714    fn parse_name_value_directive(
715        &self,
716        line: &DirectiveLine<'_>,
717        directive: &str,
718    ) -> Option<String> {
719        let &DirectiveLine { file_path, line_number, .. } = line;
720
721        if line.name != directive {
722            return None;
723        };
724
725        // FIXME(Zalathar): This silently discards directives with a matching
726        // name but no colon. Unfortunately, some directives (e.g. "pp-exact")
727        // currently rely on _not_ panicking here.
728        let value = line.value_after_colon()?;
729        debug!("{}: {}", directive, value);
730        let value = expand_variables(value.to_owned(), self);
731
732        if value.is_empty() {
733            error!("{file_path}:{line_number}: empty value for directive `{directive}`");
734            help!("expected syntax is: `{directive}: value`");
735            panic!("empty directive value detected");
736        }
737
738        Some(value)
739    }
740
741    fn set_name_directive(&self, line: &DirectiveLine<'_>, directive: &str, value: &mut bool) {
742        // If the flag is already true, don't bother looking at the directive.
743        *value = *value || self.parse_name_directive(line, directive);
744    }
745
746    fn set_name_value_directive<T>(
747        &self,
748        line: &DirectiveLine<'_>,
749        directive: &str,
750        value: &mut Option<T>,
751        parse: impl FnOnce(String) -> T,
752    ) {
753        if value.is_none() {
754            *value = self.parse_name_value_directive(line, directive).map(parse);
755        }
756    }
757
758    fn push_name_value_directive<T>(
759        &self,
760        line: &DirectiveLine<'_>,
761        directive: &str,
762        values: &mut Vec<T>,
763        parse: impl FnOnce(String) -> T,
764    ) {
765        if let Some(value) = self.parse_name_value_directive(line, directive).map(parse) {
766            values.push(value);
767        }
768    }
769}
770
771// FIXME(jieyouxu): fix some of these variable names to more accurately reflect what they do.
772fn expand_variables(mut value: String, config: &Config) -> String {
773    const CWD: &str = "{{cwd}}";
774    const SRC_BASE: &str = "{{src-base}}";
775    const TEST_SUITE_BUILD_BASE: &str = "{{build-base}}";
776    const RUST_SRC_BASE: &str = "{{rust-src-base}}";
777    const SYSROOT_BASE: &str = "{{sysroot-base}}";
778    const TARGET_LINKER: &str = "{{target-linker}}";
779    const TARGET: &str = "{{target}}";
780
781    if value.contains(CWD) {
782        let cwd = env::current_dir().unwrap();
783        value = value.replace(CWD, &cwd.to_str().unwrap());
784    }
785
786    if value.contains(SRC_BASE) {
787        value = value.replace(SRC_BASE, &config.src_test_suite_root.as_str());
788    }
789
790    if value.contains(TEST_SUITE_BUILD_BASE) {
791        value = value.replace(TEST_SUITE_BUILD_BASE, &config.build_test_suite_root.as_str());
792    }
793
794    if value.contains(SYSROOT_BASE) {
795        value = value.replace(SYSROOT_BASE, &config.sysroot_base.as_str());
796    }
797
798    if value.contains(TARGET_LINKER) {
799        value = value.replace(TARGET_LINKER, config.target_linker.as_deref().unwrap_or(""));
800    }
801
802    if value.contains(TARGET) {
803        value = value.replace(TARGET, &config.target);
804    }
805
806    if value.contains(RUST_SRC_BASE) {
807        let src_base = config.sysroot_base.join("lib/rustlib/src/rust");
808        src_base.try_exists().expect(&*format!("{} should exists", src_base));
809        let src_base = src_base.read_link_utf8().unwrap_or(src_base);
810        value = value.replace(RUST_SRC_BASE, &src_base.as_str());
811    }
812
813    value
814}
815
816struct NormalizeRule {
817    kind: NormalizeKind,
818    regex: String,
819    replacement: String,
820}
821
822enum NormalizeKind {
823    Stdout,
824    Stderr,
825    Stderr32bit,
826    Stderr64bit,
827}
828
829/// Parses the regex and replacement values of a `//@ normalize-*` directive, in the format:
830/// ```text
831/// "REGEX" -> "REPLACEMENT"
832/// ```
833fn parse_normalize_rule(raw_value: &str) -> Option<(String, String)> {
834    // FIXME: Support escaped double-quotes in strings.
835    let captures = static_regex!(
836        r#"(?x) # (verbose mode regex)
837        ^
838        \s*                     # (leading whitespace)
839        "(?<regex>[^"]*)"       # "REGEX"
840        \s+->\s+                # ->
841        "(?<replacement>[^"]*)" # "REPLACEMENT"
842        $
843        "#
844    )
845    .captures(raw_value)?;
846    let regex = captures["regex"].to_owned();
847    let replacement = captures["replacement"].to_owned();
848    // A `\n` sequence in the replacement becomes an actual newline.
849    // FIXME: Do unescaping in a less ad-hoc way, and perhaps support escaped
850    // backslashes and double-quotes.
851    let replacement = replacement.replace("\\n", "\n");
852    Some((regex, replacement))
853}
854
855/// Given an llvm version string that looks like `1.2.3-rc1`, extract as semver. Note that this
856/// accepts more than just strict `semver` syntax (as in `major.minor.patch`); this permits omitting
857/// minor and patch version components so users can write e.g. `//@ min-llvm-version: 19` instead of
858/// having to write `//@ min-llvm-version: 19.0.0`.
859///
860/// Currently panics if the input string is malformed, though we really should not use panic as an
861/// error handling strategy.
862///
863/// FIXME(jieyouxu): improve error handling
864pub(crate) fn extract_llvm_version(version: &str) -> Version {
865    // The version substring we're interested in usually looks like the `1.2.3`, without any of the
866    // fancy suffix like `-rc1` or `meow`.
867    let version = version.trim();
868    let uninterested = |c: char| !c.is_ascii_digit() && c != '.';
869    let version_without_suffix = match version.split_once(uninterested) {
870        Some((prefix, _suffix)) => prefix,
871        None => version,
872    };
873
874    let components: Vec<u64> = version_without_suffix
875        .split('.')
876        .map(|s| s.parse().expect("llvm version component should consist of only digits"))
877        .collect();
878
879    match &components[..] {
880        [major] => Version::new(*major, 0, 0),
881        [major, minor] => Version::new(*major, *minor, 0),
882        [major, minor, patch] => Version::new(*major, *minor, *patch),
883        _ => panic!("malformed llvm version string, expected only 1-3 components: {version}"),
884    }
885}
886
887pub(crate) fn extract_llvm_version_from_binary(binary_path: &str) -> Option<Version> {
888    let output = Command::new(binary_path).arg("--version").output().ok()?;
889    if !output.status.success() {
890        return None;
891    }
892    let version = String::from_utf8(output.stdout).ok()?;
893    for line in version.lines() {
894        if let Some(version) = line.split("LLVM version ").nth(1) {
895            return Some(extract_llvm_version(version));
896        }
897    }
898    None
899}
900
901/// Takes a directive of the form `"<version1> [- <version2>]"`, returns the numeric representation
902/// of `<version1>` and `<version2>` as tuple: `(<version1>, <version2>)`.
903///
904/// If the `<version2>` part is omitted, the second component of the tuple is the same as
905/// `<version1>`.
906fn extract_version_range<'a, F, VersionTy: Clone>(
907    line: &'a str,
908    parse: F,
909) -> Option<(VersionTy, VersionTy)>
910where
911    F: Fn(&'a str) -> Option<VersionTy>,
912{
913    let mut splits = line.splitn(2, "- ").map(str::trim);
914    let min = splits.next().unwrap();
915    if min.ends_with('-') {
916        return None;
917    }
918
919    let max = splits.next();
920
921    if min.is_empty() {
922        return None;
923    }
924
925    let min = parse(min)?;
926    let max = match max {
927        Some("") => return None,
928        Some(max) => parse(max)?,
929        _ => min.clone(),
930    };
931
932    Some((min, max))
933}
934
935pub(crate) fn make_test_description(
936    config: &Config,
937    cache: &DirectivesCache,
938    name: String,
939    path: &Utf8Path,
940    filterable_path: &Utf8Path,
941    file_directives: &FileDirectives<'_>,
942    test_revision: Option<&str>,
943    poisoned: &mut bool,
944    aux_props: &mut AuxProps,
945) -> CollectedTestDesc {
946    let mut ignore = false;
947    let mut ignore_message = None;
948    let mut should_fail = false;
949
950    // Scan through the test file to handle `ignore-*`, `only-*`, and `needs-*` directives.
951    iter_directives(config, file_directives, &mut |ln @ &DirectiveLine { line_number, .. }| {
952        if !ln.applies_to_test_revision(test_revision) {
953            return;
954        }
955
956        // Parse `aux-*` directives, for use by up-to-date checks.
957        parse_and_update_aux(config, ln, aux_props);
958
959        macro_rules! decision {
960            ($e:expr) => {
961                match $e {
962                    IgnoreDecision::Ignore { reason } => {
963                        ignore = true;
964                        ignore_message = Some(reason.into());
965                    }
966                    IgnoreDecision::Error { message } => {
967                        error!("{path}:{line_number}: {message}");
968                        *poisoned = true;
969                        return;
970                    }
971                    IgnoreDecision::Continue => {}
972                }
973            };
974        }
975
976        decision!(cfg::handle_ignore(&cache.cfg_conditions, ln));
977        decision!(cfg::handle_only(&cache.cfg_conditions, ln));
978        decision!(needs::handle_needs(&cache.needs, config, ln));
979        decision!(ignore_llvm(config, ln));
980        decision!(ignore_backends(config, ln));
981        decision!(needs_backends(config, ln));
982        decision!(ignore_cdb(config, ln));
983        decision!(ignore_gdb(config, ln));
984        decision!(ignore_lldb(config, ln));
985        decision!(ignore_parallel_frontend(config, ln));
986
987        if config.target == "wasm32-unknown-unknown"
988            && config.parse_name_directive(ln, directives::CHECK_RUN_RESULTS)
989        {
990            decision!(IgnoreDecision::Ignore {
991                reason: "ignored on WASM as the run results cannot be checked there".into(),
992            });
993        }
994
995        should_fail |= config.parse_name_directive(ln, "should-fail");
996    });
997
998    // The `should-fail` annotation doesn't apply to pretty tests,
999    // since we run the pretty printer across all tests by default.
1000    // If desired, we could add a `should-fail-pretty` annotation.
1001    let should_fail = if should_fail && config.mode != TestMode::Pretty {
1002        ShouldFail::Yes
1003    } else {
1004        ShouldFail::No
1005    };
1006
1007    CollectedTestDesc {
1008        name,
1009        filterable_path: filterable_path.to_owned(),
1010        ignore,
1011        ignore_message,
1012        should_fail,
1013    }
1014}
1015
1016fn ignore_cdb(config: &Config, line: &DirectiveLine<'_>) -> IgnoreDecision {
1017    if config.debugger != Some(Debugger::Cdb) {
1018        return IgnoreDecision::Continue;
1019    }
1020
1021    if let Some(actual_version) = config.cdb_version {
1022        if line.name == "min-cdb-version"
1023            && let Some(rest) = line.value_after_colon().map(str::trim)
1024        {
1025            let min_version = extract_cdb_version(rest).unwrap_or_else(|| {
1026                panic!("couldn't parse version range: {:?}", rest);
1027            });
1028
1029            // Ignore if actual version is smaller than the minimum
1030            // required version
1031            if actual_version < min_version {
1032                return IgnoreDecision::Ignore {
1033                    reason: format!("ignored when the CDB version is lower than {rest}"),
1034                };
1035            }
1036        }
1037    }
1038    IgnoreDecision::Continue
1039}
1040
1041fn ignore_gdb(config: &Config, line: &DirectiveLine<'_>) -> IgnoreDecision {
1042    if config.debugger != Some(Debugger::Gdb) {
1043        return IgnoreDecision::Continue;
1044    }
1045
1046    if let Some(actual_version) = config.gdb_version {
1047        if line.name == "min-gdb-version"
1048            && let Some(rest) = line.value_after_colon().map(str::trim)
1049        {
1050            let (start_ver, end_ver) = extract_version_range(rest, extract_gdb_version)
1051                .unwrap_or_else(|| {
1052                    panic!("couldn't parse version range: {:?}", rest);
1053                });
1054
1055            if start_ver != end_ver {
1056                panic!("Expected single GDB version")
1057            }
1058            // Ignore if actual version is smaller than the minimum
1059            // required version
1060            if actual_version < start_ver {
1061                return IgnoreDecision::Ignore {
1062                    reason: format!("ignored when the GDB version is lower than {rest}"),
1063                };
1064            }
1065        } else if line.name == "ignore-gdb-version"
1066            && let Some(rest) = line.value_after_colon().map(str::trim)
1067        {
1068            let (min_version, max_version) = extract_version_range(rest, extract_gdb_version)
1069                .unwrap_or_else(|| {
1070                    panic!("couldn't parse version range: {:?}", rest);
1071                });
1072
1073            if max_version < min_version {
1074                panic!("Malformed GDB version range: max < min")
1075            }
1076
1077            if actual_version >= min_version && actual_version <= max_version {
1078                if min_version == max_version {
1079                    return IgnoreDecision::Ignore {
1080                        reason: format!("ignored when the GDB version is {rest}"),
1081                    };
1082                } else {
1083                    return IgnoreDecision::Ignore {
1084                        reason: format!("ignored when the GDB version is between {rest}"),
1085                    };
1086                }
1087            }
1088        }
1089    }
1090    IgnoreDecision::Continue
1091}
1092
1093fn ignore_lldb(config: &Config, line: &DirectiveLine<'_>) -> IgnoreDecision {
1094    if config.debugger != Some(Debugger::Lldb) {
1095        return IgnoreDecision::Continue;
1096    }
1097
1098    if let Some(actual_version) = config.lldb_version {
1099        if line.name == "min-lldb-version"
1100            && let Some(rest) = line.value_after_colon().map(str::trim)
1101        {
1102            let min_version = rest.parse().unwrap_or_else(|e| {
1103                panic!("Unexpected format of LLDB version string: {}\n{:?}", rest, e);
1104            });
1105            // Ignore if actual version is smaller the minimum required
1106            // version
1107            if actual_version < min_version {
1108                return IgnoreDecision::Ignore {
1109                    reason: format!("ignored when the LLDB version is {rest}"),
1110                };
1111            }
1112        }
1113    }
1114    IgnoreDecision::Continue
1115}
1116
1117fn ignore_backends(config: &Config, line: &DirectiveLine<'_>) -> IgnoreDecision {
1118    let path = line.file_path;
1119    if let Some(backends_to_ignore) = config.parse_name_value_directive(line, "ignore-backends") {
1120        for backend in backends_to_ignore.split_whitespace().map(|backend| {
1121            match CodegenBackend::try_from(backend) {
1122                Ok(backend) => backend,
1123                Err(error) => {
1124                    panic!("Invalid ignore-backends value `{backend}` in `{path}`: {error}")
1125                }
1126            }
1127        }) {
1128            if !config.bypass_ignore_backends && config.default_codegen_backend == backend {
1129                return IgnoreDecision::Ignore {
1130                    reason: format!("{} backend is marked as ignore", backend.as_str()),
1131                };
1132            }
1133        }
1134    }
1135    IgnoreDecision::Continue
1136}
1137
1138fn needs_backends(config: &Config, line: &DirectiveLine<'_>) -> IgnoreDecision {
1139    let path = line.file_path;
1140    if let Some(needed_backends) = config.parse_name_value_directive(line, "needs-backends") {
1141        if !needed_backends
1142            .split_whitespace()
1143            .map(|backend| match CodegenBackend::try_from(backend) {
1144                Ok(backend) => backend,
1145                Err(error) => {
1146                    panic!("Invalid needs-backends value `{backend}` in `{path}`: {error}")
1147                }
1148            })
1149            .any(|backend| config.default_codegen_backend == backend)
1150        {
1151            return IgnoreDecision::Ignore {
1152                reason: format!(
1153                    "{} backend is not part of required backends",
1154                    config.default_codegen_backend.as_str()
1155                ),
1156            };
1157        }
1158    }
1159    IgnoreDecision::Continue
1160}
1161
1162fn ignore_llvm(config: &Config, line: &DirectiveLine<'_>) -> IgnoreDecision {
1163    let path = line.file_path;
1164    if let Some(needed_components) =
1165        config.parse_name_value_directive(line, "needs-llvm-components")
1166    {
1167        let components: HashSet<_> = config.llvm_components.split_whitespace().collect();
1168        if let Some(missing_component) = needed_components
1169            .split_whitespace()
1170            .find(|needed_component| !components.contains(needed_component))
1171        {
1172            if env::var_os("COMPILETEST_REQUIRE_ALL_LLVM_COMPONENTS").is_some() {
1173                panic!(
1174                    "missing LLVM component {missing_component}, \
1175                    and COMPILETEST_REQUIRE_ALL_LLVM_COMPONENTS is set: {path}",
1176                );
1177            }
1178            return IgnoreDecision::Ignore {
1179                reason: format!("ignored when the {missing_component} LLVM component is missing"),
1180            };
1181        }
1182    }
1183    if let Some(actual_version) = &config.llvm_version {
1184        // Note that these `min` versions will check for not just major versions.
1185
1186        if let Some(version_string) = config.parse_name_value_directive(line, "min-llvm-version") {
1187            let min_version = extract_llvm_version(&version_string);
1188            // Ignore if actual version is smaller than the minimum required version.
1189            if *actual_version < min_version {
1190                return IgnoreDecision::Ignore {
1191                    reason: format!(
1192                        "ignored when the LLVM version {actual_version} is older than {min_version}"
1193                    ),
1194                };
1195            }
1196        } else if let Some(version_string) =
1197            config.parse_name_value_directive(line, "max-llvm-major-version")
1198        {
1199            let max_version = extract_llvm_version(&version_string);
1200            // Ignore if actual major version is larger than the maximum required major version.
1201            if actual_version.major > max_version.major {
1202                return IgnoreDecision::Ignore {
1203                    reason: format!(
1204                        "ignored when the LLVM version ({actual_version}) is newer than major\
1205                        version {}",
1206                        max_version.major
1207                    ),
1208                };
1209            }
1210        } else if let Some(version_string) =
1211            config.parse_name_value_directive(line, "min-system-llvm-version")
1212        {
1213            let min_version = extract_llvm_version(&version_string);
1214            // Ignore if using system LLVM and actual version
1215            // is smaller the minimum required version
1216            if config.system_llvm && *actual_version < min_version {
1217                return IgnoreDecision::Ignore {
1218                    reason: format!(
1219                        "ignored when the system LLVM version {actual_version} is older than {min_version}"
1220                    ),
1221                };
1222            }
1223        } else if let Some(version_range) =
1224            config.parse_name_value_directive(line, "ignore-llvm-version")
1225        {
1226            // Syntax is: "ignore-llvm-version: <version1> [- <version2>]"
1227            let (v_min, v_max) =
1228                extract_version_range(&version_range, |s| Some(extract_llvm_version(s)))
1229                    .unwrap_or_else(|| {
1230                        panic!("couldn't parse version range: \"{version_range}\"");
1231                    });
1232            if v_max < v_min {
1233                panic!("malformed LLVM version range where {v_max} < {v_min}")
1234            }
1235            // Ignore if version lies inside of range.
1236            if *actual_version >= v_min && *actual_version <= v_max {
1237                if v_min == v_max {
1238                    return IgnoreDecision::Ignore {
1239                        reason: format!("ignored when the LLVM version is {actual_version}"),
1240                    };
1241                } else {
1242                    return IgnoreDecision::Ignore {
1243                        reason: format!(
1244                            "ignored when the LLVM version is between {v_min} and {v_max}"
1245                        ),
1246                    };
1247                }
1248            }
1249        } else if let Some(version_string) =
1250            config.parse_name_value_directive(line, "exact-llvm-major-version")
1251        {
1252            // Syntax is "exact-llvm-major-version: <version>"
1253            let version = extract_llvm_version(&version_string);
1254            if actual_version.major != version.major {
1255                return IgnoreDecision::Ignore {
1256                    reason: format!(
1257                        "ignored when the actual LLVM major version is {}, but the test only targets major version {}",
1258                        actual_version.major, version.major
1259                    ),
1260                };
1261            }
1262        }
1263    }
1264    IgnoreDecision::Continue
1265}
1266
1267fn ignore_parallel_frontend(config: &Config, line: &DirectiveLine<'_>) -> IgnoreDecision {
1268    if config.parallel_frontend_enabled()
1269        && config.parse_name_directive(line, "ignore-parallel-frontend")
1270    {
1271        return IgnoreDecision::Ignore {
1272            reason: "ignored when the parallel frontend is enabled".into(),
1273        };
1274    }
1275    IgnoreDecision::Continue
1276}
1277
1278enum IgnoreDecision {
1279    Ignore { reason: String },
1280    Continue,
1281    Error { message: String },
1282}
1283
1284fn parse_edition_range(config: &Config, line: &DirectiveLine<'_>) -> Option<EditionRange> {
1285    let raw = config.parse_name_value_directive(line, "edition")?;
1286    let &DirectiveLine { file_path: testfile, line_number, .. } = line;
1287
1288    // Edition range is half-open: `[lower_bound, upper_bound)`
1289    if let Some((lower_bound, upper_bound)) = raw.split_once("..") {
1290        Some(match (maybe_parse_edition(lower_bound), maybe_parse_edition(upper_bound)) {
1291            (Some(lower_bound), Some(upper_bound)) if upper_bound <= lower_bound => {
1292                fatal!(
1293                    "{testfile}:{line_number}: the left side of `//@ edition` cannot be greater than or equal to the right side"
1294                );
1295            }
1296            (Some(lower_bound), Some(upper_bound)) => {
1297                EditionRange::Range { lower_bound, upper_bound }
1298            }
1299            (Some(lower_bound), None) => EditionRange::RangeFrom(lower_bound),
1300            (None, Some(_)) => {
1301                fatal!(
1302                    "{testfile}:{line_number}: `..edition` is not a supported range in `//@ edition`"
1303                );
1304            }
1305            (None, None) => {
1306                fatal!("{testfile}:{line_number}: `..` is not a supported range in `//@ edition`");
1307            }
1308        })
1309    } else {
1310        match maybe_parse_edition(&raw) {
1311            Some(edition) => Some(EditionRange::Exact(edition)),
1312            None => {
1313                fatal!("{testfile}:{line_number}: empty value for `//@ edition`");
1314            }
1315        }
1316    }
1317}
1318
1319fn maybe_parse_edition(mut input: &str) -> Option<Edition> {
1320    input = input.trim();
1321    if input.is_empty() {
1322        return None;
1323    }
1324    Some(parse_edition(input))
1325}
1326
1327#[derive(Debug, PartialEq, Eq, Clone, Copy)]
1328enum EditionRange {
1329    Exact(Edition),
1330    RangeFrom(Edition),
1331    /// Half-open range: `[lower_bound, upper_bound)`
1332    Range {
1333        lower_bound: Edition,
1334        upper_bound: Edition,
1335    },
1336}
1337
1338impl EditionRange {
1339    fn edition_to_test(&self, requested: impl Into<Option<Edition>>) -> Edition {
1340        let min_edition = Edition::Year(2015);
1341        let requested = requested.into().unwrap_or(min_edition);
1342
1343        match *self {
1344            EditionRange::Exact(exact) => exact,
1345            EditionRange::RangeFrom(lower_bound) => {
1346                if requested >= lower_bound {
1347                    requested
1348                } else {
1349                    lower_bound
1350                }
1351            }
1352            EditionRange::Range { lower_bound, upper_bound } => {
1353                if requested >= lower_bound && requested < upper_bound {
1354                    requested
1355                } else {
1356                    lower_bound
1357                }
1358            }
1359        }
1360    }
1361}
1362
1363fn split_flags(flags: &str) -> Vec<String> {
1364    // Individual flags can be single-quoted to preserve spaces; see
1365    // <https://github.com/rust-lang/rust/pull/115948/commits/957c5db6>.
1366    // FIXME(#147955): Replace this ad-hoc quoting with an escape/quote system that
1367    // is closer to what actual shells do, so that it's more flexible and familiar.
1368    flags
1369        .split('\'')
1370        .enumerate()
1371        .flat_map(|(i, f)| if i % 2 == 1 { vec![f] } else { f.split_whitespace().collect() })
1372        .map(move |s| s.to_owned())
1373        .collect::<Vec<_>>()
1374}