compiletest/
header.rs

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