]> git.lizzy.rs Git - rust.git/blob - src/tools/compiletest/src/header.rs
Auto merge of #60378 - froydnj:apple-target-modifications, r=michaelwoerister
[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 variables to unset prior to compiling.
309     // Variables are unset before applying 'rustc_env'.
310     pub unset_rustc_env: Vec<String>,
311     // Environment settings to use during execution
312     pub exec_env: Vec<(String, String)>,
313     // Lines to check if they appear in the expected debugger output
314     pub check_lines: Vec<String>,
315     // Build documentation for all specified aux-builds as well
316     pub build_aux_docs: bool,
317     // Flag to force a crate to be built with the host architecture
318     pub force_host: bool,
319     // Check stdout for error-pattern output as well as stderr
320     pub check_stdout: bool,
321     // For UI tests, allows compiler to generate arbitrary output to stdout
322     pub dont_check_compiler_stdout: bool,
323     // For UI tests, allows compiler to generate arbitrary output to stderr
324     pub dont_check_compiler_stderr: bool,
325     // Don't force a --crate-type=dylib flag on the command line
326     //
327     // Set this for example if you have an auxiliary test file that contains
328     // a proc-macro and needs `#![crate_type = "proc-macro"]`. This ensures
329     // that the aux file is compiled as a `proc-macro` and not as a `dylib`.
330     pub no_prefer_dynamic: bool,
331     // Run --pretty expanded when running pretty printing tests
332     pub pretty_expanded: bool,
333     // Which pretty mode are we testing with, default to 'normal'
334     pub pretty_mode: String,
335     // Only compare pretty output and don't try compiling
336     pub pretty_compare_only: bool,
337     // Patterns which must not appear in the output of a cfail test.
338     pub forbid_output: Vec<String>,
339     // Revisions to test for incremental compilation.
340     pub revisions: Vec<String>,
341     // Directory (if any) to use for incremental compilation.  This is
342     // not set by end-users; rather it is set by the incremental
343     // testing harness and used when generating compilation
344     // arguments. (In particular, it propagates to the aux-builds.)
345     pub incremental_dir: Option<PathBuf>,
346     // Specifies that a test must actually compile without errors.
347     pub compile_pass: bool,
348     // rustdoc will test the output of the `--test` option
349     pub check_test_line_numbers_match: bool,
350     // The test must be compiled and run successfully. Only used in UI tests for now.
351     pub run_pass: bool,
352     // Skip any codegen step and running the executable. Only for run-pass.
353     pub skip_codegen: bool,
354     // Do not pass `-Z ui-testing` to UI tests
355     pub disable_ui_testing_normalization: bool,
356     // customized normalization rules
357     pub normalize_stdout: Vec<(String, String)>,
358     pub normalize_stderr: Vec<(String, String)>,
359     pub failure_status: i32,
360     // Whether or not `rustfix` should apply the `CodeSuggestion`s of this test and compile the
361     // resulting Rust code.
362     pub run_rustfix: bool,
363     // If true, `rustfix` will only apply `MachineApplicable` suggestions.
364     pub rustfix_only_machine_applicable: bool,
365     pub assembly_output: Option<String>,
366 }
367
368 impl TestProps {
369     pub fn new() -> Self {
370         TestProps {
371             error_patterns: vec![],
372             compile_flags: vec![],
373             run_flags: None,
374             pp_exact: None,
375             aux_builds: vec![],
376             extern_private: vec![],
377             revisions: vec![],
378             rustc_env: vec![],
379             unset_rustc_env: vec![],
380             exec_env: vec![],
381             check_lines: vec![],
382             build_aux_docs: false,
383             force_host: false,
384             check_stdout: false,
385             dont_check_compiler_stdout: false,
386             dont_check_compiler_stderr: false,
387             no_prefer_dynamic: false,
388             pretty_expanded: false,
389             pretty_mode: "normal".to_string(),
390             pretty_compare_only: false,
391             forbid_output: vec![],
392             incremental_dir: None,
393             compile_pass: false,
394             check_test_line_numbers_match: false,
395             run_pass: false,
396             skip_codegen: false,
397             disable_ui_testing_normalization: false,
398             normalize_stdout: vec![],
399             normalize_stderr: vec![],
400             failure_status: -1,
401             run_rustfix: false,
402             rustfix_only_machine_applicable: false,
403             assembly_output: None,
404         }
405     }
406
407     pub fn from_aux_file(&self, testfile: &Path, cfg: Option<&str>, config: &Config) -> Self {
408         let mut props = TestProps::new();
409
410         // copy over select properties to the aux build:
411         props.incremental_dir = self.incremental_dir.clone();
412         props.load_from(testfile, cfg, config);
413
414         props
415     }
416
417     pub fn from_file(testfile: &Path, cfg: Option<&str>, config: &Config) -> Self {
418         let mut props = TestProps::new();
419         props.load_from(testfile, cfg, config);
420         props
421     }
422
423     /// Loads properties from `testfile` into `props`. If a property is
424     /// tied to a particular revision `foo` (indicated by writing
425     /// `//[foo]`), then the property is ignored unless `cfg` is
426     /// `Some("foo")`.
427     fn load_from(&mut self, testfile: &Path, cfg: Option<&str>, config: &Config) {
428         iter_header(testfile, cfg, &mut |ln| {
429             if let Some(ep) = config.parse_error_pattern(ln) {
430                 self.error_patterns.push(ep);
431             }
432
433             if let Some(flags) = config.parse_compile_flags(ln) {
434                 self.compile_flags
435                     .extend(flags.split_whitespace().map(|s| s.to_owned()));
436             }
437
438             if let Some(edition) = config.parse_edition(ln) {
439                 self.compile_flags.push(format!("--edition={}", edition));
440             }
441
442             if let Some(r) = config.parse_revisions(ln) {
443                 self.revisions.extend(r);
444             }
445
446             if self.run_flags.is_none() {
447                 self.run_flags = config.parse_run_flags(ln);
448             }
449
450             if self.pp_exact.is_none() {
451                 self.pp_exact = config.parse_pp_exact(ln, testfile);
452             }
453
454             if !self.build_aux_docs {
455                 self.build_aux_docs = config.parse_build_aux_docs(ln);
456             }
457
458             if !self.force_host {
459                 self.force_host = config.parse_force_host(ln);
460             }
461
462             if !self.check_stdout {
463                 self.check_stdout = config.parse_check_stdout(ln);
464             }
465
466             if !self.dont_check_compiler_stdout {
467                 self.dont_check_compiler_stdout = config.parse_dont_check_compiler_stdout(ln);
468             }
469
470             if !self.dont_check_compiler_stderr {
471                 self.dont_check_compiler_stderr = config.parse_dont_check_compiler_stderr(ln);
472             }
473
474             if !self.no_prefer_dynamic {
475                 self.no_prefer_dynamic = config.parse_no_prefer_dynamic(ln);
476             }
477
478             if !self.pretty_expanded {
479                 self.pretty_expanded = config.parse_pretty_expanded(ln);
480             }
481
482             if let Some(m) = config.parse_pretty_mode(ln) {
483                 self.pretty_mode = m;
484             }
485
486             if !self.pretty_compare_only {
487                 self.pretty_compare_only = config.parse_pretty_compare_only(ln);
488             }
489
490             if let Some(ab) = config.parse_aux_build(ln) {
491                 self.aux_builds.push(ab);
492             }
493
494             if let Some(ep) = config.parse_extern_private(ln) {
495                 self.extern_private.push(ep);
496             }
497
498             if let Some(ee) = config.parse_env(ln, "exec-env") {
499                 self.exec_env.push(ee);
500             }
501
502             if let Some(ee) = config.parse_env(ln, "rustc-env") {
503                 self.rustc_env.push(ee);
504             }
505
506             if let Some(ev) = config.parse_name_value_directive(ln, "unset-rustc-env") {
507                 self.unset_rustc_env.push(ev);
508             }
509
510             if let Some(cl) = config.parse_check_line(ln) {
511                 self.check_lines.push(cl);
512             }
513
514             if let Some(of) = config.parse_forbid_output(ln) {
515                 self.forbid_output.push(of);
516             }
517
518             if !self.check_test_line_numbers_match {
519                 self.check_test_line_numbers_match = config.parse_check_test_line_numbers_match(ln);
520             }
521
522             if !self.run_pass {
523                 self.run_pass = config.parse_run_pass(ln);
524             }
525
526             if !self.compile_pass {
527                 // run-pass implies compile_pass
528                 self.compile_pass = config.parse_compile_pass(ln) || self.run_pass;
529             }
530
531             if !self.skip_codegen {
532                 self.skip_codegen = config.parse_skip_codegen(ln);
533             }
534
535             if !self.disable_ui_testing_normalization {
536                 self.disable_ui_testing_normalization =
537                     config.parse_disable_ui_testing_normalization(ln);
538             }
539
540             if let Some(rule) = config.parse_custom_normalization(ln, "normalize-stdout") {
541                 self.normalize_stdout.push(rule);
542             }
543             if let Some(rule) = config.parse_custom_normalization(ln, "normalize-stderr") {
544                 self.normalize_stderr.push(rule);
545             }
546
547             if let Some(code) = config.parse_failure_status(ln) {
548                 self.failure_status = code;
549             }
550
551             if !self.run_rustfix {
552                 self.run_rustfix = config.parse_run_rustfix(ln);
553             }
554
555             if !self.rustfix_only_machine_applicable {
556                 self.rustfix_only_machine_applicable =
557                     config.parse_rustfix_only_machine_applicable(ln);
558             }
559
560             if self.assembly_output.is_none() {
561                 self.assembly_output = config.parse_assembly_output(ln);
562             }
563         });
564
565         if self.failure_status == -1 {
566             self.failure_status = match config.mode {
567                 Mode::RunFail => 101,
568                 _ => 1,
569             };
570         }
571
572         for key in &["RUST_TEST_NOCAPTURE", "RUST_TEST_THREADS"] {
573             if let Ok(val) = env::var(key) {
574                 if self.exec_env.iter().find(|&&(ref x, _)| x == key).is_none() {
575                     self.exec_env.push(((*key).to_owned(), val))
576                 }
577             }
578         }
579     }
580 }
581
582 fn iter_header(testfile: &Path, cfg: Option<&str>, it: &mut dyn FnMut(&str)) {
583     if testfile.is_dir() {
584         return;
585     }
586
587     let comment = if testfile.to_string_lossy().ends_with(".rs") {
588         "//"
589     } else {
590         "#"
591     };
592
593     // FIXME: would be nice to allow some whitespace between comment and brace :)
594     // It took me like 2 days to debug why compile-flags weren’t taken into account for my test :)
595     let comment_with_brace = comment.to_string() + "[";
596
597     let rdr = BufReader::new(File::open(testfile).unwrap());
598     for ln in rdr.lines() {
599         // Assume that any directives will be found before the first
600         // module or function. This doesn't seem to be an optimization
601         // with a warm page cache. Maybe with a cold one.
602         let ln = ln.unwrap();
603         let ln = ln.trim();
604         if ln.starts_with("fn") || ln.starts_with("mod") {
605             return;
606         } else if ln.starts_with(&comment_with_brace) {
607             // A comment like `//[foo]` is specific to revision `foo`
608             if let Some(close_brace) = ln.find(']') {
609                 let open_brace = ln.find('[').unwrap();
610                 let lncfg = &ln[open_brace + 1 .. close_brace];
611                 let matches = match cfg {
612                     Some(s) => s == &lncfg[..],
613                     None => false,
614                 };
615                 if matches {
616                     it(ln[(close_brace + 1)..].trim_start());
617                 }
618             } else {
619                 panic!("malformed condition directive: expected `{}foo]`, found `{}`",
620                         comment_with_brace, ln)
621             }
622         } else if ln.starts_with(comment) {
623             it(ln[comment.len() ..].trim_start());
624         }
625     }
626     return;
627 }
628
629 impl Config {
630     fn parse_error_pattern(&self, line: &str) -> Option<String> {
631         self.parse_name_value_directive(line, "error-pattern")
632     }
633
634     fn parse_forbid_output(&self, line: &str) -> Option<String> {
635         self.parse_name_value_directive(line, "forbid-output")
636     }
637
638     fn parse_aux_build(&self, line: &str) -> Option<String> {
639         self.parse_name_value_directive(line, "aux-build")
640             .map(|r| r.trim().to_string())
641     }
642
643     fn parse_extern_private(&self, line: &str) -> Option<String> {
644         self.parse_name_value_directive(line, "extern-private")
645     }
646
647     fn parse_compile_flags(&self, line: &str) -> Option<String> {
648         self.parse_name_value_directive(line, "compile-flags")
649     }
650
651     fn parse_revisions(&self, line: &str) -> Option<Vec<String>> {
652         self.parse_name_value_directive(line, "revisions")
653             .map(|r| r.split_whitespace().map(|t| t.to_string()).collect())
654     }
655
656     fn parse_run_flags(&self, line: &str) -> Option<String> {
657         self.parse_name_value_directive(line, "run-flags")
658     }
659
660     fn parse_check_line(&self, line: &str) -> Option<String> {
661         self.parse_name_value_directive(line, "check")
662     }
663
664     fn parse_force_host(&self, line: &str) -> bool {
665         self.parse_name_directive(line, "force-host")
666     }
667
668     fn parse_build_aux_docs(&self, line: &str) -> bool {
669         self.parse_name_directive(line, "build-aux-docs")
670     }
671
672     fn parse_check_stdout(&self, line: &str) -> bool {
673         self.parse_name_directive(line, "check-stdout")
674     }
675
676     fn parse_dont_check_compiler_stdout(&self, line: &str) -> bool {
677         self.parse_name_directive(line, "dont-check-compiler-stdout")
678     }
679
680     fn parse_dont_check_compiler_stderr(&self, line: &str) -> bool {
681         self.parse_name_directive(line, "dont-check-compiler-stderr")
682     }
683
684     fn parse_no_prefer_dynamic(&self, line: &str) -> bool {
685         self.parse_name_directive(line, "no-prefer-dynamic")
686     }
687
688     fn parse_pretty_expanded(&self, line: &str) -> bool {
689         self.parse_name_directive(line, "pretty-expanded")
690     }
691
692     fn parse_pretty_mode(&self, line: &str) -> Option<String> {
693         self.parse_name_value_directive(line, "pretty-mode")
694     }
695
696     fn parse_pretty_compare_only(&self, line: &str) -> bool {
697         self.parse_name_directive(line, "pretty-compare-only")
698     }
699
700     fn parse_failure_status(&self, line: &str) -> Option<i32> {
701         match self.parse_name_value_directive(line, "failure-status") {
702             Some(code) => code.trim().parse::<i32>().ok(),
703             _ => None,
704         }
705     }
706
707     fn parse_compile_pass(&self, line: &str) -> bool {
708         self.parse_name_directive(line, "compile-pass")
709     }
710
711     fn parse_disable_ui_testing_normalization(&self, line: &str) -> bool {
712         self.parse_name_directive(line, "disable-ui-testing-normalization")
713     }
714
715     fn parse_check_test_line_numbers_match(&self, line: &str) -> bool {
716         self.parse_name_directive(line, "check-test-line-numbers-match")
717     }
718
719     fn parse_run_pass(&self, line: &str) -> bool {
720         self.parse_name_directive(line, "run-pass")
721     }
722
723     fn parse_skip_codegen(&self, line: &str) -> bool {
724         self.parse_name_directive(line, "skip-codegen")
725     }
726
727     fn parse_assembly_output(&self, line: &str) -> Option<String> {
728         self.parse_name_value_directive(line, "assembly-output")
729             .map(|r| r.trim().to_string())
730     }
731
732     fn parse_env(&self, line: &str, name: &str) -> Option<(String, String)> {
733         self.parse_name_value_directive(line, name).map(|nv| {
734             // nv is either FOO or FOO=BAR
735             let mut strs: Vec<String> = nv.splitn(2, '=').map(str::to_owned).collect();
736
737             match strs.len() {
738                 1 => (strs.pop().unwrap(), String::new()),
739                 2 => {
740                     let end = strs.pop().unwrap();
741                     (strs.pop().unwrap(), end)
742                 }
743                 n => panic!("Expected 1 or 2 strings, not {}", n),
744             }
745         })
746     }
747
748     fn parse_pp_exact(&self, line: &str, testfile: &Path) -> Option<PathBuf> {
749         if let Some(s) = self.parse_name_value_directive(line, "pp-exact") {
750             Some(PathBuf::from(&s))
751         } else if self.parse_name_directive(line, "pp-exact") {
752             testfile.file_name().map(PathBuf::from)
753         } else {
754             None
755         }
756     }
757
758     fn parse_custom_normalization(&self, mut line: &str, prefix: &str) -> Option<(String, String)> {
759         if self.parse_cfg_name_directive(line, prefix) == ParsedNameDirective::Match {
760             let from = parse_normalization_string(&mut line)?;
761             let to = parse_normalization_string(&mut line)?;
762             Some((from, to))
763         } else {
764             None
765         }
766     }
767
768     fn parse_needs_matching_clang(&self, line: &str) -> bool {
769         self.parse_name_directive(line, "needs-matching-clang")
770     }
771
772     fn parse_needs_profiler_support(&self, line: &str) -> bool {
773         self.parse_name_directive(line, "needs-profiler-support")
774     }
775
776     fn parse_needs_sanitizer_support(&self, line: &str) -> bool {
777         self.parse_name_directive(line, "needs-sanitizer-support")
778     }
779
780     /// Parses a name-value directive which contains config-specific information, e.g., `ignore-x86`
781     /// or `normalize-stderr-32bit`.
782     fn parse_cfg_name_directive(&self, line: &str, prefix: &str) -> ParsedNameDirective {
783         if line.starts_with(prefix) && line.as_bytes().get(prefix.len()) == Some(&b'-') {
784             let name = line[prefix.len() + 1..]
785                 .split(&[':', ' '][..])
786                 .next()
787                 .unwrap();
788
789             if name == "test" ||
790                 util::matches_os(&self.target, name) ||             // target
791                 name == util::get_arch(&self.target) ||             // architecture
792                 name == util::get_pointer_width(&self.target) ||    // pointer width
793                 name == self.stage_id.split('-').next().unwrap() || // stage
794                 Some(name) == util::get_env(&self.target) ||        // env
795                 (self.target != self.host && name == "cross-compile") ||
796                 match self.compare_mode {
797                     Some(CompareMode::Nll) => name == "compare-mode-nll",
798                     Some(CompareMode::Polonius) => name == "compare-mode-polonius",
799                     None => false,
800                 } ||
801                 (cfg!(debug_assertions) && name == "debug") {
802                 ParsedNameDirective::Match
803             } else {
804                 match self.mode {
805                     common::DebugInfoBoth => {
806                         if name == "gdb" {
807                             ParsedNameDirective::MatchGdb
808                         } else if name == "lldb" {
809                             ParsedNameDirective::MatchLldb
810                         } else {
811                             ParsedNameDirective::NoMatch
812                         }
813                     },
814                     common::DebugInfoGdb => if name == "gdb" {
815                         ParsedNameDirective::Match
816                     } else {
817                         ParsedNameDirective::NoMatch
818                     },
819                     common::DebugInfoLldb => if name == "lldb" {
820                         ParsedNameDirective::Match
821                     } else {
822                         ParsedNameDirective::NoMatch
823                     },
824                     common::Pretty => if name == "pretty" {
825                         ParsedNameDirective::Match
826                     } else {
827                         ParsedNameDirective::NoMatch
828                     },
829                     _ => ParsedNameDirective::NoMatch,
830                 }
831             }
832         } else {
833             ParsedNameDirective::NoMatch
834         }
835     }
836
837     fn has_cfg_prefix(&self, line: &str, prefix: &str) -> bool {
838         // returns whether this line contains this prefix or not. For prefix
839         // "ignore", returns true if line says "ignore-x86_64", "ignore-arch",
840         // "ignore-android" etc.
841         line.starts_with(prefix) && line.as_bytes().get(prefix.len()) == Some(&b'-')
842     }
843
844     fn parse_name_directive(&self, line: &str, directive: &str) -> bool {
845         // Ensure the directive is a whole word. Do not match "ignore-x86" when
846         // the line says "ignore-x86_64".
847         line.starts_with(directive) && match line.as_bytes().get(directive.len()) {
848             None | Some(&b' ') | Some(&b':') => true,
849             _ => false,
850         }
851     }
852
853     pub fn parse_name_value_directive(&self, line: &str, directive: &str) -> Option<String> {
854         let colon = directive.len();
855         if line.starts_with(directive) && line.as_bytes().get(colon) == Some(&b':') {
856             let value = line[(colon + 1)..].to_owned();
857             debug!("{}: {}", directive, value);
858             Some(expand_variables(value, self))
859         } else {
860             None
861         }
862     }
863
864     pub fn find_rust_src_root(&self) -> Option<PathBuf> {
865         let mut path = self.src_base.clone();
866         let path_postfix = Path::new("src/etc/lldb_batchmode.py");
867
868         while path.pop() {
869             if path.join(&path_postfix).is_file() {
870                 return Some(path);
871             }
872         }
873
874         None
875     }
876
877     fn parse_run_rustfix(&self, line: &str) -> bool {
878         self.parse_name_directive(line, "run-rustfix")
879     }
880
881     fn parse_rustfix_only_machine_applicable(&self, line: &str) -> bool {
882         self.parse_name_directive(line, "rustfix-only-machine-applicable")
883     }
884
885     fn parse_edition(&self, line: &str) -> Option<String> {
886         self.parse_name_value_directive(line, "edition")
887     }
888 }
889
890 pub fn lldb_version_to_int(version_string: &str) -> isize {
891     let error_string = format!(
892         "Encountered LLDB version string with unexpected format: {}",
893         version_string
894     );
895     version_string.parse().expect(&error_string)
896 }
897
898 fn expand_variables(mut value: String, config: &Config) -> String {
899     const CWD: &'static str = "{{cwd}}";
900     const SRC_BASE: &'static str = "{{src-base}}";
901     const BUILD_BASE: &'static str = "{{build-base}}";
902
903     if value.contains(CWD) {
904         let cwd = env::current_dir().unwrap();
905         value = value.replace(CWD, &cwd.to_string_lossy());
906     }
907
908     if value.contains(SRC_BASE) {
909         value = value.replace(SRC_BASE, &config.src_base.to_string_lossy());
910     }
911
912     if value.contains(BUILD_BASE) {
913         value = value.replace(BUILD_BASE, &config.build_base.to_string_lossy());
914     }
915
916     value
917 }
918
919 /// Finds the next quoted string `"..."` in `line`, and extract the content from it. Move the `line`
920 /// variable after the end of the quoted string.
921 ///
922 /// # Examples
923 ///
924 /// ```
925 /// let mut s = "normalize-stderr-32bit: \"something (32 bits)\" -> \"something ($WORD bits)\".";
926 /// let first = parse_normalization_string(&mut s);
927 /// assert_eq!(first, Some("something (32 bits)".to_owned()));
928 /// assert_eq!(s, " -> \"something ($WORD bits)\".");
929 /// ```
930 fn parse_normalization_string(line: &mut &str) -> Option<String> {
931     // FIXME support escapes in strings.
932     let begin = line.find('"')? + 1;
933     let end = line[begin..].find('"')? + begin;
934     let result = line[begin..end].to_owned();
935     *line = &line[end + 1..];
936     Some(result)
937 }
938
939 #[test]
940 fn test_parse_normalization_string() {
941     let mut s = "normalize-stderr-32bit: \"something (32 bits)\" -> \"something ($WORD bits)\".";
942     let first = parse_normalization_string(&mut s);
943     assert_eq!(first, Some("something (32 bits)".to_owned()));
944     assert_eq!(s, " -> \"something ($WORD bits)\".");
945
946     // Nothing to normalize (No quotes)
947     let mut s = "normalize-stderr-32bit: something (32 bits) -> something ($WORD bits).";
948     let first = parse_normalization_string(&mut s);
949     assert_eq!(first, None);
950     assert_eq!(s, r#"normalize-stderr-32bit: something (32 bits) -> something ($WORD bits)."#);
951
952     // Nothing to normalize (Only a single quote)
953     let mut s = "normalize-stderr-32bit: \"something (32 bits) -> something ($WORD bits).";
954     let first = parse_normalization_string(&mut s);
955     assert_eq!(first, None);
956     assert_eq!(s, "normalize-stderr-32bit: \"something (32 bits) -> something ($WORD bits).");
957
958     // Nothing to normalize (Three quotes)
959     let mut s = "normalize-stderr-32bit: \"something (32 bits)\" -> \"something ($WORD bits).";
960     let first = parse_normalization_string(&mut s);
961     assert_eq!(first, Some("something (32 bits)".to_owned()));
962     assert_eq!(s, " -> \"something ($WORD bits).");
963 }