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