]> git.proxmox.com Git - rustc.git/blob - src/tools/compiletest/src/header.rs
New upstream version 1.58.1+dfsg1
[rustc.git] / src / tools / compiletest / src / header.rs
1 use std::collections::HashSet;
2 use std::env;
3 use std::fs::File;
4 use std::io::prelude::*;
5 use std::io::BufReader;
6 use std::path::{Path, PathBuf};
7
8 use tracing::*;
9
10 use crate::common::{CompareMode, Config, Debugger, FailMode, Mode, PanicStrategy, PassMode};
11 use crate::util;
12 use crate::{extract_cdb_version, extract_gdb_version};
13
14 #[cfg(test)]
15 mod tests;
16
17 /// The result of parse_cfg_name_directive.
18 #[derive(Clone, Copy, PartialEq, Debug)]
19 enum ParsedNameDirective {
20 /// No match.
21 NoMatch,
22 /// Match.
23 Match,
24 }
25
26 /// Properties which must be known very early, before actually running
27 /// the test.
28 #[derive(Default)]
29 pub struct EarlyProps {
30 pub aux: Vec<String>,
31 pub aux_crate: Vec<(String, String)>,
32 pub revisions: Vec<String>,
33 }
34
35 impl EarlyProps {
36 pub fn from_file(config: &Config, testfile: &Path) -> Self {
37 let file = File::open(testfile).expect("open test file to parse earlyprops");
38 Self::from_reader(config, testfile, file)
39 }
40
41 pub fn from_reader<R: Read>(config: &Config, testfile: &Path, rdr: R) -> Self {
42 let mut props = EarlyProps::default();
43 iter_header(testfile, rdr, &mut |_, ln| {
44 if let Some(s) = config.parse_aux_build(ln) {
45 props.aux.push(s);
46 }
47 if let Some(ac) = config.parse_aux_crate(ln) {
48 props.aux_crate.push(ac);
49 }
50 config.parse_and_update_revisions(ln, &mut props.revisions);
51 });
52 return props;
53 }
54 }
55
56 #[derive(Clone, Debug)]
57 pub struct TestProps {
58 // Lines that should be expected, in order, on standard out
59 pub error_patterns: Vec<String>,
60 // Extra flags to pass to the compiler
61 pub compile_flags: Vec<String>,
62 // Extra flags to pass when the compiled code is run (such as --bench)
63 pub run_flags: Option<String>,
64 // If present, the name of a file that this test should match when
65 // pretty-printed
66 pub pp_exact: Option<PathBuf>,
67 // Other crates that should be compiled (typically from the same
68 // directory as the test, but for backwards compatibility reasons
69 // we also check the auxiliary directory)
70 pub aux_builds: Vec<String>,
71 // Similar to `aux_builds`, but a list of NAME=somelib.rs of dependencies
72 // to build and pass with the `--extern` flag.
73 pub aux_crates: Vec<(String, String)>,
74 // Environment settings to use for compiling
75 pub rustc_env: Vec<(String, String)>,
76 // Environment variables to unset prior to compiling.
77 // Variables are unset before applying 'rustc_env'.
78 pub unset_rustc_env: Vec<String>,
79 // Environment settings to use during execution
80 pub exec_env: Vec<(String, String)>,
81 // Lines to check if they appear in the expected debugger output
82 pub check_lines: Vec<String>,
83 // Build documentation for all specified aux-builds as well
84 pub build_aux_docs: bool,
85 // Flag to force a crate to be built with the host architecture
86 pub force_host: bool,
87 // Check stdout for error-pattern output as well as stderr
88 pub check_stdout: bool,
89 // Check stdout & stderr for output of run-pass test
90 pub check_run_results: bool,
91 // For UI tests, allows compiler to generate arbitrary output to stdout
92 pub dont_check_compiler_stdout: bool,
93 // For UI tests, allows compiler to generate arbitrary output to stderr
94 pub dont_check_compiler_stderr: bool,
95 // Don't force a --crate-type=dylib flag on the command line
96 //
97 // Set this for example if you have an auxiliary test file that contains
98 // a proc-macro and needs `#![crate_type = "proc-macro"]`. This ensures
99 // that the aux file is compiled as a `proc-macro` and not as a `dylib`.
100 pub no_prefer_dynamic: bool,
101 // Run -Zunpretty expanded when running pretty printing tests
102 pub pretty_expanded: bool,
103 // Which pretty mode are we testing with, default to 'normal'
104 pub pretty_mode: String,
105 // Only compare pretty output and don't try compiling
106 pub pretty_compare_only: bool,
107 // Patterns which must not appear in the output of a cfail test.
108 pub forbid_output: Vec<String>,
109 // Revisions to test for incremental compilation.
110 pub revisions: Vec<String>,
111 // Directory (if any) to use for incremental compilation. This is
112 // not set by end-users; rather it is set by the incremental
113 // testing harness and used when generating compilation
114 // arguments. (In particular, it propagates to the aux-builds.)
115 pub incremental_dir: Option<PathBuf>,
116 // If `true`, this test will use incremental compilation.
117 //
118 // This can be set manually with the `incremental` header, or implicitly
119 // by being a part of an incremental mode test. Using the `incremental`
120 // header should be avoided if possible; using an incremental mode test is
121 // preferred. Incremental mode tests support multiple passes, which can
122 // verify that the incremental cache can be loaded properly after being
123 // created. Just setting the header will only verify the behavior with
124 // creating an incremental cache, but doesn't check that it is created
125 // correctly.
126 //
127 // Compiletest will create the incremental directory, and ensure it is
128 // empty before the test starts. Incremental mode tests will reuse the
129 // incremental directory between passes in the same test.
130 pub incremental: bool,
131 // How far should the test proceed while still passing.
132 pass_mode: Option<PassMode>,
133 // Ignore `--pass` overrides from the command line for this test.
134 ignore_pass: bool,
135 // How far this test should proceed to start failing.
136 pub fail_mode: Option<FailMode>,
137 // rustdoc will test the output of the `--test` option
138 pub check_test_line_numbers_match: bool,
139 // customized normalization rules
140 pub normalize_stdout: Vec<(String, String)>,
141 pub normalize_stderr: Vec<(String, String)>,
142 pub failure_status: i32,
143 // Whether or not `rustfix` should apply the `CodeSuggestion`s of this test and compile the
144 // resulting Rust code.
145 pub run_rustfix: bool,
146 // If true, `rustfix` will only apply `MachineApplicable` suggestions.
147 pub rustfix_only_machine_applicable: bool,
148 pub assembly_output: Option<String>,
149 // If true, the test is expected to ICE
150 pub should_ice: bool,
151 // If true, the stderr is expected to be different across bit-widths.
152 pub stderr_per_bitwidth: bool,
153 }
154
155 impl TestProps {
156 pub fn new() -> Self {
157 TestProps {
158 error_patterns: vec![],
159 compile_flags: vec![],
160 run_flags: None,
161 pp_exact: None,
162 aux_builds: vec![],
163 aux_crates: vec![],
164 revisions: vec![],
165 rustc_env: vec![],
166 unset_rustc_env: vec![],
167 exec_env: vec![],
168 check_lines: vec![],
169 build_aux_docs: false,
170 force_host: false,
171 check_stdout: false,
172 check_run_results: false,
173 dont_check_compiler_stdout: false,
174 dont_check_compiler_stderr: false,
175 no_prefer_dynamic: false,
176 pretty_expanded: false,
177 pretty_mode: "normal".to_string(),
178 pretty_compare_only: false,
179 forbid_output: vec![],
180 incremental_dir: None,
181 incremental: false,
182 pass_mode: None,
183 fail_mode: None,
184 ignore_pass: false,
185 check_test_line_numbers_match: false,
186 normalize_stdout: vec![],
187 normalize_stderr: vec![],
188 failure_status: -1,
189 run_rustfix: false,
190 rustfix_only_machine_applicable: false,
191 assembly_output: None,
192 should_ice: false,
193 stderr_per_bitwidth: false,
194 }
195 }
196
197 pub fn from_aux_file(&self, testfile: &Path, cfg: Option<&str>, config: &Config) -> Self {
198 let mut props = TestProps::new();
199
200 // copy over select properties to the aux build:
201 props.incremental_dir = self.incremental_dir.clone();
202 props.load_from(testfile, cfg, config);
203
204 props
205 }
206
207 pub fn from_file(testfile: &Path, cfg: Option<&str>, config: &Config) -> Self {
208 let mut props = TestProps::new();
209 props.load_from(testfile, cfg, config);
210
211 match (props.pass_mode, props.fail_mode) {
212 (None, None) => props.fail_mode = Some(FailMode::Check),
213 (Some(_), None) | (None, Some(_)) => {}
214 (Some(_), Some(_)) => panic!("cannot use a *-fail and *-pass mode together"),
215 }
216
217 props
218 }
219
220 /// Loads properties from `testfile` into `props`. If a property is
221 /// tied to a particular revision `foo` (indicated by writing
222 /// `//[foo]`), then the property is ignored unless `cfg` is
223 /// `Some("foo")`.
224 fn load_from(&mut self, testfile: &Path, cfg: Option<&str>, config: &Config) {
225 let mut has_edition = false;
226 if !testfile.is_dir() {
227 let file = File::open(testfile).unwrap();
228
229 iter_header(testfile, file, &mut |revision, ln| {
230 if revision.is_some() && revision != cfg {
231 return;
232 }
233
234 if let Some(ep) = config.parse_error_pattern(ln) {
235 self.error_patterns.push(ep);
236 }
237
238 if let Some(flags) = config.parse_compile_flags(ln) {
239 self.compile_flags.extend(flags.split_whitespace().map(|s| s.to_owned()));
240 }
241
242 if let Some(edition) = config.parse_edition(ln) {
243 self.compile_flags.push(format!("--edition={}", edition));
244 has_edition = true;
245 }
246
247 config.parse_and_update_revisions(ln, &mut self.revisions);
248
249 if self.run_flags.is_none() {
250 self.run_flags = config.parse_run_flags(ln);
251 }
252
253 if self.pp_exact.is_none() {
254 self.pp_exact = config.parse_pp_exact(ln, testfile);
255 }
256
257 if !self.should_ice {
258 self.should_ice = config.parse_should_ice(ln);
259 }
260
261 if !self.build_aux_docs {
262 self.build_aux_docs = config.parse_build_aux_docs(ln);
263 }
264
265 if !self.force_host {
266 self.force_host = config.parse_force_host(ln);
267 }
268
269 if !self.check_stdout {
270 self.check_stdout = config.parse_check_stdout(ln);
271 }
272
273 if !self.check_run_results {
274 self.check_run_results = config.parse_check_run_results(ln);
275 }
276
277 if !self.dont_check_compiler_stdout {
278 self.dont_check_compiler_stdout = config.parse_dont_check_compiler_stdout(ln);
279 }
280
281 if !self.dont_check_compiler_stderr {
282 self.dont_check_compiler_stderr = config.parse_dont_check_compiler_stderr(ln);
283 }
284
285 if !self.no_prefer_dynamic {
286 self.no_prefer_dynamic = config.parse_no_prefer_dynamic(ln);
287 }
288
289 if !self.pretty_expanded {
290 self.pretty_expanded = config.parse_pretty_expanded(ln);
291 }
292
293 if let Some(m) = config.parse_pretty_mode(ln) {
294 self.pretty_mode = m;
295 }
296
297 if !self.pretty_compare_only {
298 self.pretty_compare_only = config.parse_pretty_compare_only(ln);
299 }
300
301 if let Some(ab) = config.parse_aux_build(ln) {
302 self.aux_builds.push(ab);
303 }
304
305 if let Some(ac) = config.parse_aux_crate(ln) {
306 self.aux_crates.push(ac);
307 }
308
309 if let Some(ee) = config.parse_env(ln, "exec-env") {
310 self.exec_env.push(ee);
311 }
312
313 if let Some(ee) = config.parse_env(ln, "rustc-env") {
314 self.rustc_env.push(ee);
315 }
316
317 if let Some(ev) = config.parse_name_value_directive(ln, "unset-rustc-env") {
318 self.unset_rustc_env.push(ev);
319 }
320
321 if let Some(cl) = config.parse_check_line(ln) {
322 self.check_lines.push(cl);
323 }
324
325 if let Some(of) = config.parse_forbid_output(ln) {
326 self.forbid_output.push(of);
327 }
328
329 if !self.check_test_line_numbers_match {
330 self.check_test_line_numbers_match =
331 config.parse_check_test_line_numbers_match(ln);
332 }
333
334 self.update_pass_mode(ln, cfg, config);
335 self.update_fail_mode(ln, config);
336
337 if !self.ignore_pass {
338 self.ignore_pass = config.parse_ignore_pass(ln);
339 }
340
341 if let Some(rule) = config.parse_custom_normalization(ln, "normalize-stdout") {
342 self.normalize_stdout.push(rule);
343 }
344 if let Some(rule) = config.parse_custom_normalization(ln, "normalize-stderr") {
345 self.normalize_stderr.push(rule);
346 }
347
348 if let Some(code) = config.parse_failure_status(ln) {
349 self.failure_status = code;
350 }
351
352 if !self.run_rustfix {
353 self.run_rustfix = config.parse_run_rustfix(ln);
354 }
355
356 if !self.rustfix_only_machine_applicable {
357 self.rustfix_only_machine_applicable =
358 config.parse_rustfix_only_machine_applicable(ln);
359 }
360
361 if self.assembly_output.is_none() {
362 self.assembly_output = config.parse_assembly_output(ln);
363 }
364
365 if !self.stderr_per_bitwidth {
366 self.stderr_per_bitwidth = config.parse_stderr_per_bitwidth(ln);
367 }
368
369 if !self.incremental {
370 self.incremental = config.parse_incremental(ln);
371 }
372 });
373 }
374
375 if self.failure_status == -1 {
376 self.failure_status = 1;
377 }
378 if self.should_ice {
379 self.failure_status = 101;
380 }
381
382 if config.mode == Mode::Incremental {
383 self.incremental = true;
384 }
385
386 for key in &["RUST_TEST_NOCAPTURE", "RUST_TEST_THREADS"] {
387 if let Ok(val) = env::var(key) {
388 if self.exec_env.iter().find(|&&(ref x, _)| x == key).is_none() {
389 self.exec_env.push(((*key).to_owned(), val))
390 }
391 }
392 }
393
394 if let (Some(edition), false) = (&config.edition, has_edition) {
395 self.compile_flags.push(format!("--edition={}", edition));
396 }
397 }
398
399 fn update_fail_mode(&mut self, ln: &str, config: &Config) {
400 let check_ui = |mode: &str| {
401 if config.mode != Mode::Ui {
402 panic!("`{}-fail` header is only supported in UI tests", mode);
403 }
404 };
405 if config.mode == Mode::Ui && config.parse_name_directive(ln, "compile-fail") {
406 panic!("`compile-fail` header is useless in UI tests");
407 }
408 let fail_mode = if config.parse_name_directive(ln, "check-fail") {
409 check_ui("check");
410 Some(FailMode::Check)
411 } else if config.parse_name_directive(ln, "build-fail") {
412 check_ui("build");
413 Some(FailMode::Build)
414 } else if config.parse_name_directive(ln, "run-fail") {
415 check_ui("run");
416 Some(FailMode::Run)
417 } else {
418 None
419 };
420 match (self.fail_mode, fail_mode) {
421 (None, Some(_)) => self.fail_mode = fail_mode,
422 (Some(_), Some(_)) => panic!("multiple `*-fail` headers in a single test"),
423 (_, None) => {}
424 }
425 }
426
427 fn update_pass_mode(&mut self, ln: &str, revision: Option<&str>, config: &Config) {
428 let check_no_run = |s| {
429 if config.mode != Mode::Ui && config.mode != Mode::Incremental {
430 panic!("`{}` header is only supported in UI and incremental tests", s);
431 }
432 if config.mode == Mode::Incremental
433 && !revision.map_or(false, |r| r.starts_with("cfail"))
434 && !self.revisions.iter().all(|r| r.starts_with("cfail"))
435 {
436 panic!("`{}` header is only supported in `cfail` incremental tests", s);
437 }
438 };
439 let pass_mode = if config.parse_name_directive(ln, "check-pass") {
440 check_no_run("check-pass");
441 Some(PassMode::Check)
442 } else if config.parse_name_directive(ln, "build-pass") {
443 check_no_run("build-pass");
444 Some(PassMode::Build)
445 } else if config.parse_name_directive(ln, "run-pass") {
446 if config.mode != Mode::Ui {
447 panic!("`run-pass` header is only supported in UI tests")
448 }
449 Some(PassMode::Run)
450 } else {
451 None
452 };
453 match (self.pass_mode, pass_mode) {
454 (None, Some(_)) => self.pass_mode = pass_mode,
455 (Some(_), Some(_)) => panic!("multiple `*-pass` headers in a single test"),
456 (_, None) => {}
457 }
458 }
459
460 pub fn pass_mode(&self, config: &Config) -> Option<PassMode> {
461 if !self.ignore_pass && self.fail_mode.is_none() && config.mode == Mode::Ui {
462 if let (mode @ Some(_), Some(_)) = (config.force_pass_mode, self.pass_mode) {
463 return mode;
464 }
465 }
466 self.pass_mode
467 }
468
469 // does not consider CLI override for pass mode
470 pub fn local_pass_mode(&self) -> Option<PassMode> {
471 self.pass_mode
472 }
473 }
474
475 fn iter_header<R: Read>(testfile: &Path, rdr: R, it: &mut dyn FnMut(Option<&str>, &str)) {
476 if testfile.is_dir() {
477 return;
478 }
479
480 let comment = if testfile.extension().map(|e| e == "rs") == Some(true) { "//" } else { "#" };
481
482 let mut rdr = BufReader::new(rdr);
483 let mut ln = String::new();
484
485 loop {
486 ln.clear();
487 if rdr.read_line(&mut ln).unwrap() == 0 {
488 break;
489 }
490
491 // Assume that any directives will be found before the first
492 // module or function. This doesn't seem to be an optimization
493 // with a warm page cache. Maybe with a cold one.
494 let ln = ln.trim();
495 if ln.starts_with("fn") || ln.starts_with("mod") {
496 return;
497 } else if ln.starts_with(comment) && ln[comment.len()..].trim_start().starts_with('[') {
498 // A comment like `//[foo]` is specific to revision `foo`
499 if let Some(close_brace) = ln.find(']') {
500 let open_brace = ln.find('[').unwrap();
501 let lncfg = &ln[open_brace + 1..close_brace];
502 it(Some(lncfg), ln[(close_brace + 1)..].trim_start());
503 } else {
504 panic!("malformed condition directive: expected `{}[foo]`, found `{}`", comment, ln)
505 }
506 } else if ln.starts_with(comment) {
507 it(None, ln[comment.len()..].trim_start());
508 }
509 }
510 }
511
512 impl Config {
513 fn parse_should_ice(&self, line: &str) -> bool {
514 self.parse_name_directive(line, "should-ice")
515 }
516 fn parse_error_pattern(&self, line: &str) -> Option<String> {
517 self.parse_name_value_directive(line, "error-pattern")
518 }
519
520 fn parse_forbid_output(&self, line: &str) -> Option<String> {
521 self.parse_name_value_directive(line, "forbid-output")
522 }
523
524 fn parse_aux_build(&self, line: &str) -> Option<String> {
525 self.parse_name_value_directive(line, "aux-build").map(|r| r.trim().to_string())
526 }
527
528 fn parse_aux_crate(&self, line: &str) -> Option<(String, String)> {
529 self.parse_name_value_directive(line, "aux-crate").map(|r| {
530 let mut parts = r.trim().splitn(2, '=');
531 (
532 parts.next().expect("missing aux-crate name (e.g. log=log.rs)").to_string(),
533 parts.next().expect("missing aux-crate value (e.g. log=log.rs)").to_string(),
534 )
535 })
536 }
537
538 fn parse_compile_flags(&self, line: &str) -> Option<String> {
539 self.parse_name_value_directive(line, "compile-flags")
540 }
541
542 fn parse_and_update_revisions(&self, line: &str, existing: &mut Vec<String>) {
543 if let Some(raw) = self.parse_name_value_directive(line, "revisions") {
544 let mut duplicates: HashSet<_> = existing.iter().cloned().collect();
545 for revision in raw.split_whitespace().map(|r| r.to_string()) {
546 if !duplicates.insert(revision.clone()) {
547 panic!("Duplicate revision: `{}` in line `{}`", revision, raw);
548 }
549 existing.push(revision);
550 }
551 }
552 }
553
554 fn parse_run_flags(&self, line: &str) -> Option<String> {
555 self.parse_name_value_directive(line, "run-flags")
556 }
557
558 fn parse_check_line(&self, line: &str) -> Option<String> {
559 self.parse_name_value_directive(line, "check")
560 }
561
562 fn parse_force_host(&self, line: &str) -> bool {
563 self.parse_name_directive(line, "force-host")
564 }
565
566 fn parse_build_aux_docs(&self, line: &str) -> bool {
567 self.parse_name_directive(line, "build-aux-docs")
568 }
569
570 fn parse_check_stdout(&self, line: &str) -> bool {
571 self.parse_name_directive(line, "check-stdout")
572 }
573
574 fn parse_check_run_results(&self, line: &str) -> bool {
575 self.parse_name_directive(line, "check-run-results")
576 }
577
578 fn parse_dont_check_compiler_stdout(&self, line: &str) -> bool {
579 self.parse_name_directive(line, "dont-check-compiler-stdout")
580 }
581
582 fn parse_dont_check_compiler_stderr(&self, line: &str) -> bool {
583 self.parse_name_directive(line, "dont-check-compiler-stderr")
584 }
585
586 fn parse_no_prefer_dynamic(&self, line: &str) -> bool {
587 self.parse_name_directive(line, "no-prefer-dynamic")
588 }
589
590 fn parse_pretty_expanded(&self, line: &str) -> bool {
591 self.parse_name_directive(line, "pretty-expanded")
592 }
593
594 fn parse_pretty_mode(&self, line: &str) -> Option<String> {
595 self.parse_name_value_directive(line, "pretty-mode")
596 }
597
598 fn parse_pretty_compare_only(&self, line: &str) -> bool {
599 self.parse_name_directive(line, "pretty-compare-only")
600 }
601
602 fn parse_failure_status(&self, line: &str) -> Option<i32> {
603 match self.parse_name_value_directive(line, "failure-status") {
604 Some(code) => code.trim().parse::<i32>().ok(),
605 _ => None,
606 }
607 }
608
609 fn parse_check_test_line_numbers_match(&self, line: &str) -> bool {
610 self.parse_name_directive(line, "check-test-line-numbers-match")
611 }
612
613 fn parse_ignore_pass(&self, line: &str) -> bool {
614 self.parse_name_directive(line, "ignore-pass")
615 }
616
617 fn parse_stderr_per_bitwidth(&self, line: &str) -> bool {
618 self.parse_name_directive(line, "stderr-per-bitwidth")
619 }
620
621 fn parse_assembly_output(&self, line: &str) -> Option<String> {
622 self.parse_name_value_directive(line, "assembly-output").map(|r| r.trim().to_string())
623 }
624
625 fn parse_env(&self, line: &str, name: &str) -> Option<(String, String)> {
626 self.parse_name_value_directive(line, name).map(|nv| {
627 // nv is either FOO or FOO=BAR
628 let mut strs: Vec<String> = nv.splitn(2, '=').map(str::to_owned).collect();
629
630 match strs.len() {
631 1 => (strs.pop().unwrap(), String::new()),
632 2 => {
633 let end = strs.pop().unwrap();
634 (strs.pop().unwrap(), end)
635 }
636 n => panic!("Expected 1 or 2 strings, not {}", n),
637 }
638 })
639 }
640
641 fn parse_pp_exact(&self, line: &str, testfile: &Path) -> Option<PathBuf> {
642 if let Some(s) = self.parse_name_value_directive(line, "pp-exact") {
643 Some(PathBuf::from(&s))
644 } else if self.parse_name_directive(line, "pp-exact") {
645 testfile.file_name().map(PathBuf::from)
646 } else {
647 None
648 }
649 }
650
651 fn parse_custom_normalization(&self, mut line: &str, prefix: &str) -> Option<(String, String)> {
652 if self.parse_cfg_name_directive(line, prefix) == ParsedNameDirective::Match {
653 let from = parse_normalization_string(&mut line)?;
654 let to = parse_normalization_string(&mut line)?;
655 Some((from, to))
656 } else {
657 None
658 }
659 }
660
661 fn parse_needs_matching_clang(&self, line: &str) -> bool {
662 self.parse_name_directive(line, "needs-matching-clang")
663 }
664
665 fn parse_needs_profiler_support(&self, line: &str) -> bool {
666 self.parse_name_directive(line, "needs-profiler-support")
667 }
668
669 /// Parses a name-value directive which contains config-specific information, e.g., `ignore-x86`
670 /// or `normalize-stderr-32bit`.
671 fn parse_cfg_name_directive(&self, line: &str, prefix: &str) -> ParsedNameDirective {
672 if !line.as_bytes().starts_with(prefix.as_bytes()) {
673 return ParsedNameDirective::NoMatch;
674 }
675 if line.as_bytes().get(prefix.len()) != Some(&b'-') {
676 return ParsedNameDirective::NoMatch;
677 }
678
679 let name = line[prefix.len() + 1..].split(&[':', ' '][..]).next().unwrap();
680
681 let is_match = name == "test" ||
682 self.target == name || // triple
683 util::matches_os(&self.target, name) || // target
684 util::matches_env(&self.target, name) || // env
685 self.target.ends_with(name) || // target and env
686 name == util::get_arch(&self.target) || // architecture
687 name == util::get_pointer_width(&self.target) || // pointer width
688 name == self.stage_id.split('-').next().unwrap() || // stage
689 name == self.channel || // channel
690 (self.target != self.host && name == "cross-compile") ||
691 (name == "endian-big" && util::is_big_endian(&self.target)) ||
692 (self.remote_test_client.is_some() && name == "remote") ||
693 match self.compare_mode {
694 Some(CompareMode::Nll) => name == "compare-mode-nll",
695 Some(CompareMode::Polonius) => name == "compare-mode-polonius",
696 Some(CompareMode::Chalk) => name == "compare-mode-chalk",
697 Some(CompareMode::SplitDwarf) => name == "compare-mode-split-dwarf",
698 Some(CompareMode::SplitDwarfSingle) => name == "compare-mode-split-dwarf-single",
699 None => false,
700 } ||
701 (cfg!(debug_assertions) && name == "debug") ||
702 match self.debugger {
703 Some(Debugger::Cdb) => name == "cdb",
704 Some(Debugger::Gdb) => name == "gdb",
705 Some(Debugger::Lldb) => name == "lldb",
706 None => false,
707 };
708
709 if is_match { ParsedNameDirective::Match } else { ParsedNameDirective::NoMatch }
710 }
711
712 fn has_cfg_prefix(&self, line: &str, prefix: &str) -> bool {
713 // returns whether this line contains this prefix or not. For prefix
714 // "ignore", returns true if line says "ignore-x86_64", "ignore-arch",
715 // "ignore-android" etc.
716 line.starts_with(prefix) && line.as_bytes().get(prefix.len()) == Some(&b'-')
717 }
718
719 fn parse_name_directive(&self, line: &str, directive: &str) -> bool {
720 // Ensure the directive is a whole word. Do not match "ignore-x86" when
721 // the line says "ignore-x86_64".
722 line.starts_with(directive)
723 && matches!(line.as_bytes().get(directive.len()), None | Some(&b' ') | Some(&b':'))
724 }
725
726 pub fn parse_name_value_directive(&self, line: &str, directive: &str) -> Option<String> {
727 let colon = directive.len();
728 if line.starts_with(directive) && line.as_bytes().get(colon) == Some(&b':') {
729 let value = line[(colon + 1)..].to_owned();
730 debug!("{}: {}", directive, value);
731 Some(expand_variables(value, self))
732 } else {
733 None
734 }
735 }
736
737 pub fn find_rust_src_root(&self) -> Option<PathBuf> {
738 let mut path = self.src_base.clone();
739 let path_postfix = Path::new("src/etc/lldb_batchmode.py");
740
741 while path.pop() {
742 if path.join(&path_postfix).is_file() {
743 return Some(path);
744 }
745 }
746
747 None
748 }
749
750 fn parse_run_rustfix(&self, line: &str) -> bool {
751 self.parse_name_directive(line, "run-rustfix")
752 }
753
754 fn parse_rustfix_only_machine_applicable(&self, line: &str) -> bool {
755 self.parse_name_directive(line, "rustfix-only-machine-applicable")
756 }
757
758 fn parse_edition(&self, line: &str) -> Option<String> {
759 self.parse_name_value_directive(line, "edition")
760 }
761
762 fn parse_incremental(&self, line: &str) -> bool {
763 self.parse_name_directive(line, "incremental")
764 }
765 }
766
767 fn expand_variables(mut value: String, config: &Config) -> String {
768 const CWD: &str = "{{cwd}}";
769 const SRC_BASE: &str = "{{src-base}}";
770 const BUILD_BASE: &str = "{{build-base}}";
771
772 if value.contains(CWD) {
773 let cwd = env::current_dir().unwrap();
774 value = value.replace(CWD, &cwd.to_string_lossy());
775 }
776
777 if value.contains(SRC_BASE) {
778 value = value.replace(SRC_BASE, &config.src_base.to_string_lossy());
779 }
780
781 if value.contains(BUILD_BASE) {
782 value = value.replace(BUILD_BASE, &config.build_base.to_string_lossy());
783 }
784
785 value
786 }
787
788 /// Finds the next quoted string `"..."` in `line`, and extract the content from it. Move the `line`
789 /// variable after the end of the quoted string.
790 ///
791 /// # Examples
792 ///
793 /// ```
794 /// let mut s = "normalize-stderr-32bit: \"something (32 bits)\" -> \"something ($WORD bits)\".";
795 /// let first = parse_normalization_string(&mut s);
796 /// assert_eq!(first, Some("something (32 bits)".to_owned()));
797 /// assert_eq!(s, " -> \"something ($WORD bits)\".");
798 /// ```
799 fn parse_normalization_string(line: &mut &str) -> Option<String> {
800 // FIXME support escapes in strings.
801 let begin = line.find('"')? + 1;
802 let end = line[begin..].find('"')? + begin;
803 let result = line[begin..end].to_owned();
804 *line = &line[end + 1..];
805 Some(result)
806 }
807
808 pub fn extract_llvm_version(version: &str) -> Option<u32> {
809 let pat = |c: char| !c.is_ascii_digit() && c != '.';
810 let version_without_suffix = match version.find(pat) {
811 Some(pos) => &version[..pos],
812 None => version,
813 };
814 let components: Vec<u32> = version_without_suffix
815 .split('.')
816 .map(|s| s.parse().expect("Malformed version component"))
817 .collect();
818 let version = match *components {
819 [a] => a * 10_000,
820 [a, b] => a * 10_000 + b * 100,
821 [a, b, c] => a * 10_000 + b * 100 + c,
822 _ => panic!("Malformed version"),
823 };
824 Some(version)
825 }
826
827 /// Takes a directive of the form "<version1> [- <version2>]",
828 /// returns the numeric representation of <version1> and <version2> as
829 /// tuple: (<version1> as u32, <version2> as u32)
830 ///
831 /// If the <version2> part is omitted, the second component of the tuple
832 /// is the same as <version1>.
833 fn extract_version_range<F>(line: &str, parse: F) -> Option<(u32, u32)>
834 where
835 F: Fn(&str) -> Option<u32>,
836 {
837 let mut splits = line.splitn(2, "- ").map(str::trim);
838 let min = splits.next().unwrap();
839 if min.ends_with('-') {
840 return None;
841 }
842
843 let max = splits.next();
844
845 if min.is_empty() {
846 return None;
847 }
848
849 let min = parse(min)?;
850 let max = match max {
851 Some(max) if max.is_empty() => return None,
852 Some(max) => parse(max)?,
853 _ => min,
854 };
855
856 Some((min, max))
857 }
858
859 pub fn make_test_description<R: Read>(
860 config: &Config,
861 name: test::TestName,
862 path: &Path,
863 src: R,
864 cfg: Option<&str>,
865 ) -> test::TestDesc {
866 let mut ignore = false;
867 let mut should_fail = false;
868
869 let rustc_has_profiler_support = env::var_os("RUSTC_PROFILER_SUPPORT").is_some();
870 let rustc_has_sanitizer_support = env::var_os("RUSTC_SANITIZER_SUPPORT").is_some();
871 let has_asm_support = util::has_asm_support(&config.target);
872 let has_asan = util::ASAN_SUPPORTED_TARGETS.contains(&&*config.target);
873 let has_lsan = util::LSAN_SUPPORTED_TARGETS.contains(&&*config.target);
874 let has_msan = util::MSAN_SUPPORTED_TARGETS.contains(&&*config.target);
875 let has_tsan = util::TSAN_SUPPORTED_TARGETS.contains(&&*config.target);
876 let has_hwasan = util::HWASAN_SUPPORTED_TARGETS.contains(&&*config.target);
877 // for `-Z gcc-ld=lld`
878 let has_rust_lld = config
879 .compile_lib_path
880 .join("rustlib")
881 .join(&config.target)
882 .join("bin")
883 .join("gcc-ld")
884 .join(if config.host.contains("windows") { "ld.exe" } else { "ld" })
885 .exists();
886 iter_header(path, src, &mut |revision, ln| {
887 if revision.is_some() && revision != cfg {
888 return;
889 }
890 ignore = match config.parse_cfg_name_directive(ln, "ignore") {
891 ParsedNameDirective::Match => true,
892 ParsedNameDirective::NoMatch => ignore,
893 };
894 if config.has_cfg_prefix(ln, "only") {
895 ignore = match config.parse_cfg_name_directive(ln, "only") {
896 ParsedNameDirective::Match => ignore,
897 ParsedNameDirective::NoMatch => true,
898 };
899 }
900 ignore |= ignore_llvm(config, ln);
901 ignore |=
902 config.run_clang_based_tests_with.is_none() && config.parse_needs_matching_clang(ln);
903 ignore |= !has_asm_support && config.parse_name_directive(ln, "needs-asm-support");
904 ignore |= !rustc_has_profiler_support && config.parse_needs_profiler_support(ln);
905 ignore |= !config.run_enabled() && config.parse_name_directive(ln, "needs-run-enabled");
906 ignore |= !rustc_has_sanitizer_support
907 && config.parse_name_directive(ln, "needs-sanitizer-support");
908 ignore |= !has_asan && config.parse_name_directive(ln, "needs-sanitizer-address");
909 ignore |= !has_lsan && config.parse_name_directive(ln, "needs-sanitizer-leak");
910 ignore |= !has_msan && config.parse_name_directive(ln, "needs-sanitizer-memory");
911 ignore |= !has_tsan && config.parse_name_directive(ln, "needs-sanitizer-thread");
912 ignore |= !has_hwasan && config.parse_name_directive(ln, "needs-sanitizer-hwaddress");
913 ignore |= config.target_panic == PanicStrategy::Abort
914 && config.parse_name_directive(ln, "needs-unwind");
915 ignore |= config.target == "wasm32-unknown-unknown" && config.parse_check_run_results(ln);
916 ignore |= config.debugger == Some(Debugger::Cdb) && ignore_cdb(config, ln);
917 ignore |= config.debugger == Some(Debugger::Gdb) && ignore_gdb(config, ln);
918 ignore |= config.debugger == Some(Debugger::Lldb) && ignore_lldb(config, ln);
919 ignore |= !has_rust_lld && config.parse_name_directive(ln, "needs-rust-lld");
920 should_fail |= config.parse_name_directive(ln, "should-fail");
921 });
922
923 // The `should-fail` annotation doesn't apply to pretty tests,
924 // since we run the pretty printer across all tests by default.
925 // If desired, we could add a `should-fail-pretty` annotation.
926 let should_panic = match config.mode {
927 crate::common::Pretty => test::ShouldPanic::No,
928 _ if should_fail => test::ShouldPanic::Yes,
929 _ => test::ShouldPanic::No,
930 };
931
932 test::TestDesc {
933 name,
934 ignore,
935 should_panic,
936 allow_fail: false,
937 compile_fail: false,
938 no_run: false,
939 test_type: test::TestType::Unknown,
940 }
941 }
942
943 fn ignore_cdb(config: &Config, line: &str) -> bool {
944 if let Some(actual_version) = config.cdb_version {
945 if let Some(min_version) = line.strip_prefix("min-cdb-version:").map(str::trim) {
946 let min_version = extract_cdb_version(min_version).unwrap_or_else(|| {
947 panic!("couldn't parse version range: {:?}", min_version);
948 });
949
950 // Ignore if actual version is smaller than the minimum
951 // required version
952 return actual_version < min_version;
953 }
954 }
955 false
956 }
957
958 fn ignore_gdb(config: &Config, line: &str) -> bool {
959 if let Some(actual_version) = config.gdb_version {
960 if let Some(rest) = line.strip_prefix("min-gdb-version:").map(str::trim) {
961 let (start_ver, end_ver) = extract_version_range(rest, extract_gdb_version)
962 .unwrap_or_else(|| {
963 panic!("couldn't parse version range: {:?}", rest);
964 });
965
966 if start_ver != end_ver {
967 panic!("Expected single GDB version")
968 }
969 // Ignore if actual version is smaller than the minimum
970 // required version
971 return actual_version < start_ver;
972 } else if let Some(rest) = line.strip_prefix("ignore-gdb-version:").map(str::trim) {
973 let (min_version, max_version) = extract_version_range(rest, extract_gdb_version)
974 .unwrap_or_else(|| {
975 panic!("couldn't parse version range: {:?}", rest);
976 });
977
978 if max_version < min_version {
979 panic!("Malformed GDB version range: max < min")
980 }
981
982 return actual_version >= min_version && actual_version <= max_version;
983 }
984 }
985 false
986 }
987
988 fn ignore_lldb(config: &Config, line: &str) -> bool {
989 if let Some(actual_version) = config.lldb_version {
990 if let Some(min_version) = line.strip_prefix("min-lldb-version:").map(str::trim) {
991 let min_version = min_version.parse().unwrap_or_else(|e| {
992 panic!("Unexpected format of LLDB version string: {}\n{:?}", min_version, e);
993 });
994 // Ignore if actual version is smaller the minimum required
995 // version
996 actual_version < min_version
997 } else {
998 line.starts_with("rust-lldb") && !config.lldb_native_rust
999 }
1000 } else {
1001 false
1002 }
1003 }
1004
1005 fn ignore_llvm(config: &Config, line: &str) -> bool {
1006 if config.system_llvm && line.starts_with("no-system-llvm") {
1007 return true;
1008 }
1009 if let Some(needed_components) =
1010 config.parse_name_value_directive(line, "needs-llvm-components")
1011 {
1012 let components: HashSet<_> = config.llvm_components.split_whitespace().collect();
1013 if let Some(missing_component) = needed_components
1014 .split_whitespace()
1015 .find(|needed_component| !components.contains(needed_component))
1016 {
1017 if env::var_os("COMPILETEST_NEEDS_ALL_LLVM_COMPONENTS").is_some() {
1018 panic!("missing LLVM component: {}", missing_component);
1019 }
1020 return true;
1021 }
1022 }
1023 if let Some(actual_version) = config.llvm_version {
1024 if let Some(rest) = line.strip_prefix("min-llvm-version:").map(str::trim) {
1025 let min_version = extract_llvm_version(rest).unwrap();
1026 // Ignore if actual version is smaller the minimum required
1027 // version
1028 actual_version < min_version
1029 } else if let Some(rest) = line.strip_prefix("min-system-llvm-version:").map(str::trim) {
1030 let min_version = extract_llvm_version(rest).unwrap();
1031 // Ignore if using system LLVM and actual version
1032 // is smaller the minimum required version
1033 config.system_llvm && actual_version < min_version
1034 } else if let Some(rest) = line.strip_prefix("ignore-llvm-version:").map(str::trim) {
1035 // Syntax is: "ignore-llvm-version: <version1> [- <version2>]"
1036 let (v_min, v_max) =
1037 extract_version_range(rest, extract_llvm_version).unwrap_or_else(|| {
1038 panic!("couldn't parse version range: {:?}", rest);
1039 });
1040 if v_max < v_min {
1041 panic!("Malformed LLVM version range: max < min")
1042 }
1043 // Ignore if version lies inside of range.
1044 actual_version >= v_min && actual_version <= v_max
1045 } else {
1046 false
1047 }
1048 } else {
1049 false
1050 }
1051 }