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