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