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