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