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!(config.mode, TestMode::Ui | TestMode::Codegen | TestMode::Assembly) {
482 panic!(
483 "`add-minicore` is currently only supported for ui, codegen and assembly test modes"
484 );
485 }
486
487 if self.local_pass_mode().is_some_and(|pm| pm == PassMode::Run) {
490 panic!("`add-minicore` cannot be used to run the test binary");
493 }
494
495 self.add_minicore = add_minicore;
496 }
497 }
498}
499
500pub(crate) fn do_early_directives_check(
501 mode: TestMode,
502 file_directives: &FileDirectives<'_>,
503) -> Result<(), String> {
504 let testfile = file_directives.path;
505
506 for directive_line @ DirectiveLine { line_number, .. } in &file_directives.lines {
507 let CheckDirectiveResult { is_known_directive, trailing_directive } =
508 check_directive(directive_line, mode);
509
510 if !is_known_directive {
511 return Err(format!(
512 "ERROR: unknown compiletest directive `{directive}` at {testfile}:{line_number}",
513 directive = directive_line.display(),
514 ));
515 }
516
517 if let Some(trailing_directive) = &trailing_directive {
518 return Err(format!(
519 "ERROR: detected trailing compiletest directive `{trailing_directive}` at {testfile}:{line_number}\n\
520 HELP: put the directive on its own line: `//@ {trailing_directive}`"
521 ));
522 }
523 }
524
525 Ok(())
526}
527
528pub(crate) struct CheckDirectiveResult<'ln> {
529 is_known_directive: bool,
530 trailing_directive: Option<&'ln str>,
531}
532
533fn check_directive<'a>(
534 directive_ln: &DirectiveLine<'a>,
535 mode: TestMode,
536) -> CheckDirectiveResult<'a> {
537 let &DirectiveLine { name: directive_name, .. } = directive_ln;
538
539 let is_known_directive = KNOWN_DIRECTIVE_NAMES_SET.contains(&directive_name)
540 || match mode {
541 TestMode::RustdocHtml => KNOWN_HTMLDOCCK_DIRECTIVE_NAMES.contains(&directive_name),
542 TestMode::RustdocJson => KNOWN_JSONDOCCK_DIRECTIVE_NAMES.contains(&directive_name),
543 _ => false,
544 };
545
546 let trailing_directive = directive_ln
550 .remark_after_space()
551 .map(|remark| remark.trim_start().split(' ').next().unwrap())
552 .filter(|token| KNOWN_DIRECTIVE_NAMES_SET.contains(token));
553
554 CheckDirectiveResult { is_known_directive, trailing_directive }
560}
561
562fn iter_directives(
563 config: &Config,
564 file_directives: &FileDirectives<'_>,
565 it: &mut dyn FnMut(&DirectiveLine<'_>),
566) {
567 let testfile = file_directives.path;
568
569 let extra_directives = match config.mode {
570 TestMode::CoverageRun => {
571 vec![
576 "//@ needs-profiler-runtime",
577 "//@ ignore-cross-compile",
581 ]
582 }
583 TestMode::Codegen if !file_directives.has_explicit_no_std_core_attribute => {
584 vec!["//@ needs-target-std"]
591 }
592 TestMode::Ui if config.parallel_frontend_enabled() => {
593 vec!["//@ compare-output-by-lines"]
596 }
597
598 _ => {
599 vec![]
601 }
602 };
603
604 for directive_str in extra_directives {
605 let directive_line = line_directive(testfile, LineNumber::ZERO, directive_str)
606 .unwrap_or_else(|| panic!("bad extra-directive line: {directive_str:?}"));
607 it(&directive_line);
608 }
609
610 for directive_line in &file_directives.lines {
611 it(directive_line);
612 }
613}
614
615impl Config {
616 fn parse_and_update_revisions(&self, line: &DirectiveLine<'_>, existing: &mut Vec<String>) {
617 const FORBIDDEN_REVISION_NAMES: [&str; 2] = [
618 "true", "false",
622 ];
623
624 const FILECHECK_FORBIDDEN_REVISION_NAMES: [&str; 9] =
625 ["CHECK", "COM", "NEXT", "SAME", "EMPTY", "NOT", "COUNT", "DAG", "LABEL"];
626
627 if let Some(raw) = self.parse_name_value_directive(line, "revisions") {
628 let &DirectiveLine { file_path: testfile, .. } = line;
629
630 if self.mode == TestMode::RunMake {
631 panic!("`run-make` mode tests do not support revisions: {}", testfile);
632 }
633
634 let mut duplicates: HashSet<_> = existing.iter().cloned().collect();
635 for revision in raw.split_whitespace() {
636 if !duplicates.insert(revision.to_string()) {
637 panic!("duplicate revision: `{}` in line `{}`: {}", revision, raw, testfile);
638 }
639
640 if FORBIDDEN_REVISION_NAMES.contains(&revision) {
641 panic!(
642 "revision name `{revision}` is not permitted: `{}` in line `{}`: {}",
643 revision, raw, testfile
644 );
645 }
646
647 if matches!(self.mode, TestMode::Assembly | TestMode::Codegen | TestMode::MirOpt)
648 && FILECHECK_FORBIDDEN_REVISION_NAMES.contains(&revision)
649 {
650 panic!(
651 "revision name `{revision}` is not permitted in a test suite that uses \
652 `FileCheck` annotations as it is confusing when used as custom `FileCheck` \
653 prefix: `{revision}` in line `{}`: {}",
654 raw, testfile
655 );
656 }
657
658 existing.push(revision.to_string());
659 }
660 }
661 }
662
663 fn parse_env(nv: String) -> (String, String) {
664 let (name, value) = nv.split_once('=').unwrap_or((&nv, ""));
668 let name = name.trim();
671 (name.to_owned(), value.to_owned())
672 }
673
674 fn parse_pp_exact(&self, line: &DirectiveLine<'_>) -> Option<Utf8PathBuf> {
675 if let Some(s) = self.parse_name_value_directive(line, "pp-exact") {
676 Some(Utf8PathBuf::from(&s))
677 } else if self.parse_name_directive(line, "pp-exact") {
678 line.file_path.file_name().map(Utf8PathBuf::from)
679 } else {
680 None
681 }
682 }
683
684 fn parse_custom_normalization(&self, line: &DirectiveLine<'_>) -> Option<NormalizeRule> {
685 let &DirectiveLine { name, .. } = line;
686
687 let kind = match name {
688 "normalize-stdout" => NormalizeKind::Stdout,
689 "normalize-stderr" => NormalizeKind::Stderr,
690 "normalize-stderr-32bit" => NormalizeKind::Stderr32bit,
691 "normalize-stderr-64bit" => NormalizeKind::Stderr64bit,
692 _ => return None,
693 };
694
695 let Some((regex, replacement)) = line.value_after_colon().and_then(parse_normalize_rule)
696 else {
697 error!("couldn't parse custom normalization rule: `{}`", line.display());
698 help!("expected syntax is: `{name}: \"REGEX\" -> \"REPLACEMENT\"`");
699 panic!("invalid normalization rule detected");
700 };
701 Some(NormalizeRule { kind, regex, replacement })
702 }
703
704 fn parse_name_directive(&self, line: &DirectiveLine<'_>, directive: &str) -> bool {
705 line.name == directive
709 }
710
711 fn parse_name_value_directive(
712 &self,
713 line: &DirectiveLine<'_>,
714 directive: &str,
715 ) -> Option<String> {
716 let &DirectiveLine { file_path, line_number, .. } = line;
717
718 if line.name != directive {
719 return None;
720 };
721
722 let value = line.value_after_colon()?;
726 debug!("{}: {}", directive, value);
727 let value = expand_variables(value.to_owned(), self);
728
729 if value.is_empty() {
730 error!("{file_path}:{line_number}: empty value for directive `{directive}`");
731 help!("expected syntax is: `{directive}: value`");
732 panic!("empty directive value detected");
733 }
734
735 Some(value)
736 }
737
738 fn set_name_directive(&self, line: &DirectiveLine<'_>, directive: &str, value: &mut bool) {
739 *value = *value || self.parse_name_directive(line, directive);
741 }
742
743 fn set_name_value_directive<T>(
744 &self,
745 line: &DirectiveLine<'_>,
746 directive: &str,
747 value: &mut Option<T>,
748 parse: impl FnOnce(String) -> T,
749 ) {
750 if value.is_none() {
751 *value = self.parse_name_value_directive(line, directive).map(parse);
752 }
753 }
754
755 fn push_name_value_directive<T>(
756 &self,
757 line: &DirectiveLine<'_>,
758 directive: &str,
759 values: &mut Vec<T>,
760 parse: impl FnOnce(String) -> T,
761 ) {
762 if let Some(value) = self.parse_name_value_directive(line, directive).map(parse) {
763 values.push(value);
764 }
765 }
766}
767
768fn expand_variables(mut value: String, config: &Config) -> String {
770 const CWD: &str = "{{cwd}}";
771 const SRC_BASE: &str = "{{src-base}}";
772 const TEST_SUITE_BUILD_BASE: &str = "{{build-base}}";
773 const RUST_SRC_BASE: &str = "{{rust-src-base}}";
774 const SYSROOT_BASE: &str = "{{sysroot-base}}";
775 const TARGET_LINKER: &str = "{{target-linker}}";
776 const TARGET: &str = "{{target}}";
777
778 if value.contains(CWD) {
779 let cwd = env::current_dir().unwrap();
780 value = value.replace(CWD, &cwd.to_str().unwrap());
781 }
782
783 if value.contains(SRC_BASE) {
784 value = value.replace(SRC_BASE, &config.src_test_suite_root.as_str());
785 }
786
787 if value.contains(TEST_SUITE_BUILD_BASE) {
788 value = value.replace(TEST_SUITE_BUILD_BASE, &config.build_test_suite_root.as_str());
789 }
790
791 if value.contains(SYSROOT_BASE) {
792 value = value.replace(SYSROOT_BASE, &config.sysroot_base.as_str());
793 }
794
795 if value.contains(TARGET_LINKER) {
796 value = value.replace(TARGET_LINKER, config.target_linker.as_deref().unwrap_or(""));
797 }
798
799 if value.contains(TARGET) {
800 value = value.replace(TARGET, &config.target);
801 }
802
803 if value.contains(RUST_SRC_BASE) {
804 let src_base = config.sysroot_base.join("lib/rustlib/src/rust");
805 src_base.try_exists().expect(&*format!("{} should exists", src_base));
806 let src_base = src_base.read_link_utf8().unwrap_or(src_base);
807 value = value.replace(RUST_SRC_BASE, &src_base.as_str());
808 }
809
810 value
811}
812
813struct NormalizeRule {
814 kind: NormalizeKind,
815 regex: String,
816 replacement: String,
817}
818
819enum NormalizeKind {
820 Stdout,
821 Stderr,
822 Stderr32bit,
823 Stderr64bit,
824}
825
826fn parse_normalize_rule(raw_value: &str) -> Option<(String, String)> {
831 let captures = static_regex!(
833 r#"(?x) # (verbose mode regex)
834 ^
835 \s* # (leading whitespace)
836 "(?<regex>[^"]*)" # "REGEX"
837 \s+->\s+ # ->
838 "(?<replacement>[^"]*)" # "REPLACEMENT"
839 $
840 "#
841 )
842 .captures(raw_value)?;
843 let regex = captures["regex"].to_owned();
844 let replacement = captures["replacement"].to_owned();
845 let replacement = replacement.replace("\\n", "\n");
849 Some((regex, replacement))
850}
851
852pub(crate) fn extract_llvm_version(version: &str) -> Version {
862 let version = version.trim();
865 let uninterested = |c: char| !c.is_ascii_digit() && c != '.';
866 let version_without_suffix = match version.split_once(uninterested) {
867 Some((prefix, _suffix)) => prefix,
868 None => version,
869 };
870
871 let components: Vec<u64> = version_without_suffix
872 .split('.')
873 .map(|s| s.parse().expect("llvm version component should consist of only digits"))
874 .collect();
875
876 match &components[..] {
877 [major] => Version::new(*major, 0, 0),
878 [major, minor] => Version::new(*major, *minor, 0),
879 [major, minor, patch] => Version::new(*major, *minor, *patch),
880 _ => panic!("malformed llvm version string, expected only 1-3 components: {version}"),
881 }
882}
883
884pub(crate) fn extract_llvm_version_from_binary(binary_path: &str) -> Option<Version> {
885 let output = Command::new(binary_path).arg("--version").output().ok()?;
886 if !output.status.success() {
887 return None;
888 }
889 let version = String::from_utf8(output.stdout).ok()?;
890 for line in version.lines() {
891 if let Some(version) = line.split("LLVM version ").nth(1) {
892 return Some(extract_llvm_version(version));
893 }
894 }
895 None
896}
897
898fn extract_version_range<'a, F, VersionTy: Clone>(
904 line: &'a str,
905 parse: F,
906) -> Option<(VersionTy, VersionTy)>
907where
908 F: Fn(&'a str) -> Option<VersionTy>,
909{
910 let mut splits = line.splitn(2, "- ").map(str::trim);
911 let min = splits.next().unwrap();
912 if min.ends_with('-') {
913 return None;
914 }
915
916 let max = splits.next();
917
918 if min.is_empty() {
919 return None;
920 }
921
922 let min = parse(min)?;
923 let max = match max {
924 Some("") => return None,
925 Some(max) => parse(max)?,
926 _ => min.clone(),
927 };
928
929 Some((min, max))
930}
931
932pub(crate) fn make_test_description(
933 config: &Config,
934 cache: &DirectivesCache,
935 name: String,
936 path: &Utf8Path,
937 filterable_path: &Utf8Path,
938 file_directives: &FileDirectives<'_>,
939 test_revision: Option<&str>,
940 poisoned: &mut bool,
941 aux_props: &mut AuxProps,
942) -> CollectedTestDesc {
943 let mut ignore = false;
944 let mut ignore_message = None;
945 let mut should_fail = false;
946
947 iter_directives(config, file_directives, &mut |ln @ &DirectiveLine { line_number, .. }| {
949 if !ln.applies_to_test_revision(test_revision) {
950 return;
951 }
952
953 parse_and_update_aux(config, ln, aux_props);
955
956 macro_rules! decision {
957 ($e:expr) => {
958 match $e {
959 IgnoreDecision::Ignore { reason } => {
960 ignore = true;
961 ignore_message = Some(reason.into());
962 }
963 IgnoreDecision::Error { message } => {
964 error!("{path}:{line_number}: {message}");
965 *poisoned = true;
966 return;
967 }
968 IgnoreDecision::Continue => {}
969 }
970 };
971 }
972
973 decision!(cfg::handle_ignore(&cache.cfg_conditions, ln));
974 decision!(cfg::handle_only(&cache.cfg_conditions, ln));
975 decision!(needs::handle_needs(&cache.needs, config, ln));
976 decision!(ignore_llvm(config, ln));
977 decision!(ignore_backends(config, ln));
978 decision!(needs_backends(config, ln));
979 decision!(ignore_cdb(config, ln));
980 decision!(ignore_gdb(config, ln));
981 decision!(ignore_lldb(config, ln));
982 decision!(ignore_parallel_frontend(config, ln));
983
984 if config.target == "wasm32-unknown-unknown"
985 && config.parse_name_directive(ln, directives::CHECK_RUN_RESULTS)
986 {
987 decision!(IgnoreDecision::Ignore {
988 reason: "ignored on WASM as the run results cannot be checked there".into(),
989 });
990 }
991
992 should_fail |= config.parse_name_directive(ln, "should-fail");
993 });
994
995 let should_fail = if should_fail && config.mode != TestMode::Pretty {
999 ShouldFail::Yes
1000 } else {
1001 ShouldFail::No
1002 };
1003
1004 CollectedTestDesc {
1005 name,
1006 filterable_path: filterable_path.to_owned(),
1007 ignore,
1008 ignore_message,
1009 should_fail,
1010 }
1011}
1012
1013fn ignore_cdb(config: &Config, line: &DirectiveLine<'_>) -> IgnoreDecision {
1014 if config.debugger != Some(Debugger::Cdb) {
1015 return IgnoreDecision::Continue;
1016 }
1017
1018 if let Some(actual_version) = config.cdb_version {
1019 if line.name == "min-cdb-version"
1020 && let Some(rest) = line.value_after_colon().map(str::trim)
1021 {
1022 let min_version = extract_cdb_version(rest).unwrap_or_else(|| {
1023 panic!("couldn't parse version range: {:?}", rest);
1024 });
1025
1026 if actual_version < min_version {
1029 return IgnoreDecision::Ignore {
1030 reason: format!("ignored when the CDB version is lower than {rest}"),
1031 };
1032 }
1033 }
1034 }
1035 IgnoreDecision::Continue
1036}
1037
1038fn ignore_gdb(config: &Config, line: &DirectiveLine<'_>) -> IgnoreDecision {
1039 if config.debugger != Some(Debugger::Gdb) {
1040 return IgnoreDecision::Continue;
1041 }
1042
1043 if let Some(actual_version) = config.gdb_version {
1044 if line.name == "min-gdb-version"
1045 && let Some(rest) = line.value_after_colon().map(str::trim)
1046 {
1047 let (start_ver, end_ver) = extract_version_range(rest, extract_gdb_version)
1048 .unwrap_or_else(|| {
1049 panic!("couldn't parse version range: {:?}", rest);
1050 });
1051
1052 if start_ver != end_ver {
1053 panic!("Expected single GDB version")
1054 }
1055 if actual_version < start_ver {
1058 return IgnoreDecision::Ignore {
1059 reason: format!("ignored when the GDB version is lower than {rest}"),
1060 };
1061 }
1062 } else if line.name == "ignore-gdb-version"
1063 && let Some(rest) = line.value_after_colon().map(str::trim)
1064 {
1065 let (min_version, max_version) = extract_version_range(rest, extract_gdb_version)
1066 .unwrap_or_else(|| {
1067 panic!("couldn't parse version range: {:?}", rest);
1068 });
1069
1070 if max_version < min_version {
1071 panic!("Malformed GDB version range: max < min")
1072 }
1073
1074 if actual_version >= min_version && actual_version <= max_version {
1075 if min_version == max_version {
1076 return IgnoreDecision::Ignore {
1077 reason: format!("ignored when the GDB version is {rest}"),
1078 };
1079 } else {
1080 return IgnoreDecision::Ignore {
1081 reason: format!("ignored when the GDB version is between {rest}"),
1082 };
1083 }
1084 }
1085 }
1086 }
1087 IgnoreDecision::Continue
1088}
1089
1090fn ignore_lldb(config: &Config, line: &DirectiveLine<'_>) -> IgnoreDecision {
1091 if config.debugger != Some(Debugger::Lldb) {
1092 return IgnoreDecision::Continue;
1093 }
1094
1095 if let Some(actual_version) = config.lldb_version {
1096 if line.name == "min-lldb-version"
1097 && let Some(rest) = line.value_after_colon().map(str::trim)
1098 {
1099 let min_version = rest.parse().unwrap_or_else(|e| {
1100 panic!("Unexpected format of LLDB version string: {}\n{:?}", rest, e);
1101 });
1102 if actual_version < min_version {
1105 return IgnoreDecision::Ignore {
1106 reason: format!("ignored when the LLDB version is {rest}"),
1107 };
1108 }
1109 }
1110 }
1111 IgnoreDecision::Continue
1112}
1113
1114fn ignore_backends(config: &Config, line: &DirectiveLine<'_>) -> IgnoreDecision {
1115 let path = line.file_path;
1116 if let Some(backends_to_ignore) = config.parse_name_value_directive(line, "ignore-backends") {
1117 for backend in backends_to_ignore.split_whitespace().map(|backend| {
1118 match CodegenBackend::try_from(backend) {
1119 Ok(backend) => backend,
1120 Err(error) => {
1121 panic!("Invalid ignore-backends value `{backend}` in `{path}`: {error}")
1122 }
1123 }
1124 }) {
1125 if !config.bypass_ignore_backends && config.default_codegen_backend == backend {
1126 return IgnoreDecision::Ignore {
1127 reason: format!("{} backend is marked as ignore", backend.as_str()),
1128 };
1129 }
1130 }
1131 }
1132 IgnoreDecision::Continue
1133}
1134
1135fn needs_backends(config: &Config, line: &DirectiveLine<'_>) -> IgnoreDecision {
1136 let path = line.file_path;
1137 if let Some(needed_backends) = config.parse_name_value_directive(line, "needs-backends") {
1138 if !needed_backends
1139 .split_whitespace()
1140 .map(|backend| match CodegenBackend::try_from(backend) {
1141 Ok(backend) => backend,
1142 Err(error) => {
1143 panic!("Invalid needs-backends value `{backend}` in `{path}`: {error}")
1144 }
1145 })
1146 .any(|backend| config.default_codegen_backend == backend)
1147 {
1148 return IgnoreDecision::Ignore {
1149 reason: format!(
1150 "{} backend is not part of required backends",
1151 config.default_codegen_backend.as_str()
1152 ),
1153 };
1154 }
1155 }
1156 IgnoreDecision::Continue
1157}
1158
1159fn ignore_llvm(config: &Config, line: &DirectiveLine<'_>) -> IgnoreDecision {
1160 let path = line.file_path;
1161 if let Some(needed_components) =
1162 config.parse_name_value_directive(line, "needs-llvm-components")
1163 {
1164 let components: HashSet<_> = config.llvm_components.split_whitespace().collect();
1165 if let Some(missing_component) = needed_components
1166 .split_whitespace()
1167 .find(|needed_component| !components.contains(needed_component))
1168 {
1169 if env::var_os("COMPILETEST_REQUIRE_ALL_LLVM_COMPONENTS").is_some() {
1170 panic!(
1171 "missing LLVM component {missing_component}, \
1172 and COMPILETEST_REQUIRE_ALL_LLVM_COMPONENTS is set: {path}",
1173 );
1174 }
1175 return IgnoreDecision::Ignore {
1176 reason: format!("ignored when the {missing_component} LLVM component is missing"),
1177 };
1178 }
1179 }
1180 if let Some(actual_version) = &config.llvm_version {
1181 if let Some(version_string) = config.parse_name_value_directive(line, "min-llvm-version") {
1184 let min_version = extract_llvm_version(&version_string);
1185 if *actual_version < min_version {
1187 return IgnoreDecision::Ignore {
1188 reason: format!(
1189 "ignored when the LLVM version {actual_version} is older than {min_version}"
1190 ),
1191 };
1192 }
1193 } else if let Some(version_string) =
1194 config.parse_name_value_directive(line, "max-llvm-major-version")
1195 {
1196 let max_version = extract_llvm_version(&version_string);
1197 if actual_version.major > max_version.major {
1199 return IgnoreDecision::Ignore {
1200 reason: format!(
1201 "ignored when the LLVM version ({actual_version}) is newer than major\
1202 version {}",
1203 max_version.major
1204 ),
1205 };
1206 }
1207 } else if let Some(version_string) =
1208 config.parse_name_value_directive(line, "min-system-llvm-version")
1209 {
1210 let min_version = extract_llvm_version(&version_string);
1211 if config.system_llvm && *actual_version < min_version {
1214 return IgnoreDecision::Ignore {
1215 reason: format!(
1216 "ignored when the system LLVM version {actual_version} is older than {min_version}"
1217 ),
1218 };
1219 }
1220 } else if let Some(version_range) =
1221 config.parse_name_value_directive(line, "ignore-llvm-version")
1222 {
1223 let (v_min, v_max) =
1225 extract_version_range(&version_range, |s| Some(extract_llvm_version(s)))
1226 .unwrap_or_else(|| {
1227 panic!("couldn't parse version range: \"{version_range}\"");
1228 });
1229 if v_max < v_min {
1230 panic!("malformed LLVM version range where {v_max} < {v_min}")
1231 }
1232 if *actual_version >= v_min && *actual_version <= v_max {
1234 if v_min == v_max {
1235 return IgnoreDecision::Ignore {
1236 reason: format!("ignored when the LLVM version is {actual_version}"),
1237 };
1238 } else {
1239 return IgnoreDecision::Ignore {
1240 reason: format!(
1241 "ignored when the LLVM version is between {v_min} and {v_max}"
1242 ),
1243 };
1244 }
1245 }
1246 } else if let Some(version_string) =
1247 config.parse_name_value_directive(line, "exact-llvm-major-version")
1248 {
1249 let version = extract_llvm_version(&version_string);
1251 if actual_version.major != version.major {
1252 return IgnoreDecision::Ignore {
1253 reason: format!(
1254 "ignored when the actual LLVM major version is {}, but the test only targets major version {}",
1255 actual_version.major, version.major
1256 ),
1257 };
1258 }
1259 }
1260 }
1261 IgnoreDecision::Continue
1262}
1263
1264fn ignore_parallel_frontend(config: &Config, line: &DirectiveLine<'_>) -> IgnoreDecision {
1265 if config.parallel_frontend_enabled()
1266 && config.parse_name_directive(line, "ignore-parallel-frontend")
1267 {
1268 return IgnoreDecision::Ignore {
1269 reason: "ignored when the parallel frontend is enabled".into(),
1270 };
1271 }
1272 IgnoreDecision::Continue
1273}
1274
1275enum IgnoreDecision {
1276 Ignore { reason: String },
1277 Continue,
1278 Error { message: String },
1279}
1280
1281fn parse_edition_range(config: &Config, line: &DirectiveLine<'_>) -> Option<EditionRange> {
1282 let raw = config.parse_name_value_directive(line, "edition")?;
1283 let &DirectiveLine { file_path: testfile, line_number, .. } = line;
1284
1285 if let Some((lower_bound, upper_bound)) = raw.split_once("..") {
1287 Some(match (maybe_parse_edition(lower_bound), maybe_parse_edition(upper_bound)) {
1288 (Some(lower_bound), Some(upper_bound)) if upper_bound <= lower_bound => {
1289 fatal!(
1290 "{testfile}:{line_number}: the left side of `//@ edition` cannot be greater than or equal to the right side"
1291 );
1292 }
1293 (Some(lower_bound), Some(upper_bound)) => {
1294 EditionRange::Range { lower_bound, upper_bound }
1295 }
1296 (Some(lower_bound), None) => EditionRange::RangeFrom(lower_bound),
1297 (None, Some(_)) => {
1298 fatal!(
1299 "{testfile}:{line_number}: `..edition` is not a supported range in `//@ edition`"
1300 );
1301 }
1302 (None, None) => {
1303 fatal!("{testfile}:{line_number}: `..` is not a supported range in `//@ edition`");
1304 }
1305 })
1306 } else {
1307 match maybe_parse_edition(&raw) {
1308 Some(edition) => Some(EditionRange::Exact(edition)),
1309 None => {
1310 fatal!("{testfile}:{line_number}: empty value for `//@ edition`");
1311 }
1312 }
1313 }
1314}
1315
1316fn maybe_parse_edition(mut input: &str) -> Option<Edition> {
1317 input = input.trim();
1318 if input.is_empty() {
1319 return None;
1320 }
1321 Some(parse_edition(input))
1322}
1323
1324#[derive(Debug, PartialEq, Eq, Clone, Copy)]
1325enum EditionRange {
1326 Exact(Edition),
1327 RangeFrom(Edition),
1328 Range {
1330 lower_bound: Edition,
1331 upper_bound: Edition,
1332 },
1333}
1334
1335impl EditionRange {
1336 fn edition_to_test(&self, requested: impl Into<Option<Edition>>) -> Edition {
1337 let min_edition = Edition::Year(2015);
1338 let requested = requested.into().unwrap_or(min_edition);
1339
1340 match *self {
1341 EditionRange::Exact(exact) => exact,
1342 EditionRange::RangeFrom(lower_bound) => {
1343 if requested >= lower_bound {
1344 requested
1345 } else {
1346 lower_bound
1347 }
1348 }
1349 EditionRange::Range { lower_bound, upper_bound } => {
1350 if requested >= lower_bound && requested < upper_bound {
1351 requested
1352 } else {
1353 lower_bound
1354 }
1355 }
1356 }
1357 }
1358}
1359
1360fn split_flags(flags: &str) -> Vec<String> {
1361 flags
1366 .split('\'')
1367 .enumerate()
1368 .flat_map(|(i, f)| if i % 2 == 1 { vec![f] } else { f.split_whitespace().collect() })
1369 .map(move |s| s.to_owned())
1370 .collect::<Vec<_>>()
1371}