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