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