]> git.lizzy.rs Git - rust.git/blob - src/tools/compiletest/src/common.rs
Auto merge of #102458 - JohnTitor:stabilize-instruction-set, r=oli-obk
[rust.git] / src / tools / compiletest / src / common.rs
1 pub use self::Mode::*;
2
3 use std::ffi::OsString;
4 use std::fmt;
5 use std::iter;
6 use std::path::{Path, PathBuf};
7 use std::process::Command;
8 use std::str::FromStr;
9
10 use crate::util::{add_dylib_path, PathBufExt};
11 use lazycell::LazyCell;
12 use test::ColorConfig;
13
14 #[derive(Clone, Copy, PartialEq, Debug)]
15 pub enum Mode {
16     RunPassValgrind,
17     Pretty,
18     DebugInfo,
19     Codegen,
20     Rustdoc,
21     RustdocJson,
22     CodegenUnits,
23     Incremental,
24     RunMake,
25     Ui,
26     JsDocTest,
27     MirOpt,
28     Assembly,
29 }
30
31 impl Mode {
32     pub fn disambiguator(self) -> &'static str {
33         // Pretty-printing tests could run concurrently, and if they do,
34         // they need to keep their output segregated.
35         match self {
36             Pretty => ".pretty",
37             _ => "",
38         }
39     }
40 }
41
42 impl FromStr for Mode {
43     type Err = ();
44     fn from_str(s: &str) -> Result<Mode, ()> {
45         match s {
46             "run-pass-valgrind" => Ok(RunPassValgrind),
47             "pretty" => Ok(Pretty),
48             "debuginfo" => Ok(DebugInfo),
49             "codegen" => Ok(Codegen),
50             "rustdoc" => Ok(Rustdoc),
51             "rustdoc-json" => Ok(RustdocJson),
52             "codegen-units" => Ok(CodegenUnits),
53             "incremental" => Ok(Incremental),
54             "run-make" => Ok(RunMake),
55             "ui" => Ok(Ui),
56             "js-doc-test" => Ok(JsDocTest),
57             "mir-opt" => Ok(MirOpt),
58             "assembly" => Ok(Assembly),
59             _ => Err(()),
60         }
61     }
62 }
63
64 impl fmt::Display for Mode {
65     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
66         let s = match *self {
67             RunPassValgrind => "run-pass-valgrind",
68             Pretty => "pretty",
69             DebugInfo => "debuginfo",
70             Codegen => "codegen",
71             Rustdoc => "rustdoc",
72             RustdocJson => "rustdoc-json",
73             CodegenUnits => "codegen-units",
74             Incremental => "incremental",
75             RunMake => "run-make",
76             Ui => "ui",
77             JsDocTest => "js-doc-test",
78             MirOpt => "mir-opt",
79             Assembly => "assembly",
80         };
81         fmt::Display::fmt(s, f)
82     }
83 }
84
85 #[derive(Clone, Copy, PartialEq, Debug, Hash)]
86 pub enum PassMode {
87     Check,
88     Build,
89     Run,
90 }
91
92 impl FromStr for PassMode {
93     type Err = ();
94     fn from_str(s: &str) -> Result<Self, ()> {
95         match s {
96             "check" => Ok(PassMode::Check),
97             "build" => Ok(PassMode::Build),
98             "run" => Ok(PassMode::Run),
99             _ => Err(()),
100         }
101     }
102 }
103
104 impl fmt::Display for PassMode {
105     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
106         let s = match *self {
107             PassMode::Check => "check",
108             PassMode::Build => "build",
109             PassMode::Run => "run",
110         };
111         fmt::Display::fmt(s, f)
112     }
113 }
114
115 #[derive(Copy, Clone, Debug, PartialEq, PartialOrd)]
116 pub enum FailMode {
117     Check,
118     Build,
119     Run,
120 }
121
122 #[derive(Clone, Debug, PartialEq)]
123 pub enum CompareMode {
124     Polonius,
125     Chalk,
126     SplitDwarf,
127     SplitDwarfSingle,
128 }
129
130 impl CompareMode {
131     pub(crate) fn to_str(&self) -> &'static str {
132         match *self {
133             CompareMode::Polonius => "polonius",
134             CompareMode::Chalk => "chalk",
135             CompareMode::SplitDwarf => "split-dwarf",
136             CompareMode::SplitDwarfSingle => "split-dwarf-single",
137         }
138     }
139
140     pub fn parse(s: String) -> CompareMode {
141         match s.as_str() {
142             "polonius" => CompareMode::Polonius,
143             "chalk" => CompareMode::Chalk,
144             "split-dwarf" => CompareMode::SplitDwarf,
145             "split-dwarf-single" => CompareMode::SplitDwarfSingle,
146             x => panic!("unknown --compare-mode option: {}", x),
147         }
148     }
149 }
150
151 #[derive(Clone, Copy, Debug, PartialEq)]
152 pub enum Debugger {
153     Cdb,
154     Gdb,
155     Lldb,
156 }
157
158 impl Debugger {
159     fn to_str(&self) -> &'static str {
160         match self {
161             Debugger::Cdb => "cdb",
162             Debugger::Gdb => "gdb",
163             Debugger::Lldb => "lldb",
164         }
165     }
166 }
167
168 impl fmt::Display for Debugger {
169     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
170         fmt::Display::fmt(self.to_str(), f)
171     }
172 }
173
174 #[derive(Clone, Copy, Debug, PartialEq)]
175 pub enum PanicStrategy {
176     Unwind,
177     Abort,
178 }
179
180 /// Configuration for compiletest
181 #[derive(Debug, Clone)]
182 pub struct Config {
183     /// `true` to overwrite stderr/stdout files instead of complaining about changes in output.
184     pub bless: bool,
185
186     /// The library paths required for running the compiler.
187     pub compile_lib_path: PathBuf,
188
189     /// The library paths required for running compiled programs.
190     pub run_lib_path: PathBuf,
191
192     /// The rustc executable.
193     pub rustc_path: PathBuf,
194
195     /// The rustdoc executable.
196     pub rustdoc_path: Option<PathBuf>,
197
198     /// The rust-demangler executable.
199     pub rust_demangler_path: Option<PathBuf>,
200
201     /// The Python executable to use for LLDB and htmldocck.
202     pub python: String,
203
204     /// The jsondocck executable.
205     pub jsondocck_path: Option<String>,
206
207     /// The jsondoclint executable.
208     pub jsondoclint_path: Option<String>,
209
210     /// The LLVM `FileCheck` binary path.
211     pub llvm_filecheck: Option<PathBuf>,
212
213     /// Path to LLVM's bin directory.
214     pub llvm_bin_dir: Option<PathBuf>,
215
216     /// The valgrind path.
217     pub valgrind_path: Option<String>,
218
219     /// Whether to fail if we can't run run-pass-valgrind tests under valgrind
220     /// (or, alternatively, to silently run them like regular run-pass tests).
221     pub force_valgrind: bool,
222
223     /// The path to the Clang executable to run Clang-based tests with. If
224     /// `None` then these tests will be ignored.
225     pub run_clang_based_tests_with: Option<String>,
226
227     /// The directory containing the tests to run
228     pub src_base: PathBuf,
229
230     /// The directory where programs should be built
231     pub build_base: PathBuf,
232
233     /// The name of the stage being built (stage1, etc)
234     pub stage_id: String,
235
236     /// The test mode, e.g. ui or debuginfo.
237     pub mode: Mode,
238
239     /// The test suite (essentially which directory is running, but without the
240     /// directory prefix such as src/test)
241     pub suite: String,
242
243     /// The debugger to use in debuginfo mode. Unset otherwise.
244     pub debugger: Option<Debugger>,
245
246     /// Run ignored tests
247     pub run_ignored: bool,
248
249     /// Only run tests that match these filters
250     pub filters: Vec<String>,
251
252     /// Skip tests tests matching these substrings. Corresponds to
253     /// `test::TestOpts::skip`. `filter_exact` does not apply to these flags.
254     pub skip: Vec<String>,
255
256     /// Exactly match the filter, rather than a substring
257     pub filter_exact: bool,
258
259     /// Force the pass mode of a check/build/run-pass test to this mode.
260     pub force_pass_mode: Option<PassMode>,
261
262     /// Explicitly enable or disable running.
263     pub run: Option<bool>,
264
265     /// Write out a parseable log of tests that were run
266     pub logfile: Option<PathBuf>,
267
268     /// A command line to prefix program execution with,
269     /// for running under valgrind
270     pub runtool: Option<String>,
271
272     /// Flags to pass to the compiler when building for the host
273     pub host_rustcflags: Vec<String>,
274
275     /// Flags to pass to the compiler when building for the target
276     pub target_rustcflags: Vec<String>,
277
278     /// Whether tests should be optimized by default. Individual test-suites and test files may
279     /// override this setting.
280     pub optimize_tests: bool,
281
282     /// Target system to be tested
283     pub target: String,
284
285     /// Host triple for the compiler being invoked
286     pub host: String,
287
288     /// Path to / name of the Microsoft Console Debugger (CDB) executable
289     pub cdb: Option<OsString>,
290
291     /// Version of CDB
292     pub cdb_version: Option<[u16; 4]>,
293
294     /// Path to / name of the GDB executable
295     pub gdb: Option<String>,
296
297     /// Version of GDB, encoded as ((major * 1000) + minor) * 1000 + patch
298     pub gdb_version: Option<u32>,
299
300     /// Whether GDB has native rust support
301     pub gdb_native_rust: bool,
302
303     /// Version of LLDB
304     pub lldb_version: Option<u32>,
305
306     /// Whether LLDB has native rust support
307     pub lldb_native_rust: bool,
308
309     /// Version of LLVM
310     pub llvm_version: Option<u32>,
311
312     /// Is LLVM a system LLVM
313     pub system_llvm: bool,
314
315     /// Path to the android tools
316     pub android_cross_path: PathBuf,
317
318     /// Extra parameter to run adb on arm-linux-androideabi
319     pub adb_path: String,
320
321     /// Extra parameter to run test suite on arm-linux-androideabi
322     pub adb_test_dir: String,
323
324     /// status whether android device available or not
325     pub adb_device_status: bool,
326
327     /// the path containing LLDB's Python module
328     pub lldb_python_dir: Option<String>,
329
330     /// Explain what's going on
331     pub verbose: bool,
332
333     /// Print one character per test instead of one line
334     pub quiet: bool,
335
336     /// Whether to use colors in test.
337     pub color: ColorConfig,
338
339     /// where to find the remote test client process, if we're using it
340     pub remote_test_client: Option<PathBuf>,
341
342     /// mode describing what file the actual ui output will be compared to
343     pub compare_mode: Option<CompareMode>,
344
345     /// If true, this will generate a coverage file with UI test files that run `MachineApplicable`
346     /// diagnostics but are missing `run-rustfix` annotations. The generated coverage file is
347     /// created in `/<build_base>/rustfix_missing_coverage.txt`
348     pub rustfix_coverage: bool,
349
350     /// whether to run `tidy` when a rustdoc test fails
351     pub has_tidy: bool,
352
353     /// The current Rust channel
354     pub channel: String,
355
356     /// The default Rust edition
357     pub edition: Option<String>,
358
359     // Configuration for various run-make tests frobbing things like C compilers
360     // or querying about various LLVM component information.
361     pub cc: String,
362     pub cxx: String,
363     pub cflags: String,
364     pub cxxflags: String,
365     pub ar: String,
366     pub linker: Option<String>,
367     pub llvm_components: String,
368
369     /// Path to a NodeJS executable. Used for JS doctests, emscripten and WASM tests
370     pub nodejs: Option<String>,
371     /// Path to a npm executable. Used for rustdoc GUI tests
372     pub npm: Option<String>,
373
374     /// Whether to rerun tests even if the inputs are unchanged.
375     pub force_rerun: bool,
376
377     pub target_cfg: LazyCell<TargetCfg>,
378 }
379
380 impl Config {
381     pub fn run_enabled(&self) -> bool {
382         self.run.unwrap_or_else(|| {
383             // Auto-detect whether to run based on the platform.
384             !self.target.ends_with("-fuchsia")
385         })
386     }
387
388     fn target_cfg(&self) -> &TargetCfg {
389         self.target_cfg.borrow_with(|| TargetCfg::new(self))
390     }
391
392     pub fn matches_arch(&self, arch: &str) -> bool {
393         self.target_cfg().arch == arch ||
394         // Shorthand for convenience. The arch for
395         // asmjs-unknown-emscripten is actually wasm32.
396         (arch == "asmjs" && self.target.starts_with("asmjs")) ||
397         // Matching all the thumb variants as one can be convenient.
398         // (thumbv6m, thumbv7em, thumbv7m, etc.)
399         (arch == "thumb" && self.target.starts_with("thumb"))
400     }
401
402     pub fn matches_os(&self, os: &str) -> bool {
403         self.target_cfg().os == os
404     }
405
406     pub fn matches_env(&self, env: &str) -> bool {
407         self.target_cfg().env == env
408     }
409
410     pub fn matches_abi(&self, abi: &str) -> bool {
411         self.target_cfg().abi == abi
412     }
413
414     pub fn matches_family(&self, family: &str) -> bool {
415         self.target_cfg().families.iter().any(|f| f == family)
416     }
417
418     pub fn is_big_endian(&self) -> bool {
419         self.target_cfg().endian == Endian::Big
420     }
421
422     pub fn get_pointer_width(&self) -> u32 {
423         *&self.target_cfg().pointer_width
424     }
425
426     pub fn can_unwind(&self) -> bool {
427         self.target_cfg().panic == PanicStrategy::Unwind
428     }
429
430     pub fn has_asm_support(&self) -> bool {
431         static ASM_SUPPORTED_ARCHS: &[&str] = &[
432             "x86", "x86_64", "arm", "aarch64", "riscv32",
433             "riscv64",
434             // These targets require an additional asm_experimental_arch feature.
435             // "nvptx64", "hexagon", "mips", "mips64", "spirv", "wasm32",
436         ];
437         ASM_SUPPORTED_ARCHS.contains(&self.target_cfg().arch.as_str())
438     }
439 }
440
441 #[derive(Clone, Debug)]
442 pub struct TargetCfg {
443     arch: String,
444     os: String,
445     env: String,
446     abi: String,
447     families: Vec<String>,
448     pointer_width: u32,
449     endian: Endian,
450     panic: PanicStrategy,
451 }
452
453 #[derive(Eq, PartialEq, Clone, Debug)]
454 pub enum Endian {
455     Little,
456     Big,
457 }
458
459 impl TargetCfg {
460     fn new(config: &Config) -> TargetCfg {
461         let mut command = Command::new(&config.rustc_path);
462         add_dylib_path(&mut command, iter::once(&config.compile_lib_path));
463         let output = match command
464             .arg("--print=cfg")
465             .arg("--target")
466             .arg(&config.target)
467             .args(&config.target_rustcflags)
468             .output()
469         {
470             Ok(output) => output,
471             Err(e) => panic!("error: failed to get cfg info from {:?}: {e}", config.rustc_path),
472         };
473         if !output.status.success() {
474             panic!(
475                 "error: failed to get cfg info from {:?}\n--- stdout\n{}\n--- stderr\n{}",
476                 config.rustc_path,
477                 String::from_utf8(output.stdout).unwrap(),
478                 String::from_utf8(output.stderr).unwrap(),
479             );
480         }
481         let print_cfg = String::from_utf8(output.stdout).unwrap();
482         let mut arch = None;
483         let mut os = None;
484         let mut env = None;
485         let mut abi = None;
486         let mut families = Vec::new();
487         let mut pointer_width = None;
488         let mut endian = None;
489         let mut panic = None;
490         for line in print_cfg.lines() {
491             if let Some((name, value)) = line.split_once('=') {
492                 let value = value.trim_matches('"');
493                 match name {
494                     "target_arch" => arch = Some(value),
495                     "target_os" => os = Some(value),
496                     "target_env" => env = Some(value),
497                     "target_abi" => abi = Some(value),
498                     "target_family" => families.push(value.to_string()),
499                     "target_pointer_width" => pointer_width = Some(value.parse().unwrap()),
500                     "target_endian" => {
501                         endian = Some(match value {
502                             "little" => Endian::Little,
503                             "big" => Endian::Big,
504                             s => panic!("unexpected {s}"),
505                         })
506                     }
507                     "panic" => {
508                         panic = match value {
509                             "abort" => Some(PanicStrategy::Abort),
510                             "unwind" => Some(PanicStrategy::Unwind),
511                             s => panic!("unexpected {s}"),
512                         }
513                     }
514                     _ => {}
515                 }
516             }
517         }
518         TargetCfg {
519             arch: arch.unwrap().to_string(),
520             os: os.unwrap().to_string(),
521             env: env.unwrap().to_string(),
522             abi: abi.unwrap().to_string(),
523             families,
524             pointer_width: pointer_width.unwrap(),
525             endian: endian.unwrap(),
526             panic: panic.unwrap(),
527         }
528     }
529 }
530
531 #[derive(Debug, Clone)]
532 pub struct TestPaths {
533     pub file: PathBuf,         // e.g., compile-test/foo/bar/baz.rs
534     pub relative_dir: PathBuf, // e.g., foo/bar
535 }
536
537 /// Used by `ui` tests to generate things like `foo.stderr` from `foo.rs`.
538 pub fn expected_output_path(
539     testpaths: &TestPaths,
540     revision: Option<&str>,
541     compare_mode: &Option<CompareMode>,
542     kind: &str,
543 ) -> PathBuf {
544     assert!(UI_EXTENSIONS.contains(&kind));
545     let mut parts = Vec::new();
546
547     if let Some(x) = revision {
548         parts.push(x);
549     }
550     if let Some(ref x) = *compare_mode {
551         parts.push(x.to_str());
552     }
553     parts.push(kind);
554
555     let extension = parts.join(".");
556     testpaths.file.with_extension(extension)
557 }
558
559 pub const UI_EXTENSIONS: &[&str] = &[
560     UI_STDERR,
561     UI_STDOUT,
562     UI_FIXED,
563     UI_RUN_STDERR,
564     UI_RUN_STDOUT,
565     UI_STDERR_64,
566     UI_STDERR_32,
567     UI_STDERR_16,
568 ];
569 pub const UI_STDERR: &str = "stderr";
570 pub const UI_STDOUT: &str = "stdout";
571 pub const UI_FIXED: &str = "fixed";
572 pub const UI_RUN_STDERR: &str = "run.stderr";
573 pub const UI_RUN_STDOUT: &str = "run.stdout";
574 pub const UI_STDERR_64: &str = "64bit.stderr";
575 pub const UI_STDERR_32: &str = "32bit.stderr";
576 pub const UI_STDERR_16: &str = "16bit.stderr";
577
578 /// Absolute path to the directory where all output for all tests in the given
579 /// `relative_dir` group should reside. Example:
580 ///   /path/to/build/host-triple/test/ui/relative/
581 /// This is created early when tests are collected to avoid race conditions.
582 pub fn output_relative_path(config: &Config, relative_dir: &Path) -> PathBuf {
583     config.build_base.join(relative_dir)
584 }
585
586 /// Generates a unique name for the test, such as `testname.revision.mode`.
587 pub fn output_testname_unique(
588     config: &Config,
589     testpaths: &TestPaths,
590     revision: Option<&str>,
591 ) -> PathBuf {
592     let mode = config.compare_mode.as_ref().map_or("", |m| m.to_str());
593     let debugger = config.debugger.as_ref().map_or("", |m| m.to_str());
594     PathBuf::from(&testpaths.file.file_stem().unwrap())
595         .with_extra_extension(revision.unwrap_or(""))
596         .with_extra_extension(mode)
597         .with_extra_extension(debugger)
598 }
599
600 /// Absolute path to the directory where all output for the given
601 /// test/revision should reside. Example:
602 ///   /path/to/build/host-triple/test/ui/relative/testname.revision.mode/
603 pub fn output_base_dir(config: &Config, testpaths: &TestPaths, revision: Option<&str>) -> PathBuf {
604     output_relative_path(config, &testpaths.relative_dir)
605         .join(output_testname_unique(config, testpaths, revision))
606 }
607
608 /// Absolute path to the base filename used as output for the given
609 /// test/revision. Example:
610 ///   /path/to/build/host-triple/test/ui/relative/testname.revision.mode/testname
611 pub fn output_base_name(config: &Config, testpaths: &TestPaths, revision: Option<&str>) -> PathBuf {
612     output_base_dir(config, testpaths, revision).join(testpaths.file.file_stem().unwrap())
613 }
614
615 /// Absolute path to the directory to use for incremental compilation. Example:
616 ///   /path/to/build/host-triple/test/ui/relative/testname.mode/testname.inc
617 pub fn incremental_dir(config: &Config, testpaths: &TestPaths) -> PathBuf {
618     output_base_name(config, testpaths, None).with_extension("inc")
619 }