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