]> git.lizzy.rs Git - rust.git/blob - src/tools/compiletest/src/header.rs
Rollup merge of #97709 - compiler-errors:normalize-const-param-ty, r=oli-obk
[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.load_from(testfile, cfg, config);
248
249         props
250     }
251
252     pub fn from_file(testfile: &Path, cfg: Option<&str>, config: &Config) -> Self {
253         let mut props = TestProps::new();
254         props.load_from(testfile, cfg, config);
255
256         match (props.pass_mode, props.fail_mode) {
257             (None, None) => props.fail_mode = Some(FailMode::Check),
258             (Some(_), None) | (None, Some(_)) => {}
259             (Some(_), Some(_)) => panic!("cannot use a *-fail and *-pass mode together"),
260         }
261
262         props
263     }
264
265     /// Loads properties from `testfile` into `props`. If a property is
266     /// tied to a particular revision `foo` (indicated by writing
267     /// `//[foo]`), then the property is ignored unless `cfg` is
268     /// `Some("foo")`.
269     fn load_from(&mut self, testfile: &Path, cfg: Option<&str>, config: &Config) {
270         let mut has_edition = false;
271         if !testfile.is_dir() {
272             let file = File::open(testfile).unwrap();
273
274             iter_header(testfile, file, &mut |revision, ln| {
275                 if revision.is_some() && revision != cfg {
276                     return;
277                 }
278
279                 use directives::*;
280
281                 config.push_name_value_directive(
282                     ln,
283                     ERROR_PATTERN,
284                     &mut self.error_patterns,
285                     |r| r,
286                 );
287
288                 if let Some(flags) = config.parse_name_value_directive(ln, COMPILE_FLAGS) {
289                     self.compile_flags.extend(flags.split_whitespace().map(|s| s.to_owned()));
290                 }
291                 if config.parse_name_value_directive(ln, INCORRECT_COMPILER_FLAGS).is_some() {
292                     panic!("`compiler-flags` directive should be spelled `compile-flags`");
293                 }
294
295                 if let Some(edition) = config.parse_edition(ln) {
296                     self.compile_flags.push(format!("--edition={}", edition));
297                     has_edition = true;
298                 }
299
300                 config.parse_and_update_revisions(ln, &mut self.revisions);
301
302                 config.set_name_value_directive(ln, RUN_FLAGS, &mut self.run_flags, |r| r);
303
304                 if self.pp_exact.is_none() {
305                     self.pp_exact = config.parse_pp_exact(ln, testfile);
306                 }
307
308                 config.set_name_directive(ln, SHOULD_ICE, &mut self.should_ice);
309                 config.set_name_directive(ln, BUILD_AUX_DOCS, &mut self.build_aux_docs);
310                 config.set_name_directive(ln, FORCE_HOST, &mut self.force_host);
311                 config.set_name_directive(ln, CHECK_STDOUT, &mut self.check_stdout);
312                 config.set_name_directive(ln, CHECK_RUN_RESULTS, &mut self.check_run_results);
313                 config.set_name_directive(
314                     ln,
315                     DONT_CHECK_COMPILER_STDOUT,
316                     &mut self.dont_check_compiler_stdout,
317                 );
318                 config.set_name_directive(
319                     ln,
320                     DONT_CHECK_COMPILER_STDERR,
321                     &mut self.dont_check_compiler_stderr,
322                 );
323                 config.set_name_directive(ln, NO_PREFER_DYNAMIC, &mut self.no_prefer_dynamic);
324                 config.set_name_directive(ln, PRETTY_EXPANDED, &mut self.pretty_expanded);
325
326                 if let Some(m) = config.parse_name_value_directive(ln, PRETTY_MODE) {
327                     self.pretty_mode = m;
328                 }
329
330                 config.set_name_directive(ln, PRETTY_COMPARE_ONLY, &mut self.pretty_compare_only);
331                 config.push_name_value_directive(ln, AUX_BUILD, &mut self.aux_builds, |r| {
332                     r.trim().to_string()
333                 });
334                 config.push_name_value_directive(
335                     ln,
336                     AUX_CRATE,
337                     &mut self.aux_crates,
338                     Config::parse_aux_crate,
339                 );
340                 config.push_name_value_directive(
341                     ln,
342                     EXEC_ENV,
343                     &mut self.exec_env,
344                     Config::parse_env,
345                 );
346                 config.push_name_value_directive(
347                     ln,
348                     RUSTC_ENV,
349                     &mut self.rustc_env,
350                     Config::parse_env,
351                 );
352                 config.push_name_value_directive(
353                     ln,
354                     UNSET_RUSTC_ENV,
355                     &mut self.unset_rustc_env,
356                     |r| r,
357                 );
358                 config.push_name_value_directive(ln, FORBID_OUTPUT, &mut self.forbid_output, |r| r);
359                 config.set_name_directive(
360                     ln,
361                     CHECK_TEST_LINE_NUMBERS_MATCH,
362                     &mut self.check_test_line_numbers_match,
363                 );
364
365                 self.update_pass_mode(ln, cfg, config);
366                 self.update_fail_mode(ln, config);
367
368                 config.set_name_directive(ln, IGNORE_PASS, &mut self.ignore_pass);
369
370                 if let Some(rule) = config.parse_custom_normalization(ln, "normalize-stdout") {
371                     self.normalize_stdout.push(rule);
372                 }
373                 if let Some(rule) = config.parse_custom_normalization(ln, "normalize-stderr") {
374                     self.normalize_stderr.push(rule);
375                 }
376
377                 if let Some(code) = config
378                     .parse_name_value_directive(ln, FAILURE_STATUS)
379                     .and_then(|code| code.trim().parse::<i32>().ok())
380                 {
381                     self.failure_status = code;
382                 }
383
384                 config.set_name_directive(ln, RUN_RUSTFIX, &mut self.run_rustfix);
385                 config.set_name_directive(
386                     ln,
387                     RUSTFIX_ONLY_MACHINE_APPLICABLE,
388                     &mut self.rustfix_only_machine_applicable,
389                 );
390                 config.set_name_value_directive(
391                     ln,
392                     ASSEMBLY_OUTPUT,
393                     &mut self.assembly_output,
394                     |r| r.trim().to_string(),
395                 );
396                 config.set_name_directive(ln, STDERR_PER_BITWIDTH, &mut self.stderr_per_bitwidth);
397                 config.set_name_directive(ln, INCREMENTAL, &mut self.incremental);
398                 config.set_name_directive(ln, KNOWN_BUG, &mut self.known_bug);
399                 config.set_name_value_directive(ln, MIR_UNIT_TEST, &mut self.mir_unit_test, |s| {
400                     s.trim().to_string()
401                 });
402             });
403         }
404
405         if self.failure_status == -1 {
406             self.failure_status = 1;
407         }
408         if self.should_ice {
409             self.failure_status = 101;
410         }
411
412         if config.mode == Mode::Incremental {
413             self.incremental = true;
414         }
415
416         for key in &["RUST_TEST_NOCAPTURE", "RUST_TEST_THREADS"] {
417             if let Ok(val) = env::var(key) {
418                 if self.exec_env.iter().find(|&&(ref x, _)| x == key).is_none() {
419                     self.exec_env.push(((*key).to_owned(), val))
420                 }
421             }
422         }
423
424         if let (Some(edition), false) = (&config.edition, has_edition) {
425             self.compile_flags.push(format!("--edition={}", edition));
426         }
427     }
428
429     fn update_fail_mode(&mut self, ln: &str, config: &Config) {
430         let check_ui = |mode: &str| {
431             if config.mode != Mode::Ui {
432                 panic!("`{}-fail` header is only supported in UI tests", mode);
433             }
434         };
435         if config.mode == Mode::Ui && config.parse_name_directive(ln, "compile-fail") {
436             panic!("`compile-fail` header is useless in UI tests");
437         }
438         let fail_mode = if config.parse_name_directive(ln, "check-fail") {
439             check_ui("check");
440             Some(FailMode::Check)
441         } else if config.parse_name_directive(ln, "build-fail") {
442             check_ui("build");
443             Some(FailMode::Build)
444         } else if config.parse_name_directive(ln, "run-fail") {
445             check_ui("run");
446             Some(FailMode::Run)
447         } else {
448             None
449         };
450         match (self.fail_mode, fail_mode) {
451             (None, Some(_)) => self.fail_mode = fail_mode,
452             (Some(_), Some(_)) => panic!("multiple `*-fail` headers in a single test"),
453             (_, None) => {}
454         }
455     }
456
457     fn update_pass_mode(&mut self, ln: &str, revision: Option<&str>, config: &Config) {
458         let check_no_run = |s| {
459             if config.mode != Mode::Ui && config.mode != Mode::Incremental {
460                 panic!("`{}` header is only supported in UI and incremental tests", s);
461             }
462             if config.mode == Mode::Incremental
463                 && !revision.map_or(false, |r| r.starts_with("cfail"))
464                 && !self.revisions.iter().all(|r| r.starts_with("cfail"))
465             {
466                 panic!("`{}` header is only supported in `cfail` incremental tests", s);
467             }
468         };
469         let pass_mode = if config.parse_name_directive(ln, "check-pass") {
470             check_no_run("check-pass");
471             Some(PassMode::Check)
472         } else if config.parse_name_directive(ln, "build-pass") {
473             check_no_run("build-pass");
474             Some(PassMode::Build)
475         } else if config.parse_name_directive(ln, "run-pass") {
476             if config.mode != Mode::Ui {
477                 panic!("`run-pass` header is only supported in UI tests")
478             }
479             Some(PassMode::Run)
480         } else {
481             None
482         };
483         match (self.pass_mode, pass_mode) {
484             (None, Some(_)) => self.pass_mode = pass_mode,
485             (Some(_), Some(_)) => panic!("multiple `*-pass` headers in a single test"),
486             (_, None) => {}
487         }
488     }
489
490     pub fn pass_mode(&self, config: &Config) -> Option<PassMode> {
491         if !self.ignore_pass && self.fail_mode.is_none() && config.mode == Mode::Ui {
492             if let (mode @ Some(_), Some(_)) = (config.force_pass_mode, self.pass_mode) {
493                 return mode;
494             }
495         }
496         self.pass_mode
497     }
498
499     // does not consider CLI override for pass mode
500     pub fn local_pass_mode(&self) -> Option<PassMode> {
501         self.pass_mode
502     }
503 }
504
505 fn iter_header<R: Read>(testfile: &Path, rdr: R, it: &mut dyn FnMut(Option<&str>, &str)) {
506     if testfile.is_dir() {
507         return;
508     }
509
510     let comment = if testfile.extension().map(|e| e == "rs") == Some(true) { "//" } else { "#" };
511
512     let mut rdr = BufReader::new(rdr);
513     let mut ln = String::new();
514
515     loop {
516         ln.clear();
517         if rdr.read_line(&mut ln).unwrap() == 0 {
518             break;
519         }
520
521         // Assume that any directives will be found before the first
522         // module or function. This doesn't seem to be an optimization
523         // with a warm page cache. Maybe with a cold one.
524         let ln = ln.trim();
525         if ln.starts_with("fn") || ln.starts_with("mod") {
526             return;
527         } else if ln.starts_with(comment) && ln[comment.len()..].trim_start().starts_with('[') {
528             // A comment like `//[foo]` is specific to revision `foo`
529             if let Some(close_brace) = ln.find(']') {
530                 let open_brace = ln.find('[').unwrap();
531                 let lncfg = &ln[open_brace + 1..close_brace];
532                 it(Some(lncfg), ln[(close_brace + 1)..].trim_start());
533             } else {
534                 panic!("malformed condition directive: expected `{}[foo]`, found `{}`", comment, ln)
535             }
536         } else if ln.starts_with(comment) {
537             it(None, ln[comment.len()..].trim_start());
538         }
539     }
540 }
541
542 impl Config {
543     fn parse_aux_crate(r: String) -> (String, String) {
544         let mut parts = r.trim().splitn(2, '=');
545         (
546             parts.next().expect("missing aux-crate name (e.g. log=log.rs)").to_string(),
547             parts.next().expect("missing aux-crate value (e.g. log=log.rs)").to_string(),
548         )
549     }
550
551     fn parse_and_update_revisions(&self, line: &str, existing: &mut Vec<String>) {
552         if let Some(raw) = self.parse_name_value_directive(line, "revisions") {
553             let mut duplicates: HashSet<_> = existing.iter().cloned().collect();
554             for revision in raw.split_whitespace().map(|r| r.to_string()) {
555                 if !duplicates.insert(revision.clone()) {
556                     panic!("Duplicate revision: `{}` in line `{}`", revision, raw);
557                 }
558                 existing.push(revision);
559             }
560         }
561     }
562
563     fn parse_env(nv: String) -> (String, String) {
564         // nv is either FOO or FOO=BAR
565         let mut strs: Vec<String> = nv.splitn(2, '=').map(str::to_owned).collect();
566
567         match strs.len() {
568             1 => (strs.pop().unwrap(), String::new()),
569             2 => {
570                 let end = strs.pop().unwrap();
571                 (strs.pop().unwrap(), end)
572             }
573             n => panic!("Expected 1 or 2 strings, not {}", n),
574         }
575     }
576
577     fn parse_pp_exact(&self, line: &str, testfile: &Path) -> Option<PathBuf> {
578         if let Some(s) = self.parse_name_value_directive(line, "pp-exact") {
579             Some(PathBuf::from(&s))
580         } else if self.parse_name_directive(line, "pp-exact") {
581             testfile.file_name().map(PathBuf::from)
582         } else {
583             None
584         }
585     }
586
587     fn parse_custom_normalization(&self, mut line: &str, prefix: &str) -> Option<(String, String)> {
588         if self.parse_cfg_name_directive(line, prefix) == ParsedNameDirective::Match {
589             let from = parse_normalization_string(&mut line)?;
590             let to = parse_normalization_string(&mut line)?;
591             Some((from, to))
592         } else {
593             None
594         }
595     }
596
597     fn parse_needs_matching_clang(&self, line: &str) -> bool {
598         self.parse_name_directive(line, "needs-matching-clang")
599     }
600
601     fn parse_needs_profiler_support(&self, line: &str) -> bool {
602         self.parse_name_directive(line, "needs-profiler-support")
603     }
604
605     /// Parses a name-value directive which contains config-specific information, e.g., `ignore-x86`
606     /// or `normalize-stderr-32bit`.
607     fn parse_cfg_name_directive(&self, line: &str, prefix: &str) -> ParsedNameDirective {
608         if !line.as_bytes().starts_with(prefix.as_bytes()) {
609             return ParsedNameDirective::NoMatch;
610         }
611         if line.as_bytes().get(prefix.len()) != Some(&b'-') {
612             return ParsedNameDirective::NoMatch;
613         }
614
615         let name = line[prefix.len() + 1..].split(&[':', ' '][..]).next().unwrap();
616
617         let is_match = name == "test" ||
618             self.target == name ||                              // triple
619             util::matches_os(&self.target, name) ||             // target
620             util::matches_env(&self.target, name) ||            // env
621             self.target.ends_with(name) ||                      // target and env
622             name == util::get_arch(&self.target) ||             // architecture
623             name == util::get_pointer_width(&self.target) ||    // pointer width
624             name == self.stage_id.split('-').next().unwrap() || // stage
625             name == self.channel ||                             // channel
626             (self.target != self.host && name == "cross-compile") ||
627             (name == "endian-big" && util::is_big_endian(&self.target)) ||
628             (self.remote_test_client.is_some() && name == "remote") ||
629             match self.compare_mode {
630                 Some(CompareMode::Polonius) => name == "compare-mode-polonius",
631                 Some(CompareMode::Chalk) => name == "compare-mode-chalk",
632                 Some(CompareMode::SplitDwarf) => name == "compare-mode-split-dwarf",
633                 Some(CompareMode::SplitDwarfSingle) => name == "compare-mode-split-dwarf-single",
634                 None => false,
635             } ||
636             (cfg!(debug_assertions) && name == "debug") ||
637             match self.debugger {
638                 Some(Debugger::Cdb) => name == "cdb",
639                 Some(Debugger::Gdb) => name == "gdb",
640                 Some(Debugger::Lldb) => name == "lldb",
641                 None => false,
642             };
643
644         if is_match { ParsedNameDirective::Match } else { ParsedNameDirective::NoMatch }
645     }
646
647     fn has_cfg_prefix(&self, line: &str, prefix: &str) -> bool {
648         // returns whether this line contains this prefix or not. For prefix
649         // "ignore", returns true if line says "ignore-x86_64", "ignore-arch",
650         // "ignore-android" etc.
651         line.starts_with(prefix) && line.as_bytes().get(prefix.len()) == Some(&b'-')
652     }
653
654     fn parse_name_directive(&self, line: &str, directive: &str) -> bool {
655         // Ensure the directive is a whole word. Do not match "ignore-x86" when
656         // the line says "ignore-x86_64".
657         line.starts_with(directive)
658             && matches!(line.as_bytes().get(directive.len()), None | Some(&b' ') | Some(&b':'))
659     }
660
661     pub fn parse_name_value_directive(&self, line: &str, directive: &str) -> Option<String> {
662         let colon = directive.len();
663         if line.starts_with(directive) && line.as_bytes().get(colon) == Some(&b':') {
664             let value = line[(colon + 1)..].to_owned();
665             debug!("{}: {}", directive, value);
666             Some(expand_variables(value, self))
667         } else {
668             None
669         }
670     }
671
672     pub fn find_rust_src_root(&self) -> Option<PathBuf> {
673         let mut path = self.src_base.clone();
674         let path_postfix = Path::new("src/etc/lldb_batchmode.py");
675
676         while path.pop() {
677             if path.join(&path_postfix).is_file() {
678                 return Some(path);
679             }
680         }
681
682         None
683     }
684
685     fn parse_edition(&self, line: &str) -> Option<String> {
686         self.parse_name_value_directive(line, "edition")
687     }
688
689     fn set_name_directive(&self, line: &str, directive: &str, value: &mut bool) {
690         if !*value {
691             *value = self.parse_name_directive(line, directive)
692         }
693     }
694
695     fn set_name_value_directive<T>(
696         &self,
697         line: &str,
698         directive: &str,
699         value: &mut Option<T>,
700         parse: impl FnOnce(String) -> T,
701     ) {
702         if value.is_none() {
703             *value = self.parse_name_value_directive(line, directive).map(parse);
704         }
705     }
706
707     fn push_name_value_directive<T>(
708         &self,
709         line: &str,
710         directive: &str,
711         values: &mut Vec<T>,
712         parse: impl FnOnce(String) -> T,
713     ) {
714         if let Some(value) = self.parse_name_value_directive(line, directive).map(parse) {
715             values.push(value);
716         }
717     }
718 }
719
720 fn expand_variables(mut value: String, config: &Config) -> String {
721     const CWD: &str = "{{cwd}}";
722     const SRC_BASE: &str = "{{src-base}}";
723     const BUILD_BASE: &str = "{{build-base}}";
724
725     if value.contains(CWD) {
726         let cwd = env::current_dir().unwrap();
727         value = value.replace(CWD, &cwd.to_string_lossy());
728     }
729
730     if value.contains(SRC_BASE) {
731         value = value.replace(SRC_BASE, &config.src_base.to_string_lossy());
732     }
733
734     if value.contains(BUILD_BASE) {
735         value = value.replace(BUILD_BASE, &config.build_base.to_string_lossy());
736     }
737
738     value
739 }
740
741 /// Finds the next quoted string `"..."` in `line`, and extract the content from it. Move the `line`
742 /// variable after the end of the quoted string.
743 ///
744 /// # Examples
745 ///
746 /// ```
747 /// let mut s = "normalize-stderr-32bit: \"something (32 bits)\" -> \"something ($WORD bits)\".";
748 /// let first = parse_normalization_string(&mut s);
749 /// assert_eq!(first, Some("something (32 bits)".to_owned()));
750 /// assert_eq!(s, " -> \"something ($WORD bits)\".");
751 /// ```
752 fn parse_normalization_string(line: &mut &str) -> Option<String> {
753     // FIXME support escapes in strings.
754     let begin = line.find('"')? + 1;
755     let end = line[begin..].find('"')? + begin;
756     let result = line[begin..end].to_owned();
757     *line = &line[end + 1..];
758     Some(result)
759 }
760
761 pub fn extract_llvm_version(version: &str) -> Option<u32> {
762     let pat = |c: char| !c.is_ascii_digit() && c != '.';
763     let version_without_suffix = match version.find(pat) {
764         Some(pos) => &version[..pos],
765         None => version,
766     };
767     let components: Vec<u32> = version_without_suffix
768         .split('.')
769         .map(|s| s.parse().expect("Malformed version component"))
770         .collect();
771     let version = match *components {
772         [a] => a * 10_000,
773         [a, b] => a * 10_000 + b * 100,
774         [a, b, c] => a * 10_000 + b * 100 + c,
775         _ => panic!("Malformed version"),
776     };
777     Some(version)
778 }
779
780 /// Takes a directive of the form "<version1> [- <version2>]",
781 /// returns the numeric representation of <version1> and <version2> as
782 /// tuple: (<version1> as u32, <version2> as u32)
783 ///
784 /// If the <version2> part is omitted, the second component of the tuple
785 /// is the same as <version1>.
786 fn extract_version_range<F>(line: &str, parse: F) -> Option<(u32, u32)>
787 where
788     F: Fn(&str) -> Option<u32>,
789 {
790     let mut splits = line.splitn(2, "- ").map(str::trim);
791     let min = splits.next().unwrap();
792     if min.ends_with('-') {
793         return None;
794     }
795
796     let max = splits.next();
797
798     if min.is_empty() {
799         return None;
800     }
801
802     let min = parse(min)?;
803     let max = match max {
804         Some(max) if max.is_empty() => return None,
805         Some(max) => parse(max)?,
806         _ => min,
807     };
808
809     Some((min, max))
810 }
811
812 pub fn make_test_description<R: Read>(
813     config: &Config,
814     name: test::TestName,
815     path: &Path,
816     src: R,
817     cfg: Option<&str>,
818 ) -> test::TestDesc {
819     let mut ignore = false;
820     let ignore_message = None;
821     let mut should_fail = false;
822
823     let rustc_has_profiler_support = env::var_os("RUSTC_PROFILER_SUPPORT").is_some();
824     let rustc_has_sanitizer_support = env::var_os("RUSTC_SANITIZER_SUPPORT").is_some();
825     let has_asm_support = util::has_asm_support(&config.target);
826     let has_asan = util::ASAN_SUPPORTED_TARGETS.contains(&&*config.target);
827     let has_lsan = util::LSAN_SUPPORTED_TARGETS.contains(&&*config.target);
828     let has_msan = util::MSAN_SUPPORTED_TARGETS.contains(&&*config.target);
829     let has_tsan = util::TSAN_SUPPORTED_TARGETS.contains(&&*config.target);
830     let has_hwasan = util::HWASAN_SUPPORTED_TARGETS.contains(&&*config.target);
831     let has_memtag = util::MEMTAG_SUPPORTED_TARGETS.contains(&&*config.target);
832     // for `-Z gcc-ld=lld`
833     let has_rust_lld = config
834         .compile_lib_path
835         .join("rustlib")
836         .join(&config.target)
837         .join("bin")
838         .join("gcc-ld")
839         .join(if config.host.contains("windows") { "ld.exe" } else { "ld" })
840         .exists();
841     iter_header(path, src, &mut |revision, ln| {
842         if revision.is_some() && revision != cfg {
843             return;
844         }
845         ignore = match config.parse_cfg_name_directive(ln, "ignore") {
846             ParsedNameDirective::Match => true,
847             ParsedNameDirective::NoMatch => ignore,
848         };
849         if config.has_cfg_prefix(ln, "only") {
850             ignore = match config.parse_cfg_name_directive(ln, "only") {
851                 ParsedNameDirective::Match => ignore,
852                 ParsedNameDirective::NoMatch => true,
853             };
854         }
855         ignore |= ignore_llvm(config, ln);
856         ignore |=
857             config.run_clang_based_tests_with.is_none() && config.parse_needs_matching_clang(ln);
858         ignore |= !has_asm_support && config.parse_name_directive(ln, "needs-asm-support");
859         ignore |= !rustc_has_profiler_support && config.parse_needs_profiler_support(ln);
860         ignore |= !config.run_enabled() && config.parse_name_directive(ln, "needs-run-enabled");
861         ignore |= !rustc_has_sanitizer_support
862             && config.parse_name_directive(ln, "needs-sanitizer-support");
863         ignore |= !has_asan && config.parse_name_directive(ln, "needs-sanitizer-address");
864         ignore |= !has_lsan && config.parse_name_directive(ln, "needs-sanitizer-leak");
865         ignore |= !has_msan && config.parse_name_directive(ln, "needs-sanitizer-memory");
866         ignore |= !has_tsan && config.parse_name_directive(ln, "needs-sanitizer-thread");
867         ignore |= !has_hwasan && config.parse_name_directive(ln, "needs-sanitizer-hwaddress");
868         ignore |= !has_memtag && config.parse_name_directive(ln, "needs-sanitizer-memtag");
869         ignore |= config.target_panic == PanicStrategy::Abort
870             && config.parse_name_directive(ln, "needs-unwind");
871         ignore |= config.target == "wasm32-unknown-unknown"
872             && config.parse_name_directive(ln, directives::CHECK_RUN_RESULTS);
873         ignore |= config.debugger == Some(Debugger::Cdb) && ignore_cdb(config, ln);
874         ignore |= config.debugger == Some(Debugger::Gdb) && ignore_gdb(config, ln);
875         ignore |= config.debugger == Some(Debugger::Lldb) && ignore_lldb(config, ln);
876         ignore |= !has_rust_lld && config.parse_name_directive(ln, "needs-rust-lld");
877         should_fail |= config.parse_name_directive(ln, "should-fail");
878     });
879
880     // The `should-fail` annotation doesn't apply to pretty tests,
881     // since we run the pretty printer across all tests by default.
882     // If desired, we could add a `should-fail-pretty` annotation.
883     let should_panic = match config.mode {
884         crate::common::Pretty => test::ShouldPanic::No,
885         _ if should_fail => test::ShouldPanic::Yes,
886         _ => test::ShouldPanic::No,
887     };
888
889     test::TestDesc {
890         name,
891         ignore,
892         ignore_message,
893         should_panic,
894         compile_fail: false,
895         no_run: false,
896         test_type: test::TestType::Unknown,
897     }
898 }
899
900 fn ignore_cdb(config: &Config, line: &str) -> bool {
901     if let Some(actual_version) = config.cdb_version {
902         if let Some(min_version) = line.strip_prefix("min-cdb-version:").map(str::trim) {
903             let min_version = extract_cdb_version(min_version).unwrap_or_else(|| {
904                 panic!("couldn't parse version range: {:?}", min_version);
905             });
906
907             // Ignore if actual version is smaller than the minimum
908             // required version
909             return actual_version < min_version;
910         }
911     }
912     false
913 }
914
915 fn ignore_gdb(config: &Config, line: &str) -> bool {
916     if let Some(actual_version) = config.gdb_version {
917         if let Some(rest) = line.strip_prefix("min-gdb-version:").map(str::trim) {
918             let (start_ver, end_ver) = extract_version_range(rest, extract_gdb_version)
919                 .unwrap_or_else(|| {
920                     panic!("couldn't parse version range: {:?}", rest);
921                 });
922
923             if start_ver != end_ver {
924                 panic!("Expected single GDB version")
925             }
926             // Ignore if actual version is smaller than the minimum
927             // required version
928             return actual_version < start_ver;
929         } else if let Some(rest) = line.strip_prefix("ignore-gdb-version:").map(str::trim) {
930             let (min_version, max_version) = extract_version_range(rest, extract_gdb_version)
931                 .unwrap_or_else(|| {
932                     panic!("couldn't parse version range: {:?}", rest);
933                 });
934
935             if max_version < min_version {
936                 panic!("Malformed GDB version range: max < min")
937             }
938
939             return actual_version >= min_version && actual_version <= max_version;
940         }
941     }
942     false
943 }
944
945 fn ignore_lldb(config: &Config, line: &str) -> bool {
946     if let Some(actual_version) = config.lldb_version {
947         if let Some(min_version) = line.strip_prefix("min-lldb-version:").map(str::trim) {
948             let min_version = min_version.parse().unwrap_or_else(|e| {
949                 panic!("Unexpected format of LLDB version string: {}\n{:?}", min_version, e);
950             });
951             // Ignore if actual version is smaller the minimum required
952             // version
953             actual_version < min_version
954         } else {
955             line.starts_with("rust-lldb") && !config.lldb_native_rust
956         }
957     } else {
958         false
959     }
960 }
961
962 fn ignore_llvm(config: &Config, line: &str) -> bool {
963     if config.system_llvm && line.starts_with("no-system-llvm") {
964         return true;
965     }
966     if let Some(needed_components) =
967         config.parse_name_value_directive(line, "needs-llvm-components")
968     {
969         let components: HashSet<_> = config.llvm_components.split_whitespace().collect();
970         if let Some(missing_component) = needed_components
971             .split_whitespace()
972             .find(|needed_component| !components.contains(needed_component))
973         {
974             if env::var_os("COMPILETEST_NEEDS_ALL_LLVM_COMPONENTS").is_some() {
975                 panic!("missing LLVM component: {}", missing_component);
976             }
977             return true;
978         }
979     }
980     if let Some(actual_version) = config.llvm_version {
981         if let Some(rest) = line.strip_prefix("min-llvm-version:").map(str::trim) {
982             let min_version = extract_llvm_version(rest).unwrap();
983             // Ignore if actual version is smaller the minimum required
984             // version
985             actual_version < min_version
986         } else if let Some(rest) = line.strip_prefix("min-system-llvm-version:").map(str::trim) {
987             let min_version = extract_llvm_version(rest).unwrap();
988             // Ignore if using system LLVM and actual version
989             // is smaller the minimum required version
990             config.system_llvm && actual_version < min_version
991         } else if let Some(rest) = line.strip_prefix("ignore-llvm-version:").map(str::trim) {
992             // Syntax is: "ignore-llvm-version: <version1> [- <version2>]"
993             let (v_min, v_max) =
994                 extract_version_range(rest, extract_llvm_version).unwrap_or_else(|| {
995                     panic!("couldn't parse version range: {:?}", rest);
996                 });
997             if v_max < v_min {
998                 panic!("Malformed LLVM version range: max < min")
999             }
1000             // Ignore if version lies inside of range.
1001             actual_version >= v_min && actual_version <= v_max
1002         } else {
1003             false
1004         }
1005     } else {
1006         false
1007     }
1008 }