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