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