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