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