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