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