compiletest/
header.rs

1use std::collections::HashSet;
2use std::env;
3use std::fs::File;
4use std::io::BufReader;
5use std::io::prelude::*;
6use std::process::Command;
7
8use camino::{Utf8Path, Utf8PathBuf};
9use semver::Version;
10use tracing::*;
11
12use crate::common::{Config, Debugger, FailMode, Mode, PassMode};
13use crate::debuggers::{extract_cdb_version, extract_gdb_version};
14use crate::errors::ErrorKind;
15use crate::executor::{CollectedTestDesc, ShouldPanic};
16use crate::header::auxiliary::{AuxProps, parse_and_update_aux};
17use crate::header::needs::CachedNeedsConditions;
18use crate::util::static_regex;
19
20pub(crate) mod auxiliary;
21mod cfg;
22mod needs;
23#[cfg(test)]
24mod tests;
25
26pub struct HeadersCache {
27    needs: CachedNeedsConditions,
28}
29
30impl HeadersCache {
31    pub fn load(config: &Config) -> Self {
32        Self { needs: CachedNeedsConditions::load(config) }
33    }
34}
35
36/// Properties which must be known very early, before actually running
37/// the test.
38#[derive(Default)]
39pub struct EarlyProps {
40    /// Auxiliary crates that should be built and made available to this test.
41    /// Included in [`EarlyProps`] so that the indicated files can participate
42    /// in up-to-date checking. Building happens via [`TestProps::aux`] instead.
43    pub(crate) aux: AuxProps,
44    pub revisions: Vec<String>,
45}
46
47impl EarlyProps {
48    pub fn from_file(config: &Config, testfile: &Utf8Path) -> Self {
49        let file = File::open(testfile.as_std_path()).expect("open test file to parse earlyprops");
50        Self::from_reader(config, testfile, file)
51    }
52
53    pub fn from_reader<R: Read>(config: &Config, testfile: &Utf8Path, rdr: R) -> Self {
54        let mut props = EarlyProps::default();
55        let mut poisoned = false;
56        iter_header(
57            config.mode,
58            &config.suite,
59            &mut poisoned,
60            testfile,
61            rdr,
62            &mut |DirectiveLine { raw_directive: ln, .. }| {
63                parse_and_update_aux(config, ln, &mut props.aux);
64                config.parse_and_update_revisions(testfile, ln, &mut props.revisions);
65            },
66        );
67
68        if poisoned {
69            eprintln!("errors encountered during EarlyProps parsing: {}", testfile);
70            panic!("errors encountered during EarlyProps parsing");
71        }
72
73        props
74    }
75}
76
77#[derive(Clone, Debug)]
78pub struct TestProps {
79    // Lines that should be expected, in order, on standard out
80    pub error_patterns: Vec<String>,
81    // Regexes that should be expected, in order, on standard out
82    pub regex_error_patterns: Vec<String>,
83    // Extra flags to pass to the compiler
84    pub compile_flags: Vec<String>,
85    // Extra flags to pass when the compiled code is run (such as --bench)
86    pub run_flags: Vec<String>,
87    /// Extra flags to pass to rustdoc but not the compiler.
88    pub doc_flags: Vec<String>,
89    // If present, the name of a file that this test should match when
90    // pretty-printed
91    pub pp_exact: Option<Utf8PathBuf>,
92    /// Auxiliary crates that should be built and made available to this test.
93    pub(crate) aux: AuxProps,
94    // Environment settings to use for compiling
95    pub rustc_env: Vec<(String, String)>,
96    // Environment variables to unset prior to compiling.
97    // Variables are unset before applying 'rustc_env'.
98    pub unset_rustc_env: Vec<String>,
99    // Environment settings to use during execution
100    pub exec_env: Vec<(String, String)>,
101    // Environment variables to unset prior to execution.
102    // Variables are unset before applying 'exec_env'
103    pub unset_exec_env: Vec<String>,
104    // Build documentation for all specified aux-builds as well
105    pub build_aux_docs: bool,
106    /// Build the documentation for each crate in a unique output directory.
107    /// Uses `<root output directory>/docs/<test name>/doc`.
108    pub unique_doc_out_dir: bool,
109    // Flag to force a crate to be built with the host architecture
110    pub force_host: bool,
111    // Check stdout for error-pattern output as well as stderr
112    pub check_stdout: bool,
113    // Check stdout & stderr for output of run-pass test
114    pub check_run_results: bool,
115    // For UI tests, allows compiler to generate arbitrary output to stdout
116    pub dont_check_compiler_stdout: bool,
117    // For UI tests, allows compiler to generate arbitrary output to stderr
118    pub dont_check_compiler_stderr: bool,
119    // Don't force a --crate-type=dylib flag on the command line
120    //
121    // Set this for example if you have an auxiliary test file that contains
122    // a proc-macro and needs `#![crate_type = "proc-macro"]`. This ensures
123    // that the aux file is compiled as a `proc-macro` and not as a `dylib`.
124    pub no_prefer_dynamic: bool,
125    // Which pretty mode are we testing with, default to 'normal'
126    pub pretty_mode: String,
127    // Only compare pretty output and don't try compiling
128    pub pretty_compare_only: bool,
129    // Patterns which must not appear in the output of a cfail test.
130    pub forbid_output: Vec<String>,
131    // Revisions to test for incremental compilation.
132    pub revisions: Vec<String>,
133    // Directory (if any) to use for incremental compilation.  This is
134    // not set by end-users; rather it is set by the incremental
135    // testing harness and used when generating compilation
136    // arguments. (In particular, it propagates to the aux-builds.)
137    pub incremental_dir: Option<Utf8PathBuf>,
138    // If `true`, this test will use incremental compilation.
139    //
140    // This can be set manually with the `incremental` header, or implicitly
141    // by being a part of an incremental mode test. Using the `incremental`
142    // header should be avoided if possible; using an incremental mode test is
143    // preferred. Incremental mode tests support multiple passes, which can
144    // verify that the incremental cache can be loaded properly after being
145    // created. Just setting the header will only verify the behavior with
146    // creating an incremental cache, but doesn't check that it is created
147    // correctly.
148    //
149    // Compiletest will create the incremental directory, and ensure it is
150    // empty before the test starts. Incremental mode tests will reuse the
151    // incremental directory between passes in the same test.
152    pub incremental: bool,
153    // If `true`, this test is a known bug.
154    //
155    // When set, some requirements are relaxed. Currently, this only means no
156    // error annotations are needed, but this may be updated in the future to
157    // include other relaxations.
158    pub known_bug: bool,
159    // How far should the test proceed while still passing.
160    pass_mode: Option<PassMode>,
161    // Ignore `--pass` overrides from the command line for this test.
162    ignore_pass: bool,
163    // How far this test should proceed to start failing.
164    pub fail_mode: Option<FailMode>,
165    // rustdoc will test the output of the `--test` option
166    pub check_test_line_numbers_match: bool,
167    // customized normalization rules
168    pub normalize_stdout: Vec<(String, String)>,
169    pub normalize_stderr: Vec<(String, String)>,
170    pub failure_status: Option<i32>,
171    // For UI tests, allows compiler to exit with arbitrary failure status
172    pub dont_check_failure_status: bool,
173    // Whether or not `rustfix` should apply the `CodeSuggestion`s of this test and compile the
174    // resulting Rust code.
175    pub run_rustfix: bool,
176    // If true, `rustfix` will only apply `MachineApplicable` suggestions.
177    pub rustfix_only_machine_applicable: bool,
178    pub assembly_output: Option<String>,
179    // If true, the test is expected to ICE
180    pub should_ice: bool,
181    // If true, the stderr is expected to be different across bit-widths.
182    pub stderr_per_bitwidth: bool,
183    // The MIR opt to unit test, if any
184    pub mir_unit_test: Option<String>,
185    // Whether to tell `rustc` to remap the "src base" directory to a fake
186    // directory.
187    pub remap_src_base: bool,
188    /// Extra flags to pass to `llvm-cov` when producing coverage reports.
189    /// Only used by the "coverage-run" test mode.
190    pub llvm_cov_flags: Vec<String>,
191    /// Extra flags to pass to LLVM's `filecheck` tool, in tests that use it.
192    pub filecheck_flags: Vec<String>,
193    /// Don't automatically insert any `--check-cfg` args
194    pub no_auto_check_cfg: bool,
195    /// Run tests which require enzyme being build
196    pub has_enzyme: bool,
197    /// Build and use `minicore` as `core` stub for `no_core` tests in cross-compilation scenarios
198    /// that don't otherwise want/need `-Z build-std`.
199    pub add_core_stubs: bool,
200    /// Whether line annotatins are required for the given error kind.
201    pub dont_require_annotations: HashSet<ErrorKind>,
202}
203
204mod directives {
205    pub const ERROR_PATTERN: &'static str = "error-pattern";
206    pub const REGEX_ERROR_PATTERN: &'static str = "regex-error-pattern";
207    pub const COMPILE_FLAGS: &'static str = "compile-flags";
208    pub const RUN_FLAGS: &'static str = "run-flags";
209    pub const DOC_FLAGS: &'static str = "doc-flags";
210    pub const SHOULD_ICE: &'static str = "should-ice";
211    pub const BUILD_AUX_DOCS: &'static str = "build-aux-docs";
212    pub const UNIQUE_DOC_OUT_DIR: &'static str = "unique-doc-out-dir";
213    pub const FORCE_HOST: &'static str = "force-host";
214    pub const CHECK_STDOUT: &'static str = "check-stdout";
215    pub const CHECK_RUN_RESULTS: &'static str = "check-run-results";
216    pub const DONT_CHECK_COMPILER_STDOUT: &'static str = "dont-check-compiler-stdout";
217    pub const DONT_CHECK_COMPILER_STDERR: &'static str = "dont-check-compiler-stderr";
218    pub const DONT_REQUIRE_ANNOTATIONS: &'static str = "dont-require-annotations";
219    pub const NO_PREFER_DYNAMIC: &'static str = "no-prefer-dynamic";
220    pub const PRETTY_MODE: &'static str = "pretty-mode";
221    pub const PRETTY_COMPARE_ONLY: &'static str = "pretty-compare-only";
222    pub const AUX_BIN: &'static str = "aux-bin";
223    pub const AUX_BUILD: &'static str = "aux-build";
224    pub const AUX_CRATE: &'static str = "aux-crate";
225    pub const PROC_MACRO: &'static str = "proc-macro";
226    pub const AUX_CODEGEN_BACKEND: &'static str = "aux-codegen-backend";
227    pub const EXEC_ENV: &'static str = "exec-env";
228    pub const RUSTC_ENV: &'static str = "rustc-env";
229    pub const UNSET_EXEC_ENV: &'static str = "unset-exec-env";
230    pub const UNSET_RUSTC_ENV: &'static str = "unset-rustc-env";
231    pub const FORBID_OUTPUT: &'static str = "forbid-output";
232    pub const CHECK_TEST_LINE_NUMBERS_MATCH: &'static str = "check-test-line-numbers-match";
233    pub const IGNORE_PASS: &'static str = "ignore-pass";
234    pub const FAILURE_STATUS: &'static str = "failure-status";
235    pub const DONT_CHECK_FAILURE_STATUS: &'static str = "dont-check-failure-status";
236    pub const RUN_RUSTFIX: &'static str = "run-rustfix";
237    pub const RUSTFIX_ONLY_MACHINE_APPLICABLE: &'static str = "rustfix-only-machine-applicable";
238    pub const ASSEMBLY_OUTPUT: &'static str = "assembly-output";
239    pub const STDERR_PER_BITWIDTH: &'static str = "stderr-per-bitwidth";
240    pub const INCREMENTAL: &'static str = "incremental";
241    pub const KNOWN_BUG: &'static str = "known-bug";
242    pub const TEST_MIR_PASS: &'static str = "test-mir-pass";
243    pub const REMAP_SRC_BASE: &'static str = "remap-src-base";
244    pub const LLVM_COV_FLAGS: &'static str = "llvm-cov-flags";
245    pub const FILECHECK_FLAGS: &'static str = "filecheck-flags";
246    pub const NO_AUTO_CHECK_CFG: &'static str = "no-auto-check-cfg";
247    pub const ADD_CORE_STUBS: &'static str = "add-core-stubs";
248    // This isn't a real directive, just one that is probably mistyped often
249    pub const INCORRECT_COMPILER_FLAGS: &'static str = "compiler-flags";
250}
251
252impl TestProps {
253    pub fn new() -> Self {
254        TestProps {
255            error_patterns: vec![],
256            regex_error_patterns: vec![],
257            compile_flags: vec![],
258            run_flags: vec![],
259            doc_flags: vec![],
260            pp_exact: None,
261            aux: Default::default(),
262            revisions: vec![],
263            rustc_env: vec![
264                ("RUSTC_ICE".to_string(), "0".to_string()),
265                ("RUST_BACKTRACE".to_string(), "short".to_string()),
266            ],
267            unset_rustc_env: vec![("RUSTC_LOG_COLOR".to_string())],
268            exec_env: vec![],
269            unset_exec_env: vec![],
270            build_aux_docs: false,
271            unique_doc_out_dir: false,
272            force_host: false,
273            check_stdout: false,
274            check_run_results: false,
275            dont_check_compiler_stdout: false,
276            dont_check_compiler_stderr: false,
277            no_prefer_dynamic: false,
278            pretty_mode: "normal".to_string(),
279            pretty_compare_only: false,
280            forbid_output: vec![],
281            incremental_dir: None,
282            incremental: false,
283            known_bug: false,
284            pass_mode: None,
285            fail_mode: None,
286            ignore_pass: false,
287            check_test_line_numbers_match: false,
288            normalize_stdout: vec![],
289            normalize_stderr: vec![],
290            failure_status: None,
291            dont_check_failure_status: false,
292            run_rustfix: false,
293            rustfix_only_machine_applicable: false,
294            assembly_output: None,
295            should_ice: false,
296            stderr_per_bitwidth: false,
297            mir_unit_test: None,
298            remap_src_base: false,
299            llvm_cov_flags: vec![],
300            filecheck_flags: vec![],
301            no_auto_check_cfg: false,
302            has_enzyme: false,
303            add_core_stubs: false,
304            dont_require_annotations: Default::default(),
305        }
306    }
307
308    pub fn from_aux_file(
309        &self,
310        testfile: &Utf8Path,
311        revision: Option<&str>,
312        config: &Config,
313    ) -> Self {
314        let mut props = TestProps::new();
315
316        // copy over select properties to the aux build:
317        props.incremental_dir = self.incremental_dir.clone();
318        props.ignore_pass = true;
319        props.load_from(testfile, revision, config);
320
321        props
322    }
323
324    pub fn from_file(testfile: &Utf8Path, revision: Option<&str>, config: &Config) -> Self {
325        let mut props = TestProps::new();
326        props.load_from(testfile, revision, config);
327        props.exec_env.push(("RUSTC".to_string(), config.rustc_path.to_string()));
328
329        match (props.pass_mode, props.fail_mode) {
330            (None, None) if config.mode == Mode::Ui => props.fail_mode = Some(FailMode::Check),
331            (Some(_), Some(_)) => panic!("cannot use a *-fail and *-pass mode together"),
332            _ => {}
333        }
334
335        props
336    }
337
338    /// Loads properties from `testfile` into `props`. If a property is
339    /// tied to a particular revision `foo` (indicated by writing
340    /// `//@[foo]`), then the property is ignored unless `test_revision` is
341    /// `Some("foo")`.
342    fn load_from(&mut self, testfile: &Utf8Path, test_revision: Option<&str>, config: &Config) {
343        let mut has_edition = false;
344        if !testfile.is_dir() {
345            let file = File::open(testfile.as_std_path()).unwrap();
346
347            let mut poisoned = false;
348
349            iter_header(
350                config.mode,
351                &config.suite,
352                &mut poisoned,
353                testfile,
354                file,
355                &mut |directive @ DirectiveLine { raw_directive: ln, .. }| {
356                    if !directive.applies_to_test_revision(test_revision) {
357                        return;
358                    }
359
360                    use directives::*;
361
362                    config.push_name_value_directive(
363                        ln,
364                        ERROR_PATTERN,
365                        &mut self.error_patterns,
366                        |r| r,
367                    );
368                    config.push_name_value_directive(
369                        ln,
370                        REGEX_ERROR_PATTERN,
371                        &mut self.regex_error_patterns,
372                        |r| r,
373                    );
374
375                    config.push_name_value_directive(ln, DOC_FLAGS, &mut self.doc_flags, |r| r);
376
377                    fn split_flags(flags: &str) -> Vec<String> {
378                        // Individual flags can be single-quoted to preserve spaces; see
379                        // <https://github.com/rust-lang/rust/pull/115948/commits/957c5db6>.
380                        flags
381                            .split('\'')
382                            .enumerate()
383                            .flat_map(|(i, f)| {
384                                if i % 2 == 1 { vec![f] } else { f.split_whitespace().collect() }
385                            })
386                            .map(move |s| s.to_owned())
387                            .collect::<Vec<_>>()
388                    }
389
390                    if let Some(flags) = config.parse_name_value_directive(ln, COMPILE_FLAGS) {
391                        let flags = split_flags(&flags);
392                        for flag in &flags {
393                            if flag == "--edition" || flag.starts_with("--edition=") {
394                                panic!("you must use `//@ edition` to configure the edition");
395                            }
396                        }
397                        self.compile_flags.extend(flags);
398                    }
399                    if config.parse_name_value_directive(ln, INCORRECT_COMPILER_FLAGS).is_some() {
400                        panic!("`compiler-flags` directive should be spelled `compile-flags`");
401                    }
402
403                    if let Some(edition) = config.parse_edition(ln) {
404                        // The edition is added at the start, since flags from //@compile-flags must
405                        // be passed to rustc last.
406                        self.compile_flags.insert(0, format!("--edition={}", edition.trim()));
407                        has_edition = true;
408                    }
409
410                    config.parse_and_update_revisions(testfile, ln, &mut self.revisions);
411
412                    if let Some(flags) = config.parse_name_value_directive(ln, RUN_FLAGS) {
413                        self.run_flags.extend(split_flags(&flags));
414                    }
415
416                    if self.pp_exact.is_none() {
417                        self.pp_exact = config.parse_pp_exact(ln, testfile);
418                    }
419
420                    config.set_name_directive(ln, SHOULD_ICE, &mut self.should_ice);
421                    config.set_name_directive(ln, BUILD_AUX_DOCS, &mut self.build_aux_docs);
422                    config.set_name_directive(ln, UNIQUE_DOC_OUT_DIR, &mut self.unique_doc_out_dir);
423
424                    config.set_name_directive(ln, FORCE_HOST, &mut self.force_host);
425                    config.set_name_directive(ln, CHECK_STDOUT, &mut self.check_stdout);
426                    config.set_name_directive(ln, CHECK_RUN_RESULTS, &mut self.check_run_results);
427                    config.set_name_directive(
428                        ln,
429                        DONT_CHECK_COMPILER_STDOUT,
430                        &mut self.dont_check_compiler_stdout,
431                    );
432                    config.set_name_directive(
433                        ln,
434                        DONT_CHECK_COMPILER_STDERR,
435                        &mut self.dont_check_compiler_stderr,
436                    );
437                    config.set_name_directive(ln, NO_PREFER_DYNAMIC, &mut self.no_prefer_dynamic);
438
439                    if let Some(m) = config.parse_name_value_directive(ln, PRETTY_MODE) {
440                        self.pretty_mode = m;
441                    }
442
443                    config.set_name_directive(
444                        ln,
445                        PRETTY_COMPARE_ONLY,
446                        &mut self.pretty_compare_only,
447                    );
448
449                    // Call a helper method to deal with aux-related directives.
450                    parse_and_update_aux(config, ln, &mut self.aux);
451
452                    config.push_name_value_directive(
453                        ln,
454                        EXEC_ENV,
455                        &mut self.exec_env,
456                        Config::parse_env,
457                    );
458                    config.push_name_value_directive(
459                        ln,
460                        UNSET_EXEC_ENV,
461                        &mut self.unset_exec_env,
462                        |r| r.trim().to_owned(),
463                    );
464                    config.push_name_value_directive(
465                        ln,
466                        RUSTC_ENV,
467                        &mut self.rustc_env,
468                        Config::parse_env,
469                    );
470                    config.push_name_value_directive(
471                        ln,
472                        UNSET_RUSTC_ENV,
473                        &mut self.unset_rustc_env,
474                        |r| r.trim().to_owned(),
475                    );
476                    config.push_name_value_directive(
477                        ln,
478                        FORBID_OUTPUT,
479                        &mut self.forbid_output,
480                        |r| r,
481                    );
482                    config.set_name_directive(
483                        ln,
484                        CHECK_TEST_LINE_NUMBERS_MATCH,
485                        &mut self.check_test_line_numbers_match,
486                    );
487
488                    self.update_pass_mode(ln, test_revision, config);
489                    self.update_fail_mode(ln, config);
490
491                    config.set_name_directive(ln, IGNORE_PASS, &mut self.ignore_pass);
492
493                    if let Some(NormalizeRule { kind, regex, replacement }) =
494                        config.parse_custom_normalization(ln)
495                    {
496                        let rule_tuple = (regex, replacement);
497                        match kind {
498                            NormalizeKind::Stdout => self.normalize_stdout.push(rule_tuple),
499                            NormalizeKind::Stderr => self.normalize_stderr.push(rule_tuple),
500                            NormalizeKind::Stderr32bit => {
501                                if config.target_cfg().pointer_width == 32 {
502                                    self.normalize_stderr.push(rule_tuple);
503                                }
504                            }
505                            NormalizeKind::Stderr64bit => {
506                                if config.target_cfg().pointer_width == 64 {
507                                    self.normalize_stderr.push(rule_tuple);
508                                }
509                            }
510                        }
511                    }
512
513                    if let Some(code) = config
514                        .parse_name_value_directive(ln, FAILURE_STATUS)
515                        .and_then(|code| code.trim().parse::<i32>().ok())
516                    {
517                        self.failure_status = Some(code);
518                    }
519
520                    config.set_name_directive(
521                        ln,
522                        DONT_CHECK_FAILURE_STATUS,
523                        &mut self.dont_check_failure_status,
524                    );
525
526                    config.set_name_directive(ln, RUN_RUSTFIX, &mut self.run_rustfix);
527                    config.set_name_directive(
528                        ln,
529                        RUSTFIX_ONLY_MACHINE_APPLICABLE,
530                        &mut self.rustfix_only_machine_applicable,
531                    );
532                    config.set_name_value_directive(
533                        ln,
534                        ASSEMBLY_OUTPUT,
535                        &mut self.assembly_output,
536                        |r| r.trim().to_string(),
537                    );
538                    config.set_name_directive(
539                        ln,
540                        STDERR_PER_BITWIDTH,
541                        &mut self.stderr_per_bitwidth,
542                    );
543                    config.set_name_directive(ln, INCREMENTAL, &mut self.incremental);
544
545                    // Unlike the other `name_value_directive`s this needs to be handled manually,
546                    // because it sets a `bool` flag.
547                    if let Some(known_bug) = config.parse_name_value_directive(ln, KNOWN_BUG) {
548                        let known_bug = known_bug.trim();
549                        if known_bug == "unknown"
550                            || known_bug.split(',').all(|issue_ref| {
551                                issue_ref
552                                    .trim()
553                                    .split_once('#')
554                                    .filter(|(_, number)| {
555                                        number.chars().all(|digit| digit.is_numeric())
556                                    })
557                                    .is_some()
558                            })
559                        {
560                            self.known_bug = true;
561                        } else {
562                            panic!(
563                                "Invalid known-bug value: {known_bug}\nIt requires comma-separated issue references (`#000` or `chalk#000`) or `known-bug: unknown`."
564                            );
565                        }
566                    } else if config.parse_name_directive(ln, KNOWN_BUG) {
567                        panic!(
568                            "Invalid known-bug attribute, requires comma-separated issue references (`#000` or `chalk#000`) or `known-bug: unknown`."
569                        );
570                    }
571
572                    config.set_name_value_directive(
573                        ln,
574                        TEST_MIR_PASS,
575                        &mut self.mir_unit_test,
576                        |s| s.trim().to_string(),
577                    );
578                    config.set_name_directive(ln, REMAP_SRC_BASE, &mut self.remap_src_base);
579
580                    if let Some(flags) = config.parse_name_value_directive(ln, LLVM_COV_FLAGS) {
581                        self.llvm_cov_flags.extend(split_flags(&flags));
582                    }
583
584                    if let Some(flags) = config.parse_name_value_directive(ln, FILECHECK_FLAGS) {
585                        self.filecheck_flags.extend(split_flags(&flags));
586                    }
587
588                    config.set_name_directive(ln, NO_AUTO_CHECK_CFG, &mut self.no_auto_check_cfg);
589
590                    self.update_add_core_stubs(ln, config);
591
592                    if let Some(err_kind) =
593                        config.parse_name_value_directive(ln, DONT_REQUIRE_ANNOTATIONS)
594                    {
595                        self.dont_require_annotations
596                            .insert(ErrorKind::from_user_str(err_kind.trim()));
597                    }
598                },
599            );
600
601            if poisoned {
602                eprintln!("errors encountered during TestProps parsing: {}", testfile);
603                panic!("errors encountered during TestProps parsing");
604            }
605        }
606
607        if self.should_ice {
608            self.failure_status = Some(101);
609        }
610
611        if config.mode == Mode::Incremental {
612            self.incremental = true;
613        }
614
615        if config.mode == Mode::Crashes {
616            // we don't want to pollute anything with backtrace-files
617            // also turn off backtraces in order to save some execution
618            // time on the tests; we only need to know IF it crashes
619            self.rustc_env = vec![
620                ("RUST_BACKTRACE".to_string(), "0".to_string()),
621                ("RUSTC_ICE".to_string(), "0".to_string()),
622            ];
623        }
624
625        for key in &["RUST_TEST_NOCAPTURE", "RUST_TEST_THREADS"] {
626            if let Ok(val) = env::var(key) {
627                if !self.exec_env.iter().any(|&(ref x, _)| x == key) {
628                    self.exec_env.push(((*key).to_owned(), val))
629                }
630            }
631        }
632
633        if let (Some(edition), false) = (&config.edition, has_edition) {
634            // The edition is added at the start, since flags from //@compile-flags must be passed
635            // to rustc last.
636            self.compile_flags.insert(0, format!("--edition={}", edition));
637        }
638    }
639
640    fn update_fail_mode(&mut self, ln: &str, config: &Config) {
641        let check_ui = |mode: &str| {
642            // Mode::Crashes may need build-fail in order to trigger llvm errors or stack overflows
643            if config.mode != Mode::Ui && config.mode != Mode::Crashes {
644                panic!("`{}-fail` header is only supported in UI tests", mode);
645            }
646        };
647        if config.mode == Mode::Ui && config.parse_name_directive(ln, "compile-fail") {
648            panic!("`compile-fail` header is useless in UI tests");
649        }
650        let fail_mode = if config.parse_name_directive(ln, "check-fail") {
651            check_ui("check");
652            Some(FailMode::Check)
653        } else if config.parse_name_directive(ln, "build-fail") {
654            check_ui("build");
655            Some(FailMode::Build)
656        } else if config.parse_name_directive(ln, "run-fail") {
657            check_ui("run");
658            Some(FailMode::Run)
659        } else {
660            None
661        };
662        match (self.fail_mode, fail_mode) {
663            (None, Some(_)) => self.fail_mode = fail_mode,
664            (Some(_), Some(_)) => panic!("multiple `*-fail` headers in a single test"),
665            (_, None) => {}
666        }
667    }
668
669    fn update_pass_mode(&mut self, ln: &str, revision: Option<&str>, config: &Config) {
670        let check_no_run = |s| match (config.mode, s) {
671            (Mode::Ui, _) => (),
672            (Mode::Crashes, _) => (),
673            (Mode::Codegen, "build-pass") => (),
674            (Mode::Incremental, _) => {
675                if revision.is_some() && !self.revisions.iter().all(|r| r.starts_with("cfail")) {
676                    panic!("`{s}` header is only supported in `cfail` incremental tests")
677                }
678            }
679            (mode, _) => panic!("`{s}` header is not supported in `{mode}` tests"),
680        };
681        let pass_mode = if config.parse_name_directive(ln, "check-pass") {
682            check_no_run("check-pass");
683            Some(PassMode::Check)
684        } else if config.parse_name_directive(ln, "build-pass") {
685            check_no_run("build-pass");
686            Some(PassMode::Build)
687        } else if config.parse_name_directive(ln, "run-pass") {
688            check_no_run("run-pass");
689            Some(PassMode::Run)
690        } else {
691            None
692        };
693        match (self.pass_mode, pass_mode) {
694            (None, Some(_)) => self.pass_mode = pass_mode,
695            (Some(_), Some(_)) => panic!("multiple `*-pass` headers in a single test"),
696            (_, None) => {}
697        }
698    }
699
700    pub fn pass_mode(&self, config: &Config) -> Option<PassMode> {
701        if !self.ignore_pass && self.fail_mode.is_none() {
702            if let mode @ Some(_) = config.force_pass_mode {
703                return mode;
704            }
705        }
706        self.pass_mode
707    }
708
709    // does not consider CLI override for pass mode
710    pub fn local_pass_mode(&self) -> Option<PassMode> {
711        self.pass_mode
712    }
713
714    pub fn update_add_core_stubs(&mut self, ln: &str, config: &Config) {
715        let add_core_stubs = config.parse_name_directive(ln, directives::ADD_CORE_STUBS);
716        if add_core_stubs {
717            if !matches!(config.mode, Mode::Ui | Mode::Codegen | Mode::Assembly) {
718                panic!(
719                    "`add-core-stubs` is currently only supported for ui, codegen and assembly test modes"
720                );
721            }
722
723            // FIXME(jieyouxu): this check is currently order-dependent, but we should probably
724            // collect all directives in one go then perform a validation pass after that.
725            if self.local_pass_mode().is_some_and(|pm| pm == PassMode::Run) {
726                // `minicore` can only be used with non-run modes, because it's `core` prelude stubs
727                // and can't run.
728                panic!("`add-core-stubs` cannot be used to run the test binary");
729            }
730
731            self.add_core_stubs = add_core_stubs;
732        }
733    }
734}
735
736/// If the given line begins with the appropriate comment prefix for a directive,
737/// returns a struct containing various parts of the directive.
738fn line_directive<'line>(
739    line_number: usize,
740    original_line: &'line str,
741) -> Option<DirectiveLine<'line>> {
742    // Ignore lines that don't start with the comment prefix.
743    let after_comment =
744        original_line.trim_start().strip_prefix(COMPILETEST_DIRECTIVE_PREFIX)?.trim_start();
745
746    let revision;
747    let raw_directive;
748
749    if let Some(after_open_bracket) = after_comment.strip_prefix('[') {
750        // A comment like `//@[foo]` only applies to revision `foo`.
751        let Some((line_revision, after_close_bracket)) = after_open_bracket.split_once(']') else {
752            panic!(
753                "malformed condition directive: expected `{COMPILETEST_DIRECTIVE_PREFIX}[foo]`, found `{original_line}`"
754            )
755        };
756
757        revision = Some(line_revision);
758        raw_directive = after_close_bracket.trim_start();
759    } else {
760        revision = None;
761        raw_directive = after_comment;
762    };
763
764    Some(DirectiveLine { line_number, revision, raw_directive })
765}
766
767// To prevent duplicating the list of directives between `compiletest`,`htmldocck` and `jsondocck`,
768// we put it into a common file which is included in rust code and parsed here.
769// FIXME: This setup is temporary until we figure out how to improve this situation.
770//        See <https://github.com/rust-lang/rust/issues/125813#issuecomment-2141953780>.
771include!("directive-list.rs");
772
773const KNOWN_HTMLDOCCK_DIRECTIVE_NAMES: &[&str] = &[
774    "count",
775    "!count",
776    "files",
777    "!files",
778    "has",
779    "!has",
780    "has-dir",
781    "!has-dir",
782    "hasraw",
783    "!hasraw",
784    "matches",
785    "!matches",
786    "matchesraw",
787    "!matchesraw",
788    "snapshot",
789    "!snapshot",
790];
791
792const KNOWN_JSONDOCCK_DIRECTIVE_NAMES: &[&str] =
793    &["count", "!count", "has", "!has", "is", "!is", "ismany", "!ismany", "set", "!set"];
794
795/// The (partly) broken-down contents of a line containing a test directive,
796/// which [`iter_header`] passes to its callback function.
797///
798/// For example:
799///
800/// ```text
801/// //@ compile-flags: -O
802///     ^^^^^^^^^^^^^^^^^ raw_directive
803///
804/// //@ [foo] compile-flags: -O
805///      ^^^                    revision
806///           ^^^^^^^^^^^^^^^^^ raw_directive
807/// ```
808struct DirectiveLine<'ln> {
809    line_number: usize,
810    /// Some test directives start with a revision name in square brackets
811    /// (e.g. `[foo]`), and only apply to that revision of the test.
812    /// If present, this field contains the revision name (e.g. `foo`).
813    revision: Option<&'ln str>,
814    /// The main part of the directive, after removing the comment prefix
815    /// and the optional revision specifier.
816    ///
817    /// This is "raw" because the directive's name and colon-separated value
818    /// (if present) have not yet been extracted or checked.
819    raw_directive: &'ln str,
820}
821
822impl<'ln> DirectiveLine<'ln> {
823    fn applies_to_test_revision(&self, test_revision: Option<&str>) -> bool {
824        self.revision.is_none() || self.revision == test_revision
825    }
826}
827
828pub(crate) struct CheckDirectiveResult<'ln> {
829    is_known_directive: bool,
830    trailing_directive: Option<&'ln str>,
831}
832
833pub(crate) fn check_directive<'a>(
834    directive_ln: &'a str,
835    mode: Mode,
836    original_line: &str,
837) -> CheckDirectiveResult<'a> {
838    let (directive_name, post) = directive_ln.split_once([':', ' ']).unwrap_or((directive_ln, ""));
839
840    let trailing = post.trim().split_once(' ').map(|(pre, _)| pre).unwrap_or(post);
841    let is_known = |s: &str| {
842        KNOWN_DIRECTIVE_NAMES.contains(&s)
843            || match mode {
844                Mode::Rustdoc | Mode::RustdocJson => {
845                    original_line.starts_with("//@")
846                        && match mode {
847                            Mode::Rustdoc => KNOWN_HTMLDOCCK_DIRECTIVE_NAMES,
848                            Mode::RustdocJson => KNOWN_JSONDOCCK_DIRECTIVE_NAMES,
849                            _ => unreachable!(),
850                        }
851                        .contains(&s)
852                }
853                _ => false,
854            }
855    };
856    let trailing_directive = {
857        // 1. is the directive name followed by a space? (to exclude `:`)
858        matches!(directive_ln.get(directive_name.len()..), Some(s) if s.starts_with(' '))
859            // 2. is what is after that directive also a directive (ex: "only-x86 only-arm")
860            && is_known(trailing)
861    }
862    .then_some(trailing);
863
864    CheckDirectiveResult { is_known_directive: is_known(&directive_name), trailing_directive }
865}
866
867const COMPILETEST_DIRECTIVE_PREFIX: &str = "//@";
868
869fn iter_header(
870    mode: Mode,
871    _suite: &str,
872    poisoned: &mut bool,
873    testfile: &Utf8Path,
874    rdr: impl Read,
875    it: &mut dyn FnMut(DirectiveLine<'_>),
876) {
877    if testfile.is_dir() {
878        return;
879    }
880
881    // Coverage tests in coverage-run mode always have these extra directives, without needing to
882    // specify them manually in every test file.
883    //
884    // FIXME(jieyouxu): I feel like there's a better way to do this, leaving for later.
885    if mode == Mode::CoverageRun {
886        let extra_directives: &[&str] = &[
887            "needs-profiler-runtime",
888            // FIXME(pietroalbini): this test currently does not work on cross-compiled targets
889            // because remote-test is not capable of sending back the *.profraw files generated by
890            // the LLVM instrumentation.
891            "ignore-cross-compile",
892        ];
893        // Process the extra implied directives, with a dummy line number of 0.
894        for raw_directive in extra_directives {
895            it(DirectiveLine { line_number: 0, revision: None, raw_directive });
896        }
897    }
898
899    let mut rdr = BufReader::with_capacity(1024, rdr);
900    let mut ln = String::new();
901    let mut line_number = 0;
902
903    loop {
904        line_number += 1;
905        ln.clear();
906        if rdr.read_line(&mut ln).unwrap() == 0 {
907            break;
908        }
909        let ln = ln.trim();
910
911        let Some(directive_line) = line_directive(line_number, ln) else {
912            continue;
913        };
914
915        // Perform unknown directive check on Rust files.
916        if testfile.extension().map(|e| e == "rs").unwrap_or(false) {
917            let CheckDirectiveResult { is_known_directive, trailing_directive } =
918                check_directive(directive_line.raw_directive, mode, ln);
919
920            if !is_known_directive {
921                *poisoned = true;
922
923                eprintln!(
924                    "error: detected unknown compiletest test directive `{}` in {}:{}",
925                    directive_line.raw_directive, testfile, line_number,
926                );
927
928                return;
929            }
930
931            if let Some(trailing_directive) = &trailing_directive {
932                *poisoned = true;
933
934                eprintln!(
935                    "error: detected trailing compiletest test directive `{}` in {}:{}\n \
936                      help: put the trailing directive in it's own line: `//@ {}`",
937                    trailing_directive, testfile, line_number, trailing_directive,
938                );
939
940                return;
941            }
942        }
943
944        it(directive_line);
945    }
946}
947
948impl Config {
949    fn parse_and_update_revisions(
950        &self,
951        testfile: &Utf8Path,
952        line: &str,
953        existing: &mut Vec<String>,
954    ) {
955        const FORBIDDEN_REVISION_NAMES: [&str; 2] = [
956            // `//@ revisions: true false` Implying `--cfg=true` and `--cfg=false` makes it very
957            // weird for the test, since if the test writer wants a cfg of the same revision name
958            // they'd have to use `cfg(r#true)` and `cfg(r#false)`.
959            "true", "false",
960        ];
961
962        const FILECHECK_FORBIDDEN_REVISION_NAMES: [&str; 9] =
963            ["CHECK", "COM", "NEXT", "SAME", "EMPTY", "NOT", "COUNT", "DAG", "LABEL"];
964
965        if let Some(raw) = self.parse_name_value_directive(line, "revisions") {
966            if self.mode == Mode::RunMake {
967                panic!("`run-make` tests do not support revisions: {}", testfile);
968            }
969
970            let mut duplicates: HashSet<_> = existing.iter().cloned().collect();
971            for revision in raw.split_whitespace() {
972                if !duplicates.insert(revision.to_string()) {
973                    panic!("duplicate revision: `{}` in line `{}`: {}", revision, raw, testfile);
974                }
975
976                if FORBIDDEN_REVISION_NAMES.contains(&revision) {
977                    panic!(
978                        "revision name `{revision}` is not permitted: `{}` in line `{}`: {}",
979                        revision, raw, testfile
980                    );
981                }
982
983                if matches!(self.mode, Mode::Assembly | Mode::Codegen | Mode::MirOpt)
984                    && FILECHECK_FORBIDDEN_REVISION_NAMES.contains(&revision)
985                {
986                    panic!(
987                        "revision name `{revision}` is not permitted in a test suite that uses \
988                        `FileCheck` annotations as it is confusing when used as custom `FileCheck` \
989                        prefix: `{revision}` in line `{}`: {}",
990                        raw, testfile
991                    );
992                }
993
994                existing.push(revision.to_string());
995            }
996        }
997    }
998
999    fn parse_env(nv: String) -> (String, String) {
1000        // nv is either FOO or FOO=BAR
1001        // FIXME(Zalathar): The form without `=` seems to be unused; should
1002        // we drop support for it?
1003        let (name, value) = nv.split_once('=').unwrap_or((&nv, ""));
1004        // Trim whitespace from the name, so that `//@ exec-env: FOO=BAR`
1005        // sees the name as `FOO` and not ` FOO`.
1006        let name = name.trim();
1007        (name.to_owned(), value.to_owned())
1008    }
1009
1010    fn parse_pp_exact(&self, line: &str, testfile: &Utf8Path) -> Option<Utf8PathBuf> {
1011        if let Some(s) = self.parse_name_value_directive(line, "pp-exact") {
1012            Some(Utf8PathBuf::from(&s))
1013        } else if self.parse_name_directive(line, "pp-exact") {
1014            testfile.file_name().map(Utf8PathBuf::from)
1015        } else {
1016            None
1017        }
1018    }
1019
1020    fn parse_custom_normalization(&self, raw_directive: &str) -> Option<NormalizeRule> {
1021        // FIXME(Zalathar): Integrate name/value splitting into `DirectiveLine`
1022        // instead of doing it here.
1023        let (directive_name, raw_value) = raw_directive.split_once(':')?;
1024
1025        let kind = match directive_name {
1026            "normalize-stdout" => NormalizeKind::Stdout,
1027            "normalize-stderr" => NormalizeKind::Stderr,
1028            "normalize-stderr-32bit" => NormalizeKind::Stderr32bit,
1029            "normalize-stderr-64bit" => NormalizeKind::Stderr64bit,
1030            _ => return None,
1031        };
1032
1033        let Some((regex, replacement)) = parse_normalize_rule(raw_value) else {
1034            panic!(
1035                "couldn't parse custom normalization rule: `{raw_directive}`\n\
1036                help: expected syntax is: `{directive_name}: \"REGEX\" -> \"REPLACEMENT\"`"
1037            );
1038        };
1039        Some(NormalizeRule { kind, regex, replacement })
1040    }
1041
1042    fn parse_name_directive(&self, line: &str, directive: &str) -> bool {
1043        // Ensure the directive is a whole word. Do not match "ignore-x86" when
1044        // the line says "ignore-x86_64".
1045        line.starts_with(directive)
1046            && matches!(line.as_bytes().get(directive.len()), None | Some(&b' ') | Some(&b':'))
1047    }
1048
1049    fn parse_negative_name_directive(&self, line: &str, directive: &str) -> bool {
1050        line.starts_with("no-") && self.parse_name_directive(&line[3..], directive)
1051    }
1052
1053    pub fn parse_name_value_directive(&self, line: &str, directive: &str) -> Option<String> {
1054        let colon = directive.len();
1055        if line.starts_with(directive) && line.as_bytes().get(colon) == Some(&b':') {
1056            let value = line[(colon + 1)..].to_owned();
1057            debug!("{}: {}", directive, value);
1058            Some(expand_variables(value, self))
1059        } else {
1060            None
1061        }
1062    }
1063
1064    fn parse_edition(&self, line: &str) -> Option<String> {
1065        self.parse_name_value_directive(line, "edition")
1066    }
1067
1068    fn set_name_directive(&self, line: &str, directive: &str, value: &mut bool) {
1069        match value {
1070            true => {
1071                if self.parse_negative_name_directive(line, directive) {
1072                    *value = false;
1073                }
1074            }
1075            false => {
1076                if self.parse_name_directive(line, directive) {
1077                    *value = true;
1078                }
1079            }
1080        }
1081    }
1082
1083    fn set_name_value_directive<T>(
1084        &self,
1085        line: &str,
1086        directive: &str,
1087        value: &mut Option<T>,
1088        parse: impl FnOnce(String) -> T,
1089    ) {
1090        if value.is_none() {
1091            *value = self.parse_name_value_directive(line, directive).map(parse);
1092        }
1093    }
1094
1095    fn push_name_value_directive<T>(
1096        &self,
1097        line: &str,
1098        directive: &str,
1099        values: &mut Vec<T>,
1100        parse: impl FnOnce(String) -> T,
1101    ) {
1102        if let Some(value) = self.parse_name_value_directive(line, directive).map(parse) {
1103            values.push(value);
1104        }
1105    }
1106}
1107
1108// FIXME(jieyouxu): fix some of these variable names to more accurately reflect what they do.
1109fn expand_variables(mut value: String, config: &Config) -> String {
1110    const CWD: &str = "{{cwd}}";
1111    const SRC_BASE: &str = "{{src-base}}";
1112    const TEST_SUITE_BUILD_BASE: &str = "{{build-base}}";
1113    const RUST_SRC_BASE: &str = "{{rust-src-base}}";
1114    const SYSROOT_BASE: &str = "{{sysroot-base}}";
1115    const TARGET_LINKER: &str = "{{target-linker}}";
1116    const TARGET: &str = "{{target}}";
1117
1118    if value.contains(CWD) {
1119        let cwd = env::current_dir().unwrap();
1120        value = value.replace(CWD, &cwd.to_str().unwrap());
1121    }
1122
1123    if value.contains(SRC_BASE) {
1124        value = value.replace(SRC_BASE, &config.src_test_suite_root.as_str());
1125    }
1126
1127    if value.contains(TEST_SUITE_BUILD_BASE) {
1128        value = value.replace(TEST_SUITE_BUILD_BASE, &config.build_test_suite_root.as_str());
1129    }
1130
1131    if value.contains(SYSROOT_BASE) {
1132        value = value.replace(SYSROOT_BASE, &config.sysroot_base.as_str());
1133    }
1134
1135    if value.contains(TARGET_LINKER) {
1136        value = value.replace(TARGET_LINKER, config.target_linker.as_deref().unwrap_or(""));
1137    }
1138
1139    if value.contains(TARGET) {
1140        value = value.replace(TARGET, &config.target);
1141    }
1142
1143    if value.contains(RUST_SRC_BASE) {
1144        let src_base = config.sysroot_base.join("lib/rustlib/src/rust");
1145        src_base.try_exists().expect(&*format!("{} should exists", src_base));
1146        let src_base = src_base.read_link_utf8().unwrap_or(src_base);
1147        value = value.replace(RUST_SRC_BASE, &src_base.as_str());
1148    }
1149
1150    value
1151}
1152
1153struct NormalizeRule {
1154    kind: NormalizeKind,
1155    regex: String,
1156    replacement: String,
1157}
1158
1159enum NormalizeKind {
1160    Stdout,
1161    Stderr,
1162    Stderr32bit,
1163    Stderr64bit,
1164}
1165
1166/// Parses the regex and replacement values of a `//@ normalize-*` header,
1167/// in the format:
1168/// ```text
1169/// "REGEX" -> "REPLACEMENT"
1170/// ```
1171fn parse_normalize_rule(raw_value: &str) -> Option<(String, String)> {
1172    // FIXME: Support escaped double-quotes in strings.
1173    let captures = static_regex!(
1174        r#"(?x) # (verbose mode regex)
1175        ^
1176        \s*                     # (leading whitespace)
1177        "(?<regex>[^"]*)"       # "REGEX"
1178        \s+->\s+                # ->
1179        "(?<replacement>[^"]*)" # "REPLACEMENT"
1180        $
1181        "#
1182    )
1183    .captures(raw_value)?;
1184    let regex = captures["regex"].to_owned();
1185    let replacement = captures["replacement"].to_owned();
1186    // A `\n` sequence in the replacement becomes an actual newline.
1187    // FIXME: Do unescaping in a less ad-hoc way, and perhaps support escaped
1188    // backslashes and double-quotes.
1189    let replacement = replacement.replace("\\n", "\n");
1190    Some((regex, replacement))
1191}
1192
1193/// Given an llvm version string that looks like `1.2.3-rc1`, extract as semver. Note that this
1194/// accepts more than just strict `semver` syntax (as in `major.minor.patch`); this permits omitting
1195/// minor and patch version components so users can write e.g. `//@ min-llvm-version: 19` instead of
1196/// having to write `//@ min-llvm-version: 19.0.0`.
1197///
1198/// Currently panics if the input string is malformed, though we really should not use panic as an
1199/// error handling strategy.
1200///
1201/// FIXME(jieyouxu): improve error handling
1202pub fn extract_llvm_version(version: &str) -> Version {
1203    // The version substring we're interested in usually looks like the `1.2.3`, without any of the
1204    // fancy suffix like `-rc1` or `meow`.
1205    let version = version.trim();
1206    let uninterested = |c: char| !c.is_ascii_digit() && c != '.';
1207    let version_without_suffix = match version.split_once(uninterested) {
1208        Some((prefix, _suffix)) => prefix,
1209        None => version,
1210    };
1211
1212    let components: Vec<u64> = version_without_suffix
1213        .split('.')
1214        .map(|s| s.parse().expect("llvm version component should consist of only digits"))
1215        .collect();
1216
1217    match &components[..] {
1218        [major] => Version::new(*major, 0, 0),
1219        [major, minor] => Version::new(*major, *minor, 0),
1220        [major, minor, patch] => Version::new(*major, *minor, *patch),
1221        _ => panic!("malformed llvm version string, expected only 1-3 components: {version}"),
1222    }
1223}
1224
1225pub fn extract_llvm_version_from_binary(binary_path: &str) -> Option<Version> {
1226    let output = Command::new(binary_path).arg("--version").output().ok()?;
1227    if !output.status.success() {
1228        return None;
1229    }
1230    let version = String::from_utf8(output.stdout).ok()?;
1231    for line in version.lines() {
1232        if let Some(version) = line.split("LLVM version ").nth(1) {
1233            return Some(extract_llvm_version(version));
1234        }
1235    }
1236    None
1237}
1238
1239/// For tests using the `needs-llvm-zstd` directive:
1240/// - for local LLVM builds, try to find the static zstd library in the llvm-config system libs.
1241/// - for `download-ci-llvm`, see if `lld` was built with zstd support.
1242pub fn llvm_has_libzstd(config: &Config) -> bool {
1243    // Strategy 1: works for local builds but not with `download-ci-llvm`.
1244    //
1245    // We check whether `llvm-config` returns the zstd library. Bootstrap's `llvm.libzstd` will only
1246    // ask to statically link it when building LLVM, so we only check if the list of system libs
1247    // contains a path to that static lib, and that it exists.
1248    //
1249    // See compiler/rustc_llvm/build.rs for more details and similar expectations.
1250    fn is_zstd_in_config(llvm_bin_dir: &Utf8Path) -> Option<()> {
1251        let llvm_config_path = llvm_bin_dir.join("llvm-config");
1252        let output = Command::new(llvm_config_path).arg("--system-libs").output().ok()?;
1253        assert!(output.status.success(), "running llvm-config --system-libs failed");
1254
1255        let libs = String::from_utf8(output.stdout).ok()?;
1256        for lib in libs.split_whitespace() {
1257            if lib.ends_with("libzstd.a") && Utf8Path::new(lib).exists() {
1258                return Some(());
1259            }
1260        }
1261
1262        None
1263    }
1264
1265    // Strategy 2: `download-ci-llvm`'s `llvm-config --system-libs` will not return any libs to
1266    // use.
1267    //
1268    // The CI artifacts also don't contain the bootstrap config used to build them: otherwise we
1269    // could have looked at the `llvm.libzstd` config.
1270    //
1271    // We infer whether `LLVM_ENABLE_ZSTD` was used to build LLVM as a byproduct of testing whether
1272    // `lld` supports it. If not, an error will be emitted: "LLVM was not built with
1273    // LLVM_ENABLE_ZSTD or did not find zstd at build time".
1274    #[cfg(unix)]
1275    fn is_lld_built_with_zstd(llvm_bin_dir: &Utf8Path) -> Option<()> {
1276        let lld_path = llvm_bin_dir.join("lld");
1277        if lld_path.exists() {
1278            // We can't call `lld` as-is, it expects to be invoked by a compiler driver using a
1279            // different name. Prepare a temporary symlink to do that.
1280            let lld_symlink_path = llvm_bin_dir.join("ld.lld");
1281            if !lld_symlink_path.exists() {
1282                std::os::unix::fs::symlink(lld_path, &lld_symlink_path).ok()?;
1283            }
1284
1285            // Run `lld` with a zstd flag. We expect this command to always error here, we don't
1286            // want to link actual files and don't pass any.
1287            let output = Command::new(&lld_symlink_path)
1288                .arg("--compress-debug-sections=zstd")
1289                .output()
1290                .ok()?;
1291            assert!(!output.status.success());
1292
1293            // Look for a specific error caused by LLVM not being built with zstd support. We could
1294            // also look for the "no input files" message, indicating the zstd flag was accepted.
1295            let stderr = String::from_utf8(output.stderr).ok()?;
1296            let zstd_available = !stderr.contains("LLVM was not built with LLVM_ENABLE_ZSTD");
1297
1298            // We don't particularly need to clean the link up (so the previous commands could fail
1299            // in theory but won't in practice), but we can try.
1300            std::fs::remove_file(lld_symlink_path).ok()?;
1301
1302            if zstd_available {
1303                return Some(());
1304            }
1305        }
1306
1307        None
1308    }
1309
1310    #[cfg(not(unix))]
1311    fn is_lld_built_with_zstd(_llvm_bin_dir: &Utf8Path) -> Option<()> {
1312        None
1313    }
1314
1315    if let Some(llvm_bin_dir) = &config.llvm_bin_dir {
1316        // Strategy 1: for local LLVM builds.
1317        if is_zstd_in_config(llvm_bin_dir).is_some() {
1318            return true;
1319        }
1320
1321        // Strategy 2: for LLVM artifacts built on CI via `download-ci-llvm`.
1322        //
1323        // It doesn't work for cases where the artifacts don't contain the linker, but it's
1324        // best-effort: CI has `llvm.libzstd` and `lld` enabled on the x64 linux artifacts, so it
1325        // will at least work there.
1326        //
1327        // If this can be improved and expanded to less common cases in the future, it should.
1328        if config.target == "x86_64-unknown-linux-gnu"
1329            && config.host == config.target
1330            && is_lld_built_with_zstd(llvm_bin_dir).is_some()
1331        {
1332            return true;
1333        }
1334    }
1335
1336    // Otherwise, all hope is lost.
1337    false
1338}
1339
1340/// Takes a directive of the form `"<version1> [- <version2>]"`, returns the numeric representation
1341/// of `<version1>` and `<version2>` as tuple: `(<version1>, <version2>)`.
1342///
1343/// If the `<version2>` part is omitted, the second component of the tuple is the same as
1344/// `<version1>`.
1345fn extract_version_range<'a, F, VersionTy: Clone>(
1346    line: &'a str,
1347    parse: F,
1348) -> Option<(VersionTy, VersionTy)>
1349where
1350    F: Fn(&'a str) -> Option<VersionTy>,
1351{
1352    let mut splits = line.splitn(2, "- ").map(str::trim);
1353    let min = splits.next().unwrap();
1354    if min.ends_with('-') {
1355        return None;
1356    }
1357
1358    let max = splits.next();
1359
1360    if min.is_empty() {
1361        return None;
1362    }
1363
1364    let min = parse(min)?;
1365    let max = match max {
1366        Some("") => return None,
1367        Some(max) => parse(max)?,
1368        _ => min.clone(),
1369    };
1370
1371    Some((min, max))
1372}
1373
1374pub(crate) fn make_test_description<R: Read>(
1375    config: &Config,
1376    cache: &HeadersCache,
1377    name: String,
1378    path: &Utf8Path,
1379    src: R,
1380    test_revision: Option<&str>,
1381    poisoned: &mut bool,
1382) -> CollectedTestDesc {
1383    let mut ignore = false;
1384    let mut ignore_message = None;
1385    let mut should_fail = false;
1386
1387    let mut local_poisoned = false;
1388
1389    // Scan through the test file to handle `ignore-*`, `only-*`, and `needs-*` directives.
1390    iter_header(
1391        config.mode,
1392        &config.suite,
1393        &mut local_poisoned,
1394        path,
1395        src,
1396        &mut |directive @ DirectiveLine { line_number, raw_directive: ln, .. }| {
1397            if !directive.applies_to_test_revision(test_revision) {
1398                return;
1399            }
1400
1401            macro_rules! decision {
1402                ($e:expr) => {
1403                    match $e {
1404                        IgnoreDecision::Ignore { reason } => {
1405                            ignore = true;
1406                            ignore_message = Some(reason.into());
1407                        }
1408                        IgnoreDecision::Error { message } => {
1409                            eprintln!("error: {}:{line_number}: {message}", path);
1410                            *poisoned = true;
1411                            return;
1412                        }
1413                        IgnoreDecision::Continue => {}
1414                    }
1415                };
1416            }
1417
1418            decision!(cfg::handle_ignore(config, ln));
1419            decision!(cfg::handle_only(config, ln));
1420            decision!(needs::handle_needs(&cache.needs, config, ln));
1421            decision!(ignore_llvm(config, path, ln));
1422            decision!(ignore_cdb(config, ln));
1423            decision!(ignore_gdb(config, ln));
1424            decision!(ignore_lldb(config, ln));
1425
1426            if config.target == "wasm32-unknown-unknown"
1427                && config.parse_name_directive(ln, directives::CHECK_RUN_RESULTS)
1428            {
1429                decision!(IgnoreDecision::Ignore {
1430                    reason: "ignored on WASM as the run results cannot be checked there".into(),
1431                });
1432            }
1433
1434            should_fail |= config.parse_name_directive(ln, "should-fail");
1435        },
1436    );
1437
1438    if local_poisoned {
1439        eprintln!("errors encountered when trying to make test description: {}", path);
1440        panic!("errors encountered when trying to make test description");
1441    }
1442
1443    // The `should-fail` annotation doesn't apply to pretty tests,
1444    // since we run the pretty printer across all tests by default.
1445    // If desired, we could add a `should-fail-pretty` annotation.
1446    let should_panic = match config.mode {
1447        crate::common::Pretty => ShouldPanic::No,
1448        _ if should_fail => ShouldPanic::Yes,
1449        _ => ShouldPanic::No,
1450    };
1451
1452    CollectedTestDesc { name, ignore, ignore_message, should_panic }
1453}
1454
1455fn ignore_cdb(config: &Config, line: &str) -> IgnoreDecision {
1456    if config.debugger != Some(Debugger::Cdb) {
1457        return IgnoreDecision::Continue;
1458    }
1459
1460    if let Some(actual_version) = config.cdb_version {
1461        if let Some(rest) = line.strip_prefix("min-cdb-version:").map(str::trim) {
1462            let min_version = extract_cdb_version(rest).unwrap_or_else(|| {
1463                panic!("couldn't parse version range: {:?}", rest);
1464            });
1465
1466            // Ignore if actual version is smaller than the minimum
1467            // required version
1468            if actual_version < min_version {
1469                return IgnoreDecision::Ignore {
1470                    reason: format!("ignored when the CDB version is lower than {rest}"),
1471                };
1472            }
1473        }
1474    }
1475    IgnoreDecision::Continue
1476}
1477
1478fn ignore_gdb(config: &Config, line: &str) -> IgnoreDecision {
1479    if config.debugger != Some(Debugger::Gdb) {
1480        return IgnoreDecision::Continue;
1481    }
1482
1483    if let Some(actual_version) = config.gdb_version {
1484        if let Some(rest) = line.strip_prefix("min-gdb-version:").map(str::trim) {
1485            let (start_ver, end_ver) = extract_version_range(rest, extract_gdb_version)
1486                .unwrap_or_else(|| {
1487                    panic!("couldn't parse version range: {:?}", rest);
1488                });
1489
1490            if start_ver != end_ver {
1491                panic!("Expected single GDB version")
1492            }
1493            // Ignore if actual version is smaller than the minimum
1494            // required version
1495            if actual_version < start_ver {
1496                return IgnoreDecision::Ignore {
1497                    reason: format!("ignored when the GDB version is lower than {rest}"),
1498                };
1499            }
1500        } else if let Some(rest) = line.strip_prefix("ignore-gdb-version:").map(str::trim) {
1501            let (min_version, max_version) = extract_version_range(rest, extract_gdb_version)
1502                .unwrap_or_else(|| {
1503                    panic!("couldn't parse version range: {:?}", rest);
1504                });
1505
1506            if max_version < min_version {
1507                panic!("Malformed GDB version range: max < min")
1508            }
1509
1510            if actual_version >= min_version && actual_version <= max_version {
1511                if min_version == max_version {
1512                    return IgnoreDecision::Ignore {
1513                        reason: format!("ignored when the GDB version is {rest}"),
1514                    };
1515                } else {
1516                    return IgnoreDecision::Ignore {
1517                        reason: format!("ignored when the GDB version is between {rest}"),
1518                    };
1519                }
1520            }
1521        }
1522    }
1523    IgnoreDecision::Continue
1524}
1525
1526fn ignore_lldb(config: &Config, line: &str) -> IgnoreDecision {
1527    if config.debugger != Some(Debugger::Lldb) {
1528        return IgnoreDecision::Continue;
1529    }
1530
1531    if let Some(actual_version) = config.lldb_version {
1532        if let Some(rest) = line.strip_prefix("min-lldb-version:").map(str::trim) {
1533            let min_version = rest.parse().unwrap_or_else(|e| {
1534                panic!("Unexpected format of LLDB version string: {}\n{:?}", rest, e);
1535            });
1536            // Ignore if actual version is smaller the minimum required
1537            // version
1538            if actual_version < min_version {
1539                return IgnoreDecision::Ignore {
1540                    reason: format!("ignored when the LLDB version is {rest}"),
1541                };
1542            }
1543        }
1544    }
1545    IgnoreDecision::Continue
1546}
1547
1548fn ignore_llvm(config: &Config, path: &Utf8Path, line: &str) -> IgnoreDecision {
1549    if let Some(needed_components) =
1550        config.parse_name_value_directive(line, "needs-llvm-components")
1551    {
1552        let components: HashSet<_> = config.llvm_components.split_whitespace().collect();
1553        if let Some(missing_component) = needed_components
1554            .split_whitespace()
1555            .find(|needed_component| !components.contains(needed_component))
1556        {
1557            if env::var_os("COMPILETEST_REQUIRE_ALL_LLVM_COMPONENTS").is_some() {
1558                panic!(
1559                    "missing LLVM component {}, and COMPILETEST_REQUIRE_ALL_LLVM_COMPONENTS is set: {}",
1560                    missing_component, path
1561                );
1562            }
1563            return IgnoreDecision::Ignore {
1564                reason: format!("ignored when the {missing_component} LLVM component is missing"),
1565            };
1566        }
1567    }
1568    if let Some(actual_version) = &config.llvm_version {
1569        // Note that these `min` versions will check for not just major versions.
1570
1571        if let Some(version_string) = config.parse_name_value_directive(line, "min-llvm-version") {
1572            let min_version = extract_llvm_version(&version_string);
1573            // Ignore if actual version is smaller than the minimum required version.
1574            if *actual_version < min_version {
1575                return IgnoreDecision::Ignore {
1576                    reason: format!(
1577                        "ignored when the LLVM version {actual_version} is older than {min_version}"
1578                    ),
1579                };
1580            }
1581        } else if let Some(version_string) =
1582            config.parse_name_value_directive(line, "max-llvm-major-version")
1583        {
1584            let max_version = extract_llvm_version(&version_string);
1585            // Ignore if actual major version is larger than the maximum required major version.
1586            if actual_version.major > max_version.major {
1587                return IgnoreDecision::Ignore {
1588                    reason: format!(
1589                        "ignored when the LLVM version ({actual_version}) is newer than major\
1590                        version {}",
1591                        max_version.major
1592                    ),
1593                };
1594            }
1595        } else if let Some(version_string) =
1596            config.parse_name_value_directive(line, "min-system-llvm-version")
1597        {
1598            let min_version = extract_llvm_version(&version_string);
1599            // Ignore if using system LLVM and actual version
1600            // is smaller the minimum required version
1601            if config.system_llvm && *actual_version < min_version {
1602                return IgnoreDecision::Ignore {
1603                    reason: format!(
1604                        "ignored when the system LLVM version {actual_version} is older than {min_version}"
1605                    ),
1606                };
1607            }
1608        } else if let Some(version_range) =
1609            config.parse_name_value_directive(line, "ignore-llvm-version")
1610        {
1611            // Syntax is: "ignore-llvm-version: <version1> [- <version2>]"
1612            let (v_min, v_max) =
1613                extract_version_range(&version_range, |s| Some(extract_llvm_version(s)))
1614                    .unwrap_or_else(|| {
1615                        panic!("couldn't parse version range: \"{version_range}\"");
1616                    });
1617            if v_max < v_min {
1618                panic!("malformed LLVM version range where {v_max} < {v_min}")
1619            }
1620            // Ignore if version lies inside of range.
1621            if *actual_version >= v_min && *actual_version <= v_max {
1622                if v_min == v_max {
1623                    return IgnoreDecision::Ignore {
1624                        reason: format!("ignored when the LLVM version is {actual_version}"),
1625                    };
1626                } else {
1627                    return IgnoreDecision::Ignore {
1628                        reason: format!(
1629                            "ignored when the LLVM version is between {v_min} and {v_max}"
1630                        ),
1631                    };
1632                }
1633            }
1634        } else if let Some(version_string) =
1635            config.parse_name_value_directive(line, "exact-llvm-major-version")
1636        {
1637            // Syntax is "exact-llvm-major-version: <version>"
1638            let version = extract_llvm_version(&version_string);
1639            if actual_version.major != version.major {
1640                return IgnoreDecision::Ignore {
1641                    reason: format!(
1642                        "ignored when the actual LLVM major version is {}, but the test only targets major version {}",
1643                        actual_version.major, version.major
1644                    ),
1645                };
1646            }
1647        }
1648    }
1649    IgnoreDecision::Continue
1650}
1651
1652enum IgnoreDecision {
1653    Ignore { reason: String },
1654    Continue,
1655    Error { message: String },
1656}