Skip to main content

compiletest/
directives.rs

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