1use std::collections::HashSet;
2use std::process::Command;
3use std::{env, fs};
4
5use camino::{Utf8Path, Utf8PathBuf};
6use semver::Version;
7use tracing::*;
8
9use crate::common::{CodegenBackend, Config, Debugger, FailMode, PassMode, RunFailMode, TestMode};
10use crate::debuggers::{extract_cdb_version, extract_gdb_version};
11use crate::directives::auxiliary::parse_and_update_aux;
12pub(crate) use crate::directives::auxiliary::{AuxCrate, AuxProps};
13use crate::directives::directive_names::{
14 KNOWN_DIRECTIVE_NAMES_SET, KNOWN_HTMLDOCCK_DIRECTIVE_NAMES, KNOWN_JSONDOCCK_DIRECTIVE_NAMES,
15};
16pub(crate) use crate::directives::file::FileDirectives;
17use crate::directives::handlers::DIRECTIVE_HANDLERS_MAP;
18use crate::directives::line::DirectiveLine;
19use crate::directives::needs::CachedNeedsConditions;
20use crate::edition::{Edition, parse_edition};
21use crate::errors::ErrorKind;
22use crate::executor::{CollectedTestDesc, ShouldFail};
23use crate::util::static_regex;
24use crate::{fatal, help};
25
26mod auxiliary;
27mod cfg;
28mod directive_names;
29mod file;
30mod handlers;
31mod line;
32pub(crate) use line::line_directive;
33mod line_number;
34pub(crate) use line_number::LineNumber;
35mod needs;
36#[cfg(test)]
37mod tests;
38
39pub(crate) struct DirectivesCache {
40 cfg_conditions: cfg::PreparedConditions,
43 needs: CachedNeedsConditions,
44}
45
46impl DirectivesCache {
47 pub(crate) fn load(config: &Config) -> Self {
48 Self {
49 cfg_conditions: cfg::prepare_conditions(config),
50 needs: CachedNeedsConditions::load(config),
51 }
52 }
53}
54
55#[derive(Default)]
58pub(crate) struct EarlyProps {
59 pub(crate) revisions: Vec<String>,
60}
61
62impl EarlyProps {
63 pub(crate) fn from_file_directives(
64 config: &Config,
65 file_directives: &FileDirectives<'_>,
66 ) -> Self {
67 let mut props = EarlyProps::default();
68
69 iter_directives(
70 config,
71 file_directives,
72 &mut |ln: &DirectiveLine<'_>| {
74 config.parse_and_update_revisions(ln, &mut props.revisions);
75 },
76 );
77
78 props
79 }
80}
81
82#[derive(Clone, Debug)]
83pub(crate) struct TestProps {
84 pub(crate) error_patterns: Vec<String>,
86 pub(crate) regex_error_patterns: Vec<String>,
88 pub(crate) edition: Option<Edition>,
92 pub(crate) compile_flags: Vec<String>,
94 pub(crate) run_flags: Vec<String>,
96 pub(crate) doc_flags: Vec<String>,
98 pub(crate) pp_exact: Option<Utf8PathBuf>,
101 pub(crate) aux: AuxProps,
103 pub(crate) rustc_env: Vec<(String, String)>,
105 pub(crate) unset_rustc_env: Vec<String>,
108 pub(crate) exec_env: Vec<(String, String)>,
110 pub(crate) unset_exec_env: Vec<String>,
113 pub(crate) build_aux_docs: bool,
115 pub(crate) unique_doc_out_dir: bool,
118 pub(crate) force_host: bool,
120 pub(crate) check_stdout: bool,
122 pub(crate) check_run_results: bool,
124 pub(crate) dont_check_compiler_stdout: bool,
126 pub(crate) dont_check_compiler_stderr: bool,
128 pub(crate) no_prefer_dynamic: bool,
134 pub(crate) pretty_mode: String,
136 pub(crate) pretty_compare_only: bool,
138 pub(crate) forbid_output: Vec<String>,
140 pub(crate) revisions: Vec<String>,
142 pub(crate) incremental_dir: Option<Utf8PathBuf>,
147 pub(crate) incremental: bool,
162 pub(crate) known_bug: bool,
168 pass_mode: Option<PassMode>,
170 ignore_pass: bool,
172 pub(crate) fail_mode: Option<FailMode>,
174 pub(crate) check_test_line_numbers_match: bool,
176 pub(crate) normalize_stdout: Vec<(String, String)>,
178 pub(crate) normalize_stderr: Vec<(String, String)>,
179 pub(crate) failure_status: Option<i32>,
180 pub(crate) dont_check_failure_status: bool,
182 pub(crate) run_rustfix: bool,
185 pub(crate) rustfix_only_machine_applicable: bool,
187 pub(crate) assembly_output: Option<String>,
188 pub(crate) stderr_per_bitwidth: bool,
190 pub(crate) mir_unit_test: Option<String>,
192 pub(crate) remap_src_base: bool,
195 pub(crate) llvm_cov_flags: Vec<String>,
198 pub(crate) skip_filecheck: bool,
201 pub(crate) filecheck_flags: Vec<String>,
203 pub(crate) no_auto_check_cfg: bool,
205 pub(crate) add_minicore: bool,
208 pub(crate) minicore_compile_flags: Vec<String>,
210 pub(crate) dont_require_annotations: HashSet<ErrorKind>,
212 pub(crate) disable_gdb_pretty_printers: bool,
214 pub(crate) compare_output_by_lines: bool,
216}
217
218mod directives {
219 pub(crate) const ERROR_PATTERN: &str = "error-pattern";
220 pub(crate) const REGEX_ERROR_PATTERN: &str = "regex-error-pattern";
221 pub(crate) const COMPILE_FLAGS: &str = "compile-flags";
222 pub(crate) const RUN_FLAGS: &str = "run-flags";
223 pub(crate) const DOC_FLAGS: &str = "doc-flags";
224 pub(crate) const BUILD_AUX_DOCS: &str = "build-aux-docs";
225 pub(crate) const UNIQUE_DOC_OUT_DIR: &str = "unique-doc-out-dir";
226 pub(crate) const FORCE_HOST: &str = "force-host";
227 pub(crate) const CHECK_STDOUT: &str = "check-stdout";
228 pub(crate) const CHECK_RUN_RESULTS: &str = "check-run-results";
229 pub(crate) const DONT_CHECK_COMPILER_STDOUT: &str = "dont-check-compiler-stdout";
230 pub(crate) const DONT_CHECK_COMPILER_STDERR: &str = "dont-check-compiler-stderr";
231 pub(crate) const DONT_REQUIRE_ANNOTATIONS: &str = "dont-require-annotations";
232 pub(crate) const NO_PREFER_DYNAMIC: &str = "no-prefer-dynamic";
233 pub(crate) const PRETTY_MODE: &str = "pretty-mode";
234 pub(crate) const PRETTY_COMPARE_ONLY: &str = "pretty-compare-only";
235 pub(crate) const AUX_BIN: &str = "aux-bin";
236 pub(crate) const AUX_BUILD: &str = "aux-build";
237 pub(crate) const AUX_CRATE: &str = "aux-crate";
238 pub(crate) const PROC_MACRO: &str = "proc-macro";
239 pub(crate) const AUX_CODEGEN_BACKEND: &str = "aux-codegen-backend";
240 pub(crate) const EXEC_ENV: &str = "exec-env";
241 pub(crate) const RUSTC_ENV: &str = "rustc-env";
242 pub(crate) const UNSET_EXEC_ENV: &str = "unset-exec-env";
243 pub(crate) const UNSET_RUSTC_ENV: &str = "unset-rustc-env";
244 pub(crate) const FORBID_OUTPUT: &str = "forbid-output";
245 pub(crate) const CHECK_TEST_LINE_NUMBERS_MATCH: &str = "check-test-line-numbers-match";
246 pub(crate) const IGNORE_PASS: &str = "ignore-pass";
247 pub(crate) const FAILURE_STATUS: &str = "failure-status";
248 pub(crate) const DONT_CHECK_FAILURE_STATUS: &str = "dont-check-failure-status";
249 pub(crate) const RUN_RUSTFIX: &str = "run-rustfix";
250 pub(crate) const RUSTFIX_ONLY_MACHINE_APPLICABLE: &str = "rustfix-only-machine-applicable";
251 pub(crate) const ASSEMBLY_OUTPUT: &str = "assembly-output";
252 pub(crate) const STDERR_PER_BITWIDTH: &str = "stderr-per-bitwidth";
253 pub(crate) const INCREMENTAL: &str = "incremental";
254 pub(crate) const KNOWN_BUG: &str = "known-bug";
255 pub(crate) const TEST_MIR_PASS: &str = "test-mir-pass";
256 pub(crate) const REMAP_SRC_BASE: &str = "remap-src-base";
257 pub(crate) const LLVM_COV_FLAGS: &str = "llvm-cov-flags";
258 pub(crate) const FILECHECK_FLAGS: &str = "filecheck-flags";
259 pub(crate) const NO_AUTO_CHECK_CFG: &str = "no-auto-check-cfg";
260 pub(crate) const ADD_MINICORE: &str = "add-minicore";
261 pub(crate) const MINICORE_COMPILE_FLAGS: &str = "minicore-compile-flags";
262 pub(crate) const DISABLE_GDB_PRETTY_PRINTERS: &str = "disable-gdb-pretty-printers";
263 pub(crate) const COMPARE_OUTPUT_BY_LINES: &str = "compare-output-by-lines";
264}
265
266impl TestProps {
267 pub(crate) fn new() -> Self {
268 TestProps {
269 error_patterns: vec![],
270 regex_error_patterns: vec![],
271 edition: None,
272 compile_flags: vec![],
273 run_flags: vec![],
274 doc_flags: vec![],
275 pp_exact: None,
276 aux: Default::default(),
277 revisions: vec![],
278 rustc_env: vec![
279 ("RUSTC_ICE".to_string(), "0".to_string()),
280 ("RUST_BACKTRACE".to_string(), "short".to_string()),
281 ],
282 unset_rustc_env: vec![("RUSTC_LOG_COLOR".to_string())],
283 exec_env: vec![],
284 unset_exec_env: vec![],
285 build_aux_docs: false,
286 unique_doc_out_dir: false,
287 force_host: false,
288 check_stdout: false,
289 check_run_results: false,
290 dont_check_compiler_stdout: false,
291 dont_check_compiler_stderr: false,
292 no_prefer_dynamic: false,
293 pretty_mode: "normal".to_string(),
294 pretty_compare_only: false,
295 forbid_output: vec![],
296 incremental_dir: None,
297 incremental: false,
298 known_bug: false,
299 pass_mode: None,
300 fail_mode: None,
301 ignore_pass: false,
302 check_test_line_numbers_match: false,
303 normalize_stdout: vec![],
304 normalize_stderr: vec![],
305 failure_status: None,
306 dont_check_failure_status: false,
307 run_rustfix: false,
308 rustfix_only_machine_applicable: false,
309 assembly_output: None,
310 stderr_per_bitwidth: false,
311 mir_unit_test: None,
312 remap_src_base: false,
313 llvm_cov_flags: vec![],
314 skip_filecheck: false,
315 filecheck_flags: vec![],
316 no_auto_check_cfg: false,
317 add_minicore: false,
318 minicore_compile_flags: vec![],
319 dont_require_annotations: Default::default(),
320 disable_gdb_pretty_printers: false,
321 compare_output_by_lines: false,
322 }
323 }
324
325 pub(crate) fn from_aux_file(
326 &self,
327 testfile: &Utf8Path,
328 revision: Option<&str>,
329 config: &Config,
330 ) -> Self {
331 let mut props = TestProps::new();
332
333 props.incremental_dir = self.incremental_dir.clone();
335 props.ignore_pass = true;
336 props.load_from(testfile, revision, config);
337
338 props
339 }
340
341 pub(crate) fn from_file(testfile: &Utf8Path, revision: Option<&str>, config: &Config) -> Self {
342 let mut props = TestProps::new();
343 props.load_from(testfile, revision, config);
344 props.exec_env.push(("RUSTC".to_string(), config.rustc_path.to_string()));
345
346 match (props.pass_mode, props.fail_mode) {
347 (None, None) if config.mode == TestMode::Ui => props.fail_mode = Some(FailMode::Check),
348 (Some(_), Some(_)) => panic!("cannot use a *-fail and *-pass mode together"),
349 _ => {}
350 }
351
352 props
353 }
354
355 fn load_from(&mut self, testfile: &Utf8Path, test_revision: Option<&str>, config: &Config) {
360 if !testfile.is_dir() {
361 let file_contents = fs::read_to_string(testfile).unwrap();
362 let file_directives = FileDirectives::from_file_contents(testfile, &file_contents);
363
364 iter_directives(
365 config,
366 &file_directives,
367 &mut |ln: &DirectiveLine<'_>| {
369 if !ln.applies_to_test_revision(test_revision) {
370 return;
371 }
372
373 if let Some(handler) = DIRECTIVE_HANDLERS_MAP.get(ln.name) {
374 handler.handle(config, ln, self);
375 }
376 },
377 );
378 }
379
380 if config.mode == TestMode::Incremental {
381 self.incremental = true;
382 }
383
384 if config.mode == TestMode::Crashes {
385 self.rustc_env = vec![
389 ("RUST_BACKTRACE".to_string(), "0".to_string()),
390 ("RUSTC_ICE".to_string(), "0".to_string()),
391 ];
392 }
393
394 for key in &["RUST_TEST_NOCAPTURE", "RUST_TEST_THREADS"] {
395 if let Ok(val) = env::var(key) {
396 if !self.exec_env.iter().any(|&(ref x, _)| x == key) {
397 self.exec_env.push(((*key).to_owned(), val))
398 }
399 }
400 }
401
402 if let Some(edition) = self.edition.or(config.edition) {
403 self.compile_flags.insert(0, format!("--edition={edition}"));
406 }
407 }
408
409 fn update_fail_mode(&mut self, ln: &DirectiveLine<'_>, config: &Config) {
410 let check_ui = |mode: &str| {
411 if config.mode != TestMode::Ui {
412 panic!("`{}-fail` directive is only supported in UI tests", mode);
413 }
414 };
415 let fail_mode = if config.parse_name_directive(ln, "check-fail") {
416 check_ui("check");
417 Some(FailMode::Check)
418 } else if config.parse_name_directive(ln, "build-fail") {
419 check_ui("build");
420 Some(FailMode::Build)
421 } else if config.parse_name_directive(ln, "run-fail") {
422 check_ui("run");
423 Some(FailMode::Run(RunFailMode::Fail))
424 } else if config.parse_name_directive(ln, "run-crash") {
425 check_ui("run");
426 Some(FailMode::Run(RunFailMode::Crash))
427 } else if config.parse_name_directive(ln, "run-fail-or-crash") {
428 check_ui("run");
429 Some(FailMode::Run(RunFailMode::FailOrCrash))
430 } else {
431 None
432 };
433 match (self.fail_mode, fail_mode) {
434 (None, Some(_)) => self.fail_mode = fail_mode,
435 (Some(_), Some(_)) => panic!("multiple `*-fail` directives in a single test"),
436 (_, None) => {}
437 }
438 }
439
440 fn update_pass_mode(&mut self, ln: &DirectiveLine<'_>, config: &Config) {
441 let check_no_run = |s| match (config.mode, s) {
442 (TestMode::Ui, _) => (),
443 (mode, _) => panic!("`{s}` directive is not supported in `{mode}` tests"),
444 };
445 let pass_mode = if config.parse_name_directive(ln, "check-pass") {
446 check_no_run("check-pass");
447 Some(PassMode::Check)
448 } else if config.parse_name_directive(ln, "build-pass") {
449 check_no_run("build-pass");
450 Some(PassMode::Build)
451 } else if config.parse_name_directive(ln, "run-pass") {
452 check_no_run("run-pass");
453 Some(PassMode::Run)
454 } else {
455 None
456 };
457 match (self.pass_mode, pass_mode) {
458 (None, Some(_)) => self.pass_mode = pass_mode,
459 (Some(_), Some(_)) => panic!("multiple `*-pass` directives in a single test"),
460 (_, None) => {}
461 }
462 }
463
464 pub(crate) fn pass_mode(&self, config: &Config) -> Option<PassMode> {
465 if !self.ignore_pass && self.fail_mode.is_none() {
466 if let mode @ Some(_) = config.force_pass_mode {
467 return mode;
468 }
469 }
470 self.pass_mode
471 }
472
473 pub(crate) fn local_pass_mode(&self) -> Option<PassMode> {
475 self.pass_mode
476 }
477
478 fn update_add_minicore(&mut self, ln: &DirectiveLine<'_>, config: &Config) {
479 let add_minicore = config.parse_name_directive(ln, directives::ADD_MINICORE);
480 if add_minicore {
481 if !matches!(
482 config.mode,
483 TestMode::Ui | TestMode::Codegen | TestMode::Assembly | TestMode::MirOpt
484 ) {
485 panic!(
486 "`add-minicore` is currently only supported for ui, codegen, assembly and mir-opt test modes"
487 );
488 }
489
490 if self.local_pass_mode().is_some_and(|pm| pm == PassMode::Run) {
493 panic!("`add-minicore` cannot be used to run the test binary");
496 }
497
498 self.add_minicore = add_minicore;
499 }
500 }
501}
502
503pub(crate) fn do_early_directives_check(
504 mode: TestMode,
505 file_directives: &FileDirectives<'_>,
506) -> Result<(), String> {
507 let testfile = file_directives.path;
508
509 for directive_line @ DirectiveLine { line_number, .. } in &file_directives.lines {
510 let CheckDirectiveResult { is_known_directive, trailing_directive } =
511 check_directive(directive_line, mode);
512
513 if !is_known_directive {
514 return Err(format!(
515 "ERROR: unknown compiletest directive `{directive}` at {testfile}:{line_number}",
516 directive = directive_line.display(),
517 ));
518 }
519
520 if let Some(trailing_directive) = &trailing_directive {
521 return Err(format!(
522 "ERROR: detected trailing compiletest directive `{trailing_directive}` at {testfile}:{line_number}\n\
523 HELP: put the directive on its own line: `//@ {trailing_directive}`"
524 ));
525 }
526 }
527
528 Ok(())
529}
530
531pub(crate) struct CheckDirectiveResult<'ln> {
532 is_known_directive: bool,
533 trailing_directive: Option<&'ln str>,
534}
535
536fn check_directive<'a>(
537 directive_ln: &DirectiveLine<'a>,
538 mode: TestMode,
539) -> CheckDirectiveResult<'a> {
540 let &DirectiveLine { name: directive_name, .. } = directive_ln;
541
542 let is_known_directive = KNOWN_DIRECTIVE_NAMES_SET.contains(&directive_name)
543 || match mode {
544 TestMode::RustdocHtml => KNOWN_HTMLDOCCK_DIRECTIVE_NAMES.contains(&directive_name),
545 TestMode::RustdocJson => KNOWN_JSONDOCCK_DIRECTIVE_NAMES.contains(&directive_name),
546 _ => false,
547 };
548
549 let trailing_directive = directive_ln
553 .remark_after_space()
554 .map(|remark| remark.trim_start().split(' ').next().unwrap())
555 .filter(|token| KNOWN_DIRECTIVE_NAMES_SET.contains(token));
556
557 CheckDirectiveResult { is_known_directive, trailing_directive }
563}
564
565fn iter_directives(
566 config: &Config,
567 file_directives: &FileDirectives<'_>,
568 it: &mut dyn FnMut(&DirectiveLine<'_>),
569) {
570 let testfile = file_directives.path;
571
572 let extra_directives = match config.mode {
573 TestMode::CoverageRun => {
574 vec![
579 "//@ needs-profiler-runtime",
580 "//@ ignore-cross-compile",
584 ]
585 }
586 TestMode::Codegen if !file_directives.has_explicit_no_std_core_attribute => {
587 vec!["//@ needs-target-std"]
594 }
595 TestMode::Ui if config.parallel_frontend_enabled() => {
596 vec!["//@ compare-output-by-lines"]
599 }
600
601 _ => {
602 vec![]
604 }
605 };
606
607 for directive_str in extra_directives {
608 let directive_line = line_directive(testfile, LineNumber::ZERO, directive_str)
609 .unwrap_or_else(|| panic!("bad extra-directive line: {directive_str:?}"));
610 it(&directive_line);
611 }
612
613 for directive_line in &file_directives.lines {
614 it(directive_line);
615 }
616}
617
618impl Config {
619 fn parse_and_update_revisions(&self, line: &DirectiveLine<'_>, existing: &mut Vec<String>) {
620 const FORBIDDEN_REVISION_NAMES: [&str; 2] = [
621 "true", "false",
625 ];
626
627 const FILECHECK_FORBIDDEN_REVISION_NAMES: [&str; 9] =
628 ["CHECK", "COM", "NEXT", "SAME", "EMPTY", "NOT", "COUNT", "DAG", "LABEL"];
629
630 if let Some(raw) = self.parse_name_value_directive(line, "revisions") {
631 let &DirectiveLine { file_path: testfile, .. } = line;
632
633 if self.mode == TestMode::RunMake {
634 panic!("`run-make` mode tests do not support revisions: {}", testfile);
635 }
636
637 let mut duplicates: HashSet<_> = existing.iter().cloned().collect();
638 for revision in raw.split_whitespace() {
639 if !duplicates.insert(revision.to_string()) {
640 panic!("duplicate revision: `{}` in line `{}`: {}", revision, raw, testfile);
641 }
642
643 if FORBIDDEN_REVISION_NAMES.contains(&revision) {
644 panic!(
645 "revision name `{revision}` is not permitted: `{}` in line `{}`: {}",
646 revision, raw, testfile
647 );
648 }
649
650 if matches!(self.mode, TestMode::Assembly | TestMode::Codegen | TestMode::MirOpt)
651 && FILECHECK_FORBIDDEN_REVISION_NAMES.contains(&revision)
652 {
653 panic!(
654 "revision name `{revision}` is not permitted in a test suite that uses \
655 `FileCheck` annotations as it is confusing when used as custom `FileCheck` \
656 prefix: `{revision}` in line `{}`: {}",
657 raw, testfile
658 );
659 }
660
661 existing.push(revision.to_string());
662 }
663 }
664 }
665
666 fn parse_env(nv: String) -> (String, String) {
667 let (name, value) = nv.split_once('=').unwrap_or((&nv, ""));
671 let name = name.trim();
674 (name.to_owned(), value.to_owned())
675 }
676
677 fn parse_pp_exact(&self, line: &DirectiveLine<'_>) -> Option<Utf8PathBuf> {
678 if let Some(s) = self.parse_name_value_directive(line, "pp-exact") {
679 Some(Utf8PathBuf::from(&s))
680 } else if self.parse_name_directive(line, "pp-exact") {
681 line.file_path.file_name().map(Utf8PathBuf::from)
682 } else {
683 None
684 }
685 }
686
687 fn parse_custom_normalization(&self, line: &DirectiveLine<'_>) -> Option<NormalizeRule> {
688 let &DirectiveLine { name, .. } = line;
689
690 let kind = match name {
691 "normalize-stdout" => NormalizeKind::Stdout,
692 "normalize-stderr" => NormalizeKind::Stderr,
693 "normalize-stderr-32bit" => NormalizeKind::Stderr32bit,
694 "normalize-stderr-64bit" => NormalizeKind::Stderr64bit,
695 _ => return None,
696 };
697
698 let Some((regex, replacement)) = line.value_after_colon().and_then(parse_normalize_rule)
699 else {
700 error!("couldn't parse custom normalization rule: `{}`", line.display());
701 help!("expected syntax is: `{name}: \"REGEX\" -> \"REPLACEMENT\"`");
702 panic!("invalid normalization rule detected");
703 };
704 Some(NormalizeRule { kind, regex, replacement })
705 }
706
707 fn parse_name_directive(&self, line: &DirectiveLine<'_>, directive: &str) -> bool {
708 line.name == directive
712 }
713
714 fn parse_name_value_directive(
715 &self,
716 line: &DirectiveLine<'_>,
717 directive: &str,
718 ) -> Option<String> {
719 let &DirectiveLine { file_path, line_number, .. } = line;
720
721 if line.name != directive {
722 return None;
723 };
724
725 let value = line.value_after_colon()?;
729 debug!("{}: {}", directive, value);
730 let value = expand_variables(value.to_owned(), self);
731
732 if value.is_empty() {
733 error!("{file_path}:{line_number}: empty value for directive `{directive}`");
734 help!("expected syntax is: `{directive}: value`");
735 panic!("empty directive value detected");
736 }
737
738 Some(value)
739 }
740
741 fn set_name_directive(&self, line: &DirectiveLine<'_>, directive: &str, value: &mut bool) {
742 *value = *value || self.parse_name_directive(line, directive);
744 }
745
746 fn set_name_value_directive<T>(
747 &self,
748 line: &DirectiveLine<'_>,
749 directive: &str,
750 value: &mut Option<T>,
751 parse: impl FnOnce(String) -> T,
752 ) {
753 if value.is_none() {
754 *value = self.parse_name_value_directive(line, directive).map(parse);
755 }
756 }
757
758 fn push_name_value_directive<T>(
759 &self,
760 line: &DirectiveLine<'_>,
761 directive: &str,
762 values: &mut Vec<T>,
763 parse: impl FnOnce(String) -> T,
764 ) {
765 if let Some(value) = self.parse_name_value_directive(line, directive).map(parse) {
766 values.push(value);
767 }
768 }
769}
770
771fn expand_variables(mut value: String, config: &Config) -> String {
773 const CWD: &str = "{{cwd}}";
774 const SRC_BASE: &str = "{{src-base}}";
775 const TEST_SUITE_BUILD_BASE: &str = "{{build-base}}";
776 const RUST_SRC_BASE: &str = "{{rust-src-base}}";
777 const SYSROOT_BASE: &str = "{{sysroot-base}}";
778 const TARGET_LINKER: &str = "{{target-linker}}";
779 const TARGET: &str = "{{target}}";
780
781 if value.contains(CWD) {
782 let cwd = env::current_dir().unwrap();
783 value = value.replace(CWD, &cwd.to_str().unwrap());
784 }
785
786 if value.contains(SRC_BASE) {
787 value = value.replace(SRC_BASE, &config.src_test_suite_root.as_str());
788 }
789
790 if value.contains(TEST_SUITE_BUILD_BASE) {
791 value = value.replace(TEST_SUITE_BUILD_BASE, &config.build_test_suite_root.as_str());
792 }
793
794 if value.contains(SYSROOT_BASE) {
795 value = value.replace(SYSROOT_BASE, &config.sysroot_base.as_str());
796 }
797
798 if value.contains(TARGET_LINKER) {
799 value = value.replace(TARGET_LINKER, config.target_linker.as_deref().unwrap_or(""));
800 }
801
802 if value.contains(TARGET) {
803 value = value.replace(TARGET, &config.target);
804 }
805
806 if value.contains(RUST_SRC_BASE) {
807 let src_base = config.sysroot_base.join("lib/rustlib/src/rust");
808 src_base.try_exists().expect(&*format!("{} should exists", src_base));
809 let src_base = src_base.read_link_utf8().unwrap_or(src_base);
810 value = value.replace(RUST_SRC_BASE, &src_base.as_str());
811 }
812
813 value
814}
815
816struct NormalizeRule {
817 kind: NormalizeKind,
818 regex: String,
819 replacement: String,
820}
821
822enum NormalizeKind {
823 Stdout,
824 Stderr,
825 Stderr32bit,
826 Stderr64bit,
827}
828
829fn parse_normalize_rule(raw_value: &str) -> Option<(String, String)> {
834 let captures = static_regex!(
836 r#"(?x) # (verbose mode regex)
837 ^
838 \s* # (leading whitespace)
839 "(?<regex>[^"]*)" # "REGEX"
840 \s+->\s+ # ->
841 "(?<replacement>[^"]*)" # "REPLACEMENT"
842 $
843 "#
844 )
845 .captures(raw_value)?;
846 let regex = captures["regex"].to_owned();
847 let replacement = captures["replacement"].to_owned();
848 let replacement = replacement.replace("\\n", "\n");
852 Some((regex, replacement))
853}
854
855pub(crate) fn extract_llvm_version(version: &str) -> Version {
865 let version = version.trim();
868 let uninterested = |c: char| !c.is_ascii_digit() && c != '.';
869 let version_without_suffix = match version.split_once(uninterested) {
870 Some((prefix, _suffix)) => prefix,
871 None => version,
872 };
873
874 let components: Vec<u64> = version_without_suffix
875 .split('.')
876 .map(|s| s.parse().expect("llvm version component should consist of only digits"))
877 .collect();
878
879 match &components[..] {
880 [major] => Version::new(*major, 0, 0),
881 [major, minor] => Version::new(*major, *minor, 0),
882 [major, minor, patch] => Version::new(*major, *minor, *patch),
883 _ => panic!("malformed llvm version string, expected only 1-3 components: {version}"),
884 }
885}
886
887pub(crate) fn extract_llvm_version_from_binary(binary_path: &str) -> Option<Version> {
888 let output = Command::new(binary_path).arg("--version").output().ok()?;
889 if !output.status.success() {
890 return None;
891 }
892 let version = String::from_utf8(output.stdout).ok()?;
893 for line in version.lines() {
894 if let Some(version) = line.split("LLVM version ").nth(1) {
895 return Some(extract_llvm_version(version));
896 }
897 }
898 None
899}
900
901fn extract_version_range<'a, F, VersionTy: Clone>(
907 line: &'a str,
908 parse: F,
909) -> Option<(VersionTy, VersionTy)>
910where
911 F: Fn(&'a str) -> Option<VersionTy>,
912{
913 let mut splits = line.splitn(2, "- ").map(str::trim);
914 let min = splits.next().unwrap();
915 if min.ends_with('-') {
916 return None;
917 }
918
919 let max = splits.next();
920
921 if min.is_empty() {
922 return None;
923 }
924
925 let min = parse(min)?;
926 let max = match max {
927 Some("") => return None,
928 Some(max) => parse(max)?,
929 _ => min.clone(),
930 };
931
932 Some((min, max))
933}
934
935pub(crate) fn make_test_description(
936 config: &Config,
937 cache: &DirectivesCache,
938 name: String,
939 path: &Utf8Path,
940 filterable_path: &Utf8Path,
941 file_directives: &FileDirectives<'_>,
942 test_revision: Option<&str>,
943 poisoned: &mut bool,
944 aux_props: &mut AuxProps,
945) -> CollectedTestDesc {
946 let mut ignore = false;
947 let mut ignore_message = None;
948 let mut should_fail = false;
949
950 iter_directives(config, file_directives, &mut |ln @ &DirectiveLine { line_number, .. }| {
952 if !ln.applies_to_test_revision(test_revision) {
953 return;
954 }
955
956 parse_and_update_aux(config, ln, aux_props);
958
959 macro_rules! decision {
960 ($e:expr) => {
961 match $e {
962 IgnoreDecision::Ignore { reason } => {
963 ignore = true;
964 ignore_message = Some(reason.into());
965 }
966 IgnoreDecision::Error { message } => {
967 error!("{path}:{line_number}: {message}");
968 *poisoned = true;
969 return;
970 }
971 IgnoreDecision::Continue => {}
972 }
973 };
974 }
975
976 decision!(cfg::handle_ignore(&cache.cfg_conditions, ln));
977 decision!(cfg::handle_only(&cache.cfg_conditions, ln));
978 decision!(needs::handle_needs(&cache.needs, config, ln));
979 decision!(ignore_llvm(config, ln));
980 decision!(ignore_backends(config, ln));
981 decision!(needs_backends(config, ln));
982 decision!(ignore_cdb(config, ln));
983 decision!(ignore_gdb(config, ln));
984 decision!(ignore_lldb(config, ln));
985 decision!(ignore_parallel_frontend(config, ln));
986
987 if config.target == "wasm32-unknown-unknown"
988 && config.parse_name_directive(ln, directives::CHECK_RUN_RESULTS)
989 {
990 decision!(IgnoreDecision::Ignore {
991 reason: "ignored on WASM as the run results cannot be checked there".into(),
992 });
993 }
994
995 should_fail |= config.parse_name_directive(ln, "should-fail");
996 });
997
998 let should_fail = if should_fail && config.mode != TestMode::Pretty {
1002 ShouldFail::Yes
1003 } else {
1004 ShouldFail::No
1005 };
1006
1007 CollectedTestDesc {
1008 name,
1009 filterable_path: filterable_path.to_owned(),
1010 ignore,
1011 ignore_message,
1012 should_fail,
1013 }
1014}
1015
1016fn ignore_cdb(config: &Config, line: &DirectiveLine<'_>) -> IgnoreDecision {
1017 if config.debugger != Some(Debugger::Cdb) {
1018 return IgnoreDecision::Continue;
1019 }
1020
1021 if let Some(actual_version) = config.cdb_version {
1022 if line.name == "min-cdb-version"
1023 && let Some(rest) = line.value_after_colon().map(str::trim)
1024 {
1025 let min_version = extract_cdb_version(rest).unwrap_or_else(|| {
1026 panic!("couldn't parse version range: {:?}", rest);
1027 });
1028
1029 if actual_version < min_version {
1032 return IgnoreDecision::Ignore {
1033 reason: format!("ignored when the CDB version is lower than {rest}"),
1034 };
1035 }
1036 }
1037 }
1038 IgnoreDecision::Continue
1039}
1040
1041fn ignore_gdb(config: &Config, line: &DirectiveLine<'_>) -> IgnoreDecision {
1042 if config.debugger != Some(Debugger::Gdb) {
1043 return IgnoreDecision::Continue;
1044 }
1045
1046 if let Some(actual_version) = config.gdb_version {
1047 if line.name == "min-gdb-version"
1048 && let Some(rest) = line.value_after_colon().map(str::trim)
1049 {
1050 let (start_ver, end_ver) = extract_version_range(rest, extract_gdb_version)
1051 .unwrap_or_else(|| {
1052 panic!("couldn't parse version range: {:?}", rest);
1053 });
1054
1055 if start_ver != end_ver {
1056 panic!("Expected single GDB version")
1057 }
1058 if actual_version < start_ver {
1061 return IgnoreDecision::Ignore {
1062 reason: format!("ignored when the GDB version is lower than {rest}"),
1063 };
1064 }
1065 } else if line.name == "ignore-gdb-version"
1066 && let Some(rest) = line.value_after_colon().map(str::trim)
1067 {
1068 let (min_version, max_version) = extract_version_range(rest, extract_gdb_version)
1069 .unwrap_or_else(|| {
1070 panic!("couldn't parse version range: {:?}", rest);
1071 });
1072
1073 if max_version < min_version {
1074 panic!("Malformed GDB version range: max < min")
1075 }
1076
1077 if actual_version >= min_version && actual_version <= max_version {
1078 if min_version == max_version {
1079 return IgnoreDecision::Ignore {
1080 reason: format!("ignored when the GDB version is {rest}"),
1081 };
1082 } else {
1083 return IgnoreDecision::Ignore {
1084 reason: format!("ignored when the GDB version is between {rest}"),
1085 };
1086 }
1087 }
1088 }
1089 }
1090 IgnoreDecision::Continue
1091}
1092
1093fn ignore_lldb(config: &Config, line: &DirectiveLine<'_>) -> IgnoreDecision {
1094 if config.debugger != Some(Debugger::Lldb) {
1095 return IgnoreDecision::Continue;
1096 }
1097
1098 if let Some(actual_version) = config.lldb_version {
1099 if line.name == "min-lldb-version"
1100 && let Some(rest) = line.value_after_colon().map(str::trim)
1101 {
1102 let min_version = rest.parse().unwrap_or_else(|e| {
1103 panic!("Unexpected format of LLDB version string: {}\n{:?}", rest, e);
1104 });
1105 if actual_version < min_version {
1108 return IgnoreDecision::Ignore {
1109 reason: format!("ignored when the LLDB version is {rest}"),
1110 };
1111 }
1112 }
1113 }
1114 IgnoreDecision::Continue
1115}
1116
1117fn ignore_backends(config: &Config, line: &DirectiveLine<'_>) -> IgnoreDecision {
1118 let path = line.file_path;
1119 if let Some(backends_to_ignore) = config.parse_name_value_directive(line, "ignore-backends") {
1120 for backend in backends_to_ignore.split_whitespace().map(|backend| {
1121 match CodegenBackend::try_from(backend) {
1122 Ok(backend) => backend,
1123 Err(error) => {
1124 panic!("Invalid ignore-backends value `{backend}` in `{path}`: {error}")
1125 }
1126 }
1127 }) {
1128 if !config.bypass_ignore_backends && config.default_codegen_backend == backend {
1129 return IgnoreDecision::Ignore {
1130 reason: format!("{} backend is marked as ignore", backend.as_str()),
1131 };
1132 }
1133 }
1134 }
1135 IgnoreDecision::Continue
1136}
1137
1138fn needs_backends(config: &Config, line: &DirectiveLine<'_>) -> IgnoreDecision {
1139 let path = line.file_path;
1140 if let Some(needed_backends) = config.parse_name_value_directive(line, "needs-backends") {
1141 if !needed_backends
1142 .split_whitespace()
1143 .map(|backend| match CodegenBackend::try_from(backend) {
1144 Ok(backend) => backend,
1145 Err(error) => {
1146 panic!("Invalid needs-backends value `{backend}` in `{path}`: {error}")
1147 }
1148 })
1149 .any(|backend| config.default_codegen_backend == backend)
1150 {
1151 return IgnoreDecision::Ignore {
1152 reason: format!(
1153 "{} backend is not part of required backends",
1154 config.default_codegen_backend.as_str()
1155 ),
1156 };
1157 }
1158 }
1159 IgnoreDecision::Continue
1160}
1161
1162fn ignore_llvm(config: &Config, line: &DirectiveLine<'_>) -> IgnoreDecision {
1163 let path = line.file_path;
1164 if let Some(needed_components) =
1165 config.parse_name_value_directive(line, "needs-llvm-components")
1166 {
1167 let components: HashSet<_> = config.llvm_components.split_whitespace().collect();
1168 if let Some(missing_component) = needed_components
1169 .split_whitespace()
1170 .find(|needed_component| !components.contains(needed_component))
1171 {
1172 if env::var_os("COMPILETEST_REQUIRE_ALL_LLVM_COMPONENTS").is_some() {
1173 panic!(
1174 "missing LLVM component {missing_component}, \
1175 and COMPILETEST_REQUIRE_ALL_LLVM_COMPONENTS is set: {path}",
1176 );
1177 }
1178 return IgnoreDecision::Ignore {
1179 reason: format!("ignored when the {missing_component} LLVM component is missing"),
1180 };
1181 }
1182 }
1183 if let Some(actual_version) = &config.llvm_version {
1184 if let Some(version_string) = config.parse_name_value_directive(line, "min-llvm-version") {
1187 let min_version = extract_llvm_version(&version_string);
1188 if *actual_version < min_version {
1190 return IgnoreDecision::Ignore {
1191 reason: format!(
1192 "ignored when the LLVM version {actual_version} is older than {min_version}"
1193 ),
1194 };
1195 }
1196 } else if let Some(version_string) =
1197 config.parse_name_value_directive(line, "max-llvm-major-version")
1198 {
1199 let max_version = extract_llvm_version(&version_string);
1200 if actual_version.major > max_version.major {
1202 return IgnoreDecision::Ignore {
1203 reason: format!(
1204 "ignored when the LLVM version ({actual_version}) is newer than major\
1205 version {}",
1206 max_version.major
1207 ),
1208 };
1209 }
1210 } else if let Some(version_string) =
1211 config.parse_name_value_directive(line, "min-system-llvm-version")
1212 {
1213 let min_version = extract_llvm_version(&version_string);
1214 if config.system_llvm && *actual_version < min_version {
1217 return IgnoreDecision::Ignore {
1218 reason: format!(
1219 "ignored when the system LLVM version {actual_version} is older than {min_version}"
1220 ),
1221 };
1222 }
1223 } else if let Some(version_range) =
1224 config.parse_name_value_directive(line, "ignore-llvm-version")
1225 {
1226 let (v_min, v_max) =
1228 extract_version_range(&version_range, |s| Some(extract_llvm_version(s)))
1229 .unwrap_or_else(|| {
1230 panic!("couldn't parse version range: \"{version_range}\"");
1231 });
1232 if v_max < v_min {
1233 panic!("malformed LLVM version range where {v_max} < {v_min}")
1234 }
1235 if *actual_version >= v_min && *actual_version <= v_max {
1237 if v_min == v_max {
1238 return IgnoreDecision::Ignore {
1239 reason: format!("ignored when the LLVM version is {actual_version}"),
1240 };
1241 } else {
1242 return IgnoreDecision::Ignore {
1243 reason: format!(
1244 "ignored when the LLVM version is between {v_min} and {v_max}"
1245 ),
1246 };
1247 }
1248 }
1249 } else if let Some(version_string) =
1250 config.parse_name_value_directive(line, "exact-llvm-major-version")
1251 {
1252 let version = extract_llvm_version(&version_string);
1254 if actual_version.major != version.major {
1255 return IgnoreDecision::Ignore {
1256 reason: format!(
1257 "ignored when the actual LLVM major version is {}, but the test only targets major version {}",
1258 actual_version.major, version.major
1259 ),
1260 };
1261 }
1262 }
1263 }
1264 IgnoreDecision::Continue
1265}
1266
1267fn ignore_parallel_frontend(config: &Config, line: &DirectiveLine<'_>) -> IgnoreDecision {
1268 if config.parallel_frontend_enabled()
1269 && config.parse_name_directive(line, "ignore-parallel-frontend")
1270 {
1271 return IgnoreDecision::Ignore {
1272 reason: "ignored when the parallel frontend is enabled".into(),
1273 };
1274 }
1275 IgnoreDecision::Continue
1276}
1277
1278enum IgnoreDecision {
1279 Ignore { reason: String },
1280 Continue,
1281 Error { message: String },
1282}
1283
1284fn parse_edition_range(config: &Config, line: &DirectiveLine<'_>) -> Option<EditionRange> {
1285 let raw = config.parse_name_value_directive(line, "edition")?;
1286 let &DirectiveLine { file_path: testfile, line_number, .. } = line;
1287
1288 if let Some((lower_bound, upper_bound)) = raw.split_once("..") {
1290 Some(match (maybe_parse_edition(lower_bound), maybe_parse_edition(upper_bound)) {
1291 (Some(lower_bound), Some(upper_bound)) if upper_bound <= lower_bound => {
1292 fatal!(
1293 "{testfile}:{line_number}: the left side of `//@ edition` cannot be greater than or equal to the right side"
1294 );
1295 }
1296 (Some(lower_bound), Some(upper_bound)) => {
1297 EditionRange::Range { lower_bound, upper_bound }
1298 }
1299 (Some(lower_bound), None) => EditionRange::RangeFrom(lower_bound),
1300 (None, Some(_)) => {
1301 fatal!(
1302 "{testfile}:{line_number}: `..edition` is not a supported range in `//@ edition`"
1303 );
1304 }
1305 (None, None) => {
1306 fatal!("{testfile}:{line_number}: `..` is not a supported range in `//@ edition`");
1307 }
1308 })
1309 } else {
1310 match maybe_parse_edition(&raw) {
1311 Some(edition) => Some(EditionRange::Exact(edition)),
1312 None => {
1313 fatal!("{testfile}:{line_number}: empty value for `//@ edition`");
1314 }
1315 }
1316 }
1317}
1318
1319fn maybe_parse_edition(mut input: &str) -> Option<Edition> {
1320 input = input.trim();
1321 if input.is_empty() {
1322 return None;
1323 }
1324 Some(parse_edition(input))
1325}
1326
1327#[derive(Debug, PartialEq, Eq, Clone, Copy)]
1328enum EditionRange {
1329 Exact(Edition),
1330 RangeFrom(Edition),
1331 Range {
1333 lower_bound: Edition,
1334 upper_bound: Edition,
1335 },
1336}
1337
1338impl EditionRange {
1339 fn edition_to_test(&self, requested: impl Into<Option<Edition>>) -> Edition {
1340 let min_edition = Edition::Year(2015);
1341 let requested = requested.into().unwrap_or(min_edition);
1342
1343 match *self {
1344 EditionRange::Exact(exact) => exact,
1345 EditionRange::RangeFrom(lower_bound) => {
1346 if requested >= lower_bound {
1347 requested
1348 } else {
1349 lower_bound
1350 }
1351 }
1352 EditionRange::Range { lower_bound, upper_bound } => {
1353 if requested >= lower_bound && requested < upper_bound {
1354 requested
1355 } else {
1356 lower_bound
1357 }
1358 }
1359 }
1360 }
1361}
1362
1363fn split_flags(flags: &str) -> Vec<String> {
1364 flags
1369 .split('\'')
1370 .enumerate()
1371 .flat_map(|(i, f)| if i % 2 == 1 { vec![f] } else { f.split_whitespace().collect() })
1372 .map(move |s| s.to_owned())
1373 .collect::<Vec<_>>()
1374}