]> git.lizzy.rs Git - rust.git/blob - src/tools/compiletest/src/header.rs
f4a82aeb307dc86410f8b4605525bd733dc918f1
[rust.git] / src / tools / compiletest / src / header.rs
1 // Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 use std::env;
12 use std::fs::File;
13 use std::io::prelude::*;
14 use std::io::BufReader;
15 use std::path::{Path, PathBuf};
16
17 use common::{self, CompareMode, Config, Mode};
18 use util;
19
20 use extract_gdb_version;
21
22 /// Whether to ignore the test.
23 #[derive(Clone, Copy, PartialEq, Debug)]
24 pub enum Ignore {
25     /// Run it.
26     Run,
27     /// Ignore it totally.
28     Ignore,
29     /// Ignore only the gdb test, but run the lldb test.
30     IgnoreGdb,
31     /// Ignore only the lldb test, but run the gdb test.
32     IgnoreLldb,
33 }
34
35 impl Ignore {
36     pub fn can_run_gdb(&self) -> bool {
37         *self == Ignore::Run || *self == Ignore::IgnoreLldb
38     }
39
40     pub fn can_run_lldb(&self) -> bool {
41         *self == Ignore::Run || *self == Ignore::IgnoreGdb
42     }
43
44     pub fn no_gdb(&self) -> Ignore {
45         match *self {
46             Ignore::Run => Ignore::IgnoreGdb,
47             Ignore::IgnoreGdb => Ignore::IgnoreGdb,
48             _ => Ignore::Ignore,
49         }
50     }
51
52     pub fn no_lldb(&self) -> Ignore {
53         match *self {
54             Ignore::Run => Ignore::IgnoreLldb,
55             Ignore::IgnoreLldb => Ignore::IgnoreLldb,
56             _ => Ignore::Ignore,
57         }
58     }
59 }
60
61 /// The result of parse_cfg_name_directive.
62 #[derive(Clone, Copy, PartialEq, Debug)]
63 enum ParsedNameDirective {
64     /// No match.
65     NoMatch,
66     /// Match.
67     Match,
68     /// Mode was DebugInfoBoth and this matched gdb.
69     MatchGdb,
70     /// Mode was DebugInfoBoth and this matched lldb.
71     MatchLldb,
72 }
73
74 /// Properties which must be known very early, before actually running
75 /// the test.
76 pub struct EarlyProps {
77     pub ignore: Ignore,
78     pub should_fail: bool,
79     pub aux: Vec<String>,
80     pub revisions: Vec<String>,
81 }
82
83 impl EarlyProps {
84     pub fn from_file(config: &Config, testfile: &Path) -> Self {
85         let mut props = EarlyProps {
86             ignore: Ignore::Run,
87             should_fail: false,
88             aux: Vec::new(),
89             revisions: vec![],
90         };
91
92         if config.mode == common::DebugInfoBoth {
93             if config.lldb_python_dir.is_none() {
94                 props.ignore = props.ignore.no_lldb();
95             }
96             if config.gdb_version.is_none() {
97                 props.ignore = props.ignore.no_gdb();
98             }
99         }
100
101         iter_header(testfile, None, &mut |ln| {
102             // we should check if any only-<platform> exists and if it exists
103             // and does not matches the current platform, skip the test
104             if props.ignore != Ignore::Ignore {
105                 props.ignore = match config.parse_cfg_name_directive(ln, "ignore") {
106                     ParsedNameDirective::Match => Ignore::Ignore,
107                     ParsedNameDirective::NoMatch => props.ignore,
108                     ParsedNameDirective::MatchGdb => props.ignore.no_gdb(),
109                     ParsedNameDirective::MatchLldb => props.ignore.no_lldb(),
110                 };
111
112                 if config.has_cfg_prefix(ln, "only") {
113                     props.ignore = match config.parse_cfg_name_directive(ln, "only") {
114                         ParsedNameDirective::Match => props.ignore,
115                         ParsedNameDirective::NoMatch => Ignore::Ignore,
116                         ParsedNameDirective::MatchLldb => props.ignore.no_gdb(),
117                         ParsedNameDirective::MatchGdb => props.ignore.no_lldb(),
118                     };
119                 }
120
121                 if ignore_llvm(config, ln) {
122                     props.ignore = Ignore::Ignore;
123                 }
124             }
125
126             if (config.mode == common::DebugInfoGdb || config.mode == common::DebugInfoBoth) &&
127                 props.ignore.can_run_gdb() && ignore_gdb(config, ln) {
128                 props.ignore = props.ignore.no_gdb();
129             }
130
131             if (config.mode == common::DebugInfoLldb || config.mode == common::DebugInfoBoth) &&
132                 props.ignore.can_run_lldb() && ignore_lldb(config, ln) {
133                 props.ignore = props.ignore.no_lldb();
134             }
135
136             if let Some(s) = config.parse_aux_build(ln) {
137                 props.aux.push(s);
138             }
139
140             if let Some(r) = config.parse_revisions(ln) {
141                 props.revisions.extend(r);
142             }
143
144             props.should_fail = props.should_fail || config.parse_name_directive(ln, "should-fail");
145         });
146
147         return props;
148
149         fn ignore_gdb(config: &Config, line: &str) -> bool {
150             if let Some(actual_version) = config.gdb_version {
151                 if line.starts_with("min-gdb-version") {
152                     let (start_ver, end_ver) = extract_gdb_version_range(line);
153
154                     if start_ver != end_ver {
155                         panic!("Expected single GDB version")
156                     }
157                     // Ignore if actual version is smaller the minimum required
158                     // version
159                     actual_version < start_ver
160                 } else if line.starts_with("ignore-gdb-version") {
161                     let (min_version, max_version) = extract_gdb_version_range(line);
162
163                     if max_version < min_version {
164                         panic!("Malformed GDB version range: max < min")
165                     }
166
167                     actual_version >= min_version && actual_version <= max_version
168                 } else {
169                     false
170                 }
171             } else {
172                 false
173             }
174         }
175
176         // Takes a directive of the form "ignore-gdb-version <version1> [- <version2>]",
177         // returns the numeric representation of <version1> and <version2> as
178         // tuple: (<version1> as u32, <version2> as u32)
179         // If the <version2> part is omitted, the second component of the tuple
180         // is the same as <version1>.
181         fn extract_gdb_version_range(line: &str) -> (u32, u32) {
182             const ERROR_MESSAGE: &'static str = "Malformed GDB version directive";
183
184             let range_components = line.split(&[' ', '-'][..])
185                                        .filter(|word| !word.is_empty())
186                                        .map(extract_gdb_version)
187                                        .skip_while(Option::is_none)
188                                        .take(3) // 3 or more = invalid, so take at most 3.
189                                        .collect::<Vec<Option<u32>>>();
190
191             match range_components.len() {
192                 1 => {
193                     let v = range_components[0].unwrap();
194                     (v, v)
195                 }
196                 2 => {
197                     let v_min = range_components[0].unwrap();
198                     let v_max = range_components[1].expect(ERROR_MESSAGE);
199                     (v_min, v_max)
200                 }
201                 _ => panic!(ERROR_MESSAGE),
202             }
203         }
204
205         fn ignore_lldb(config: &Config, line: &str) -> bool {
206             if let Some(ref actual_version) = config.lldb_version {
207                 if line.starts_with("min-lldb-version") {
208                     let min_version = line.trim_right()
209                         .rsplit(' ')
210                         .next()
211                         .expect("Malformed lldb version directive");
212                     // Ignore if actual version is smaller the minimum required
213                     // version
214                     lldb_version_to_int(actual_version) < lldb_version_to_int(min_version)
215                 } else if line.starts_with("rust-lldb") && !config.lldb_native_rust {
216                     true
217                 } else {
218                     false
219                 }
220             } else {
221                 false
222             }
223         }
224
225         fn ignore_llvm(config: &Config, line: &str) -> bool {
226             if config.system_llvm && line.starts_with("no-system-llvm") {
227                 return true;
228             }
229             if let Some(ref actual_version) = config.llvm_version {
230                 if line.starts_with("min-llvm-version") {
231                     let min_version = line.trim_right()
232                         .rsplit(' ')
233                         .next()
234                         .expect("Malformed llvm version directive");
235                     // Ignore if actual version is smaller the minimum required
236                     // version
237                     &actual_version[..] < min_version
238                 } else if line.starts_with("min-system-llvm-version") {
239                     let min_version = line.trim_right()
240                         .rsplit(' ')
241                         .next()
242                         .expect("Malformed llvm version directive");
243                     // Ignore if using system LLVM and actual version
244                     // is smaller the minimum required version
245                     config.system_llvm && &actual_version[..] < min_version
246                 } else if line.starts_with("ignore-llvm-version") {
247                     // Syntax is: "ignore-llvm-version <version1> [- <version2>]"
248                     let range_components = line.split(' ')
249                         .skip(1) // Skip the directive.
250                         .map(|s| s.trim())
251                         .filter(|word| !word.is_empty() && word != &"-")
252                         .take(3) // 3 or more = invalid, so take at most 3.
253                         .collect::<Vec<&str>>();
254                     match range_components.len() {
255                         1 => {
256                             &actual_version[..] == range_components[0]
257                         }
258                         2 => {
259                             let v_min = range_components[0];
260                             let v_max = range_components[1];
261                             if v_max < v_min {
262                                 panic!("Malformed LLVM version range: max < min")
263                             }
264                             // Ignore if version lies inside of range.
265                             &actual_version[..] >= v_min && &actual_version[..] <= v_max
266                         }
267                         _ => panic!("Malformed LLVM version directive"),
268                     }
269                 } else {
270                     false
271                 }
272             } else {
273                 false
274             }
275         }
276     }
277 }
278
279 #[derive(Clone, Debug)]
280 pub struct TestProps {
281     // Lines that should be expected, in order, on standard out
282     pub error_patterns: Vec<String>,
283     // Extra flags to pass to the compiler
284     pub compile_flags: Vec<String>,
285     // Extra flags to pass when the compiled code is run (such as --bench)
286     pub run_flags: Option<String>,
287     // If present, the name of a file that this test should match when
288     // pretty-printed
289     pub pp_exact: Option<PathBuf>,
290     // Other crates that should be compiled (typically from the same
291     // directory as the test, but for backwards compatibility reasons
292     // we also check the auxiliary directory)
293     pub aux_builds: Vec<String>,
294     // Environment settings to use for compiling
295     pub rustc_env: Vec<(String, String)>,
296     // Environment settings to use during execution
297     pub exec_env: Vec<(String, String)>,
298     // Lines to check if they appear in the expected debugger output
299     pub check_lines: Vec<String>,
300     // Build documentation for all specified aux-builds as well
301     pub build_aux_docs: bool,
302     // Flag to force a crate to be built with the host architecture
303     pub force_host: bool,
304     // Check stdout for error-pattern output as well as stderr
305     pub check_stdout: bool,
306     // For UI tests, allows compiler to generate arbitrary output to stdout
307     pub dont_check_compiler_stdout: bool,
308     // For UI tests, allows compiler to generate arbitrary output to stderr
309     pub dont_check_compiler_stderr: bool,
310     // Don't force a --crate-type=dylib flag on the command line
311     pub no_prefer_dynamic: bool,
312     // Run --pretty expanded when running pretty printing tests
313     pub pretty_expanded: bool,
314     // Which pretty mode are we testing with, default to 'normal'
315     pub pretty_mode: String,
316     // Only compare pretty output and don't try compiling
317     pub pretty_compare_only: bool,
318     // Patterns which must not appear in the output of a cfail test.
319     pub forbid_output: Vec<String>,
320     // Revisions to test for incremental compilation.
321     pub revisions: Vec<String>,
322     // Directory (if any) to use for incremental compilation.  This is
323     // not set by end-users; rather it is set by the incremental
324     // testing harness and used when generating compilation
325     // arguments. (In particular, it propagates to the aux-builds.)
326     pub incremental_dir: Option<PathBuf>,
327     // Specifies that a test must actually compile without errors.
328     pub compile_pass: bool,
329     // rustdoc will test the output of the `--test` option
330     pub check_test_line_numbers_match: bool,
331     // The test must be compiled and run successfully. Only used in UI tests for now.
332     pub run_pass: bool,
333     // Skip any codegen step and running the executable. Only for run-pass.
334     pub skip_codegen: bool,
335     // Do not pass `-Z ui-testing` to UI tests
336     pub disable_ui_testing_normalization: bool,
337     // customized normalization rules
338     pub normalize_stdout: Vec<(String, String)>,
339     pub normalize_stderr: Vec<(String, String)>,
340     pub failure_status: i32,
341     pub run_rustfix: bool,
342     pub rustfix_only_machine_applicable: bool,
343 }
344
345 impl TestProps {
346     pub fn new() -> Self {
347         TestProps {
348             error_patterns: vec![],
349             compile_flags: vec![],
350             run_flags: None,
351             pp_exact: None,
352             aux_builds: vec![],
353             revisions: vec![],
354             rustc_env: vec![],
355             exec_env: vec![],
356             check_lines: vec![],
357             build_aux_docs: false,
358             force_host: false,
359             check_stdout: false,
360             dont_check_compiler_stdout: false,
361             dont_check_compiler_stderr: false,
362             no_prefer_dynamic: false,
363             pretty_expanded: false,
364             pretty_mode: "normal".to_string(),
365             pretty_compare_only: false,
366             forbid_output: vec![],
367             incremental_dir: None,
368             compile_pass: false,
369             check_test_line_numbers_match: false,
370             run_pass: false,
371             skip_codegen: false,
372             disable_ui_testing_normalization: false,
373             normalize_stdout: vec![],
374             normalize_stderr: vec![],
375             failure_status: -1,
376             run_rustfix: false,
377             rustfix_only_machine_applicable: false,
378         }
379     }
380
381     pub fn from_aux_file(&self, testfile: &Path, cfg: Option<&str>, config: &Config) -> Self {
382         let mut props = TestProps::new();
383
384         // copy over select properties to the aux build:
385         props.incremental_dir = self.incremental_dir.clone();
386         props.load_from(testfile, cfg, config);
387
388         props
389     }
390
391     pub fn from_file(testfile: &Path, cfg: Option<&str>, config: &Config) -> Self {
392         let mut props = TestProps::new();
393         props.load_from(testfile, cfg, config);
394         props
395     }
396
397     /// Load properties from `testfile` into `props`. If a property is
398     /// tied to a particular revision `foo` (indicated by writing
399     /// `//[foo]`), then the property is ignored unless `cfg` is
400     /// `Some("foo")`.
401     fn load_from(&mut self, testfile: &Path, cfg: Option<&str>, config: &Config) {
402         iter_header(testfile, cfg, &mut |ln| {
403             if let Some(ep) = config.parse_error_pattern(ln) {
404                 self.error_patterns.push(ep);
405             }
406
407             if let Some(flags) = config.parse_compile_flags(ln) {
408                 self.compile_flags
409                     .extend(flags.split_whitespace().map(|s| s.to_owned()));
410             }
411
412             if let Some(edition) = config.parse_edition(ln) {
413                 self.compile_flags.push(format!("--edition={}", edition));
414             }
415
416             if let Some(r) = config.parse_revisions(ln) {
417                 self.revisions.extend(r);
418             }
419
420             if self.run_flags.is_none() {
421                 self.run_flags = config.parse_run_flags(ln);
422             }
423
424             if self.pp_exact.is_none() {
425                 self.pp_exact = config.parse_pp_exact(ln, testfile);
426             }
427
428             if !self.build_aux_docs {
429                 self.build_aux_docs = config.parse_build_aux_docs(ln);
430             }
431
432             if !self.force_host {
433                 self.force_host = config.parse_force_host(ln);
434             }
435
436             if !self.check_stdout {
437                 self.check_stdout = config.parse_check_stdout(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(ee) = config.parse_env(ln, "exec-env") {
469                 self.exec_env.push(ee);
470             }
471
472             if let Some(ee) = config.parse_env(ln, "rustc-env") {
473                 self.rustc_env.push(ee);
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 = config.parse_check_test_line_numbers_match(ln);
486             }
487
488             if !self.run_pass {
489                 self.run_pass = config.parse_run_pass(ln);
490             }
491
492             if !self.compile_pass {
493                 // run-pass implies must_compile_successfully
494                 self.compile_pass = config.parse_compile_pass(ln) || self.run_pass;
495             }
496
497             if !self.skip_codegen {
498                 self.skip_codegen = config.parse_skip_codegen(ln);
499             }
500
501             if !self.disable_ui_testing_normalization {
502                 self.disable_ui_testing_normalization =
503                     config.parse_disable_ui_testing_normalization(ln);
504             }
505
506             if let Some(rule) = config.parse_custom_normalization(ln, "normalize-stdout") {
507                 self.normalize_stdout.push(rule);
508             }
509             if let Some(rule) = config.parse_custom_normalization(ln, "normalize-stderr") {
510                 self.normalize_stderr.push(rule);
511             }
512
513             if let Some(code) = config.parse_failure_status(ln) {
514                 self.failure_status = code;
515             }
516
517             if !self.run_rustfix {
518                 self.run_rustfix = config.parse_run_rustfix(ln);
519             }
520
521             if !self.rustfix_only_machine_applicable {
522                 self.rustfix_only_machine_applicable =
523                     config.parse_rustfix_only_machine_applicable(ln);
524             }
525         });
526
527         if self.failure_status == -1 {
528             self.failure_status = match config.mode {
529                 Mode::RunFail => 101,
530                 _ => 1,
531             };
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
544 fn iter_header(testfile: &Path, cfg: Option<&str>, it: &mut dyn FnMut(&str)) {
545     if testfile.is_dir() {
546         return;
547     }
548
549     let comment = if testfile.to_string_lossy().ends_with(".rs") {
550         "//"
551     } else {
552         "#"
553     };
554
555     let comment_with_brace = comment.to_string() + "[";
556
557     let rdr = BufReader::new(File::open(testfile).unwrap());
558     for ln in rdr.lines() {
559         // Assume that any directives will be found before the first
560         // module or function. This doesn't seem to be an optimization
561         // with a warm page cache. Maybe with a cold one.
562         let ln = ln.unwrap();
563         let ln = ln.trim();
564         if ln.starts_with("fn") || ln.starts_with("mod") {
565             return;
566         } else if ln.starts_with(&comment_with_brace) {
567             // A comment like `//[foo]` is specific to revision `foo`
568             if let Some(close_brace) = ln.find(']') {
569                 let open_brace = ln.find('[').unwrap();
570                 let lncfg = &ln[open_brace + 1 .. close_brace];
571                 let matches = match cfg {
572                     Some(s) => s == &lncfg[..],
573                     None => false,
574                 };
575                 if matches {
576                     it(ln[(close_brace + 1)..].trim_left());
577                 }
578             } else {
579                 panic!("malformed condition directive: expected `{}foo]`, found `{}`",
580                         comment_with_brace, ln)
581             }
582         } else if ln.starts_with(comment) {
583             it(ln[comment.len() ..].trim_left());
584         }
585     }
586     return;
587 }
588
589 impl Config {
590     fn parse_error_pattern(&self, line: &str) -> Option<String> {
591         self.parse_name_value_directive(line, "error-pattern")
592     }
593
594     fn parse_forbid_output(&self, line: &str) -> Option<String> {
595         self.parse_name_value_directive(line, "forbid-output")
596     }
597
598     fn parse_aux_build(&self, line: &str) -> Option<String> {
599         self.parse_name_value_directive(line, "aux-build")
600     }
601
602     fn parse_compile_flags(&self, line: &str) -> Option<String> {
603         self.parse_name_value_directive(line, "compile-flags")
604     }
605
606     fn parse_revisions(&self, line: &str) -> Option<Vec<String>> {
607         self.parse_name_value_directive(line, "revisions")
608             .map(|r| r.split_whitespace().map(|t| t.to_string()).collect())
609     }
610
611     fn parse_run_flags(&self, line: &str) -> Option<String> {
612         self.parse_name_value_directive(line, "run-flags")
613     }
614
615     fn parse_check_line(&self, line: &str) -> Option<String> {
616         self.parse_name_value_directive(line, "check")
617     }
618
619     fn parse_force_host(&self, line: &str) -> bool {
620         self.parse_name_directive(line, "force-host")
621     }
622
623     fn parse_build_aux_docs(&self, line: &str) -> bool {
624         self.parse_name_directive(line, "build-aux-docs")
625     }
626
627     fn parse_check_stdout(&self, line: &str) -> bool {
628         self.parse_name_directive(line, "check-stdout")
629     }
630
631     fn parse_dont_check_compiler_stdout(&self, line: &str) -> bool {
632         self.parse_name_directive(line, "dont-check-compiler-stdout")
633     }
634
635     fn parse_dont_check_compiler_stderr(&self, line: &str) -> bool {
636         self.parse_name_directive(line, "dont-check-compiler-stderr")
637     }
638
639     fn parse_no_prefer_dynamic(&self, line: &str) -> bool {
640         self.parse_name_directive(line, "no-prefer-dynamic")
641     }
642
643     fn parse_pretty_expanded(&self, line: &str) -> bool {
644         self.parse_name_directive(line, "pretty-expanded")
645     }
646
647     fn parse_pretty_mode(&self, line: &str) -> Option<String> {
648         self.parse_name_value_directive(line, "pretty-mode")
649     }
650
651     fn parse_pretty_compare_only(&self, line: &str) -> bool {
652         self.parse_name_directive(line, "pretty-compare-only")
653     }
654
655     fn parse_failure_status(&self, line: &str) -> Option<i32> {
656         match self.parse_name_value_directive(line, "failure-status") {
657             Some(code) => code.trim().parse::<i32>().ok(),
658             _ => None,
659         }
660     }
661
662     fn parse_compile_pass(&self, line: &str) -> bool {
663         self.parse_name_directive(line, "compile-pass")
664     }
665
666     fn parse_disable_ui_testing_normalization(&self, line: &str) -> bool {
667         self.parse_name_directive(line, "disable-ui-testing-normalization")
668     }
669
670     fn parse_check_test_line_numbers_match(&self, line: &str) -> bool {
671         self.parse_name_directive(line, "check-test-line-numbers-match")
672     }
673
674     fn parse_run_pass(&self, line: &str) -> bool {
675         self.parse_name_directive(line, "run-pass")
676     }
677
678     fn parse_skip_codegen(&self, line: &str) -> bool {
679         self.parse_name_directive(line, "skip-codegen")
680     }
681
682     fn parse_env(&self, line: &str, name: &str) -> Option<(String, String)> {
683         self.parse_name_value_directive(line, name).map(|nv| {
684             // nv is either FOO or FOO=BAR
685             let mut strs: Vec<String> = nv.splitn(2, '=').map(str::to_owned).collect();
686
687             match strs.len() {
688                 1 => (strs.pop().unwrap(), String::new()),
689                 2 => {
690                     let end = strs.pop().unwrap();
691                     (strs.pop().unwrap(), end)
692                 }
693                 n => panic!("Expected 1 or 2 strings, not {}", n),
694             }
695         })
696     }
697
698     fn parse_pp_exact(&self, line: &str, testfile: &Path) -> Option<PathBuf> {
699         if let Some(s) = self.parse_name_value_directive(line, "pp-exact") {
700             Some(PathBuf::from(&s))
701         } else if self.parse_name_directive(line, "pp-exact") {
702             testfile.file_name().map(PathBuf::from)
703         } else {
704             None
705         }
706     }
707
708     fn parse_custom_normalization(&self, mut line: &str, prefix: &str) -> Option<(String, String)> {
709         if self.parse_cfg_name_directive(line, prefix) == ParsedNameDirective::Match {
710             let from = parse_normalization_string(&mut line)?;
711             let to = parse_normalization_string(&mut line)?;
712             Some((from, to))
713         } else {
714             None
715         }
716     }
717
718     /// Parses a name-value directive which contains config-specific information, e.g. `ignore-x86`
719     /// or `normalize-stderr-32bit`.
720     fn parse_cfg_name_directive(&self, line: &str, prefix: &str) -> ParsedNameDirective {
721         if line.starts_with(prefix) && line.as_bytes().get(prefix.len()) == Some(&b'-') {
722             let name = line[prefix.len() + 1..]
723                 .split(&[':', ' '][..])
724                 .next()
725                 .unwrap();
726
727             if name == "test" ||
728                 util::matches_os(&self.target, name) ||             // target
729                 name == util::get_arch(&self.target) ||             // architecture
730                 name == util::get_pointer_width(&self.target) ||    // pointer width
731                 name == self.stage_id.split('-').next().unwrap() || // stage
732                 Some(name) == util::get_env(&self.target) ||        // env
733                 (self.target != self.host && name == "cross-compile") ||
734                 match self.compare_mode {
735                     Some(CompareMode::Nll) => name == "compare-mode-nll",
736                     Some(CompareMode::Polonius) => name == "compare-mode-polonius",
737                     None => false,
738                 } ||
739                 (cfg!(debug_assertions) && name == "debug") {
740                 ParsedNameDirective::Match
741             } else {
742                 match self.mode {
743                     common::DebugInfoBoth => {
744                         if name == "gdb" {
745                             ParsedNameDirective::MatchGdb
746                         } else if name == "lldb" {
747                             ParsedNameDirective::MatchLldb
748                         } else {
749                             ParsedNameDirective::NoMatch
750                         }
751                     },
752                     common::DebugInfoGdb => if name == "gdb" {
753                         ParsedNameDirective::Match
754                     } else {
755                         ParsedNameDirective::NoMatch
756                     },
757                     common::DebugInfoLldb => if name == "lldb" {
758                         ParsedNameDirective::Match
759                     } else {
760                         ParsedNameDirective::NoMatch
761                     },
762                     common::Pretty => if name == "pretty" {
763                         ParsedNameDirective::Match
764                     } else {
765                         ParsedNameDirective::NoMatch
766                     },
767                     _ => ParsedNameDirective::NoMatch,
768                 }
769             }
770         } else {
771             ParsedNameDirective::NoMatch
772         }
773     }
774
775     fn has_cfg_prefix(&self, line: &str, prefix: &str) -> bool {
776         // returns whether this line contains this prefix or not. For prefix
777         // "ignore", returns true if line says "ignore-x86_64", "ignore-arch",
778         // "ignore-android" etc.
779         line.starts_with(prefix) && line.as_bytes().get(prefix.len()) == Some(&b'-')
780     }
781
782     fn parse_name_directive(&self, line: &str, directive: &str) -> bool {
783         // Ensure the directive is a whole word. Do not match "ignore-x86" when
784         // the line says "ignore-x86_64".
785         line.starts_with(directive) && match line.as_bytes().get(directive.len()) {
786             None | Some(&b' ') | Some(&b':') => true,
787             _ => false,
788         }
789     }
790
791     pub fn parse_name_value_directive(&self, line: &str, directive: &str) -> Option<String> {
792         let colon = directive.len();
793         if line.starts_with(directive) && line.as_bytes().get(colon) == Some(&b':') {
794             let value = line[(colon + 1)..].to_owned();
795             debug!("{}: {}", directive, value);
796             Some(expand_variables(value, self))
797         } else {
798             None
799         }
800     }
801
802     pub fn find_rust_src_root(&self) -> Option<PathBuf> {
803         let mut path = self.src_base.clone();
804         let path_postfix = Path::new("src/etc/lldb_batchmode.py");
805
806         while path.pop() {
807             if path.join(&path_postfix).is_file() {
808                 return Some(path);
809             }
810         }
811
812         None
813     }
814
815     fn parse_run_rustfix(&self, line: &str) -> bool {
816         self.parse_name_directive(line, "run-rustfix")
817     }
818
819     fn parse_rustfix_only_machine_applicable(&self, line: &str) -> bool {
820         self.parse_name_directive(line, "rustfix-only-machine-applicable")
821     }
822
823     fn parse_edition(&self, line: &str) -> Option<String> {
824         self.parse_name_value_directive(line, "edition")
825     }
826 }
827
828 pub fn lldb_version_to_int(version_string: &str) -> isize {
829     let error_string = format!(
830         "Encountered LLDB version string with unexpected format: {}",
831         version_string
832     );
833     version_string.parse().expect(&error_string)
834 }
835
836 fn expand_variables(mut value: String, config: &Config) -> String {
837     const CWD: &'static str = "{{cwd}}";
838     const SRC_BASE: &'static str = "{{src-base}}";
839     const BUILD_BASE: &'static str = "{{build-base}}";
840
841     if value.contains(CWD) {
842         let cwd = env::current_dir().unwrap();
843         value = value.replace(CWD, &cwd.to_string_lossy());
844     }
845
846     if value.contains(SRC_BASE) {
847         value = value.replace(SRC_BASE, &config.src_base.to_string_lossy());
848     }
849
850     if value.contains(BUILD_BASE) {
851         value = value.replace(BUILD_BASE, &config.build_base.to_string_lossy());
852     }
853
854     value
855 }
856
857 /// Finds the next quoted string `"..."` in `line`, and extract the content from it. Move the `line`
858 /// variable after the end of the quoted string.
859 ///
860 /// # Examples
861 ///
862 /// ```
863 /// let mut s = "normalize-stderr-32bit: \"something (32 bits)\" -> \"something ($WORD bits)\".";
864 /// let first = parse_normalization_string(&mut s);
865 /// assert_eq!(first, Some("something (32 bits)".to_owned()));
866 /// assert_eq!(s, " -> \"something ($WORD bits)\".");
867 /// ```
868 fn parse_normalization_string(line: &mut &str) -> Option<String> {
869     // FIXME support escapes in strings.
870     let begin = line.find('"')? + 1;
871     let end = line[begin..].find('"')? + begin;
872     let result = line[begin..end].to_owned();
873     *line = &line[end + 1..];
874     Some(result)
875 }