]> git.lizzy.rs Git - rust.git/blob - src/tools/clippy/tests/compile-test.rs
Rollup merge of #96768 - m-ou-se:futex-fuchsia, r=tmandry
[rust.git] / src / tools / clippy / tests / compile-test.rs
1 #![feature(test)] // compiletest_rs requires this attribute
2 #![feature(once_cell)]
3 #![feature(is_sorted)]
4 #![cfg_attr(feature = "deny-warnings", deny(warnings))]
5 #![warn(rust_2018_idioms, unused_lifetimes)]
6
7 use compiletest_rs as compiletest;
8 use compiletest_rs::common::Mode as TestMode;
9
10 use std::collections::HashMap;
11 use std::env::{self, remove_var, set_var, var_os};
12 use std::ffi::{OsStr, OsString};
13 use std::fs;
14 use std::io;
15 use std::path::{Path, PathBuf};
16 use std::sync::LazyLock;
17 use test_utils::IS_RUSTC_TEST_SUITE;
18
19 mod test_utils;
20
21 // whether to run internal tests or not
22 const RUN_INTERNAL_TESTS: bool = cfg!(feature = "internal");
23
24 /// All crates used in UI tests are listed here
25 static TEST_DEPENDENCIES: &[&str] = &[
26     "clippy_utils",
27     "derive_new",
28     "futures",
29     "if_chain",
30     "itertools",
31     "quote",
32     "regex",
33     "serde",
34     "serde_derive",
35     "syn",
36     "tokio",
37     "parking_lot",
38     "rustc_semver",
39 ];
40
41 // Test dependencies may need an `extern crate` here to ensure that they show up
42 // in the depinfo file (otherwise cargo thinks they are unused)
43 #[allow(unused_extern_crates)]
44 extern crate clippy_utils;
45 #[allow(unused_extern_crates)]
46 extern crate derive_new;
47 #[allow(unused_extern_crates)]
48 extern crate futures;
49 #[allow(unused_extern_crates)]
50 extern crate if_chain;
51 #[allow(unused_extern_crates)]
52 extern crate itertools;
53 #[allow(unused_extern_crates)]
54 extern crate parking_lot;
55 #[allow(unused_extern_crates)]
56 extern crate quote;
57 #[allow(unused_extern_crates)]
58 extern crate rustc_semver;
59 #[allow(unused_extern_crates)]
60 extern crate syn;
61 #[allow(unused_extern_crates)]
62 extern crate tokio;
63
64 /// Produces a string with an `--extern` flag for all UI test crate
65 /// dependencies.
66 ///
67 /// The dependency files are located by parsing the depinfo file for this test
68 /// module. This assumes the `-Z binary-dep-depinfo` flag is enabled. All test
69 /// dependencies must be added to Cargo.toml at the project root. Test
70 /// dependencies that are not *directly* used by this test module require an
71 /// `extern crate` declaration.
72 static EXTERN_FLAGS: LazyLock<String> = LazyLock::new(|| {
73     let current_exe_depinfo = {
74         let mut path = env::current_exe().unwrap();
75         path.set_extension("d");
76         fs::read_to_string(path).unwrap()
77     };
78     let mut crates: HashMap<&str, &str> = HashMap::with_capacity(TEST_DEPENDENCIES.len());
79     for line in current_exe_depinfo.lines() {
80         // each dependency is expected to have a Makefile rule like `/path/to/crate-hash.rlib:`
81         let parse_name_path = || {
82             if line.starts_with(char::is_whitespace) {
83                 return None;
84             }
85             let path_str = line.strip_suffix(':')?;
86             let path = Path::new(path_str);
87             if !matches!(path.extension()?.to_str()?, "rlib" | "so" | "dylib" | "dll") {
88                 return None;
89             }
90             let (name, _hash) = path.file_stem()?.to_str()?.rsplit_once('-')?;
91             // the "lib" prefix is not present for dll files
92             let name = name.strip_prefix("lib").unwrap_or(name);
93             Some((name, path_str))
94         };
95         if let Some((name, path)) = parse_name_path() {
96             if TEST_DEPENDENCIES.contains(&name) {
97                 // A dependency may be listed twice if it is available in sysroot,
98                 // and the sysroot dependencies are listed first. As of the writing,
99                 // this only seems to apply to if_chain.
100                 crates.insert(name, path);
101             }
102         }
103     }
104     let not_found: Vec<&str> = TEST_DEPENDENCIES
105         .iter()
106         .copied()
107         .filter(|n| !crates.contains_key(n))
108         .collect();
109     assert!(
110         not_found.is_empty(),
111         "dependencies not found in depinfo: {:?}\n\
112         help: Make sure the `-Z binary-dep-depinfo` rust flag is enabled\n\
113         help: Try adding to dev-dependencies in Cargo.toml\n\
114         help: Be sure to also add `extern crate ...;` to tests/compile-test.rs",
115         not_found,
116     );
117     crates
118         .into_iter()
119         .map(|(name, path)| format!(" --extern {}={}", name, path))
120         .collect()
121 });
122
123 fn base_config(test_dir: &str) -> compiletest::Config {
124     let mut config = compiletest::Config {
125         edition: Some("2021".into()),
126         mode: TestMode::Ui,
127         ..compiletest::Config::default()
128     };
129
130     if let Ok(filters) = env::var("TESTNAME") {
131         config.filters = filters.split(',').map(ToString::to_string).collect();
132     }
133
134     if let Some(path) = option_env!("RUSTC_LIB_PATH") {
135         let path = PathBuf::from(path);
136         config.run_lib_path = path.clone();
137         config.compile_lib_path = path;
138     }
139     let current_exe_path = env::current_exe().unwrap();
140     let deps_path = current_exe_path.parent().unwrap();
141     let profile_path = deps_path.parent().unwrap();
142
143     // Using `-L dependency={}` enforces that external dependencies are added with `--extern`.
144     // This is valuable because a) it allows us to monitor what external dependencies are used
145     // and b) it ensures that conflicting rlibs are resolved properly.
146     let host_libs = option_env!("HOST_LIBS")
147         .map(|p| format!(" -L dependency={}", Path::new(p).join("deps").display()))
148         .unwrap_or_default();
149     config.target_rustcflags = Some(format!(
150         "--emit=metadata -Dwarnings -Zui-testing -L dependency={}{}{}",
151         deps_path.display(),
152         host_libs,
153         &*EXTERN_FLAGS,
154     ));
155
156     config.src_base = Path::new("tests").join(test_dir);
157     config.build_base = profile_path.join("test").join(test_dir);
158     config.rustc_path = profile_path.join(if cfg!(windows) {
159         "clippy-driver.exe"
160     } else {
161         "clippy-driver"
162     });
163     config
164 }
165
166 fn run_ui() {
167     let mut config = base_config("ui");
168     config.rustfix_coverage = true;
169     // use tests/clippy.toml
170     let _g = VarGuard::set("CARGO_MANIFEST_DIR", fs::canonicalize("tests").unwrap());
171     let _threads = VarGuard::set(
172         "RUST_TEST_THREADS",
173         // if RUST_TEST_THREADS is set, adhere to it, otherwise override it
174         env::var("RUST_TEST_THREADS").unwrap_or_else(|_| {
175             std::thread::available_parallelism()
176                 .map_or(1, std::num::NonZeroUsize::get)
177                 .to_string()
178         }),
179     );
180     compiletest::run_tests(&config);
181     check_rustfix_coverage();
182 }
183
184 fn run_internal_tests() {
185     // only run internal tests with the internal-tests feature
186     if !RUN_INTERNAL_TESTS {
187         return;
188     }
189     let config = base_config("ui-internal");
190     compiletest::run_tests(&config);
191 }
192
193 fn run_ui_toml() {
194     fn run_tests(config: &compiletest::Config, mut tests: Vec<tester::TestDescAndFn>) -> Result<bool, io::Error> {
195         let mut result = true;
196         let opts = compiletest::test_opts(config);
197         for dir in fs::read_dir(&config.src_base)? {
198             let dir = dir?;
199             if !dir.file_type()?.is_dir() {
200                 continue;
201             }
202             let dir_path = dir.path();
203             let _g = VarGuard::set("CARGO_MANIFEST_DIR", &dir_path);
204             for file in fs::read_dir(&dir_path)? {
205                 let file = file?;
206                 let file_path = file.path();
207                 if file.file_type()?.is_dir() {
208                     continue;
209                 }
210                 if file_path.extension() != Some(OsStr::new("rs")) {
211                     continue;
212                 }
213                 let paths = compiletest::common::TestPaths {
214                     file: file_path,
215                     base: config.src_base.clone(),
216                     relative_dir: dir_path.file_name().unwrap().into(),
217                 };
218                 let test_name = compiletest::make_test_name(config, &paths);
219                 let index = tests
220                     .iter()
221                     .position(|test| test.desc.name == test_name)
222                     .expect("The test should be in there");
223                 result &= tester::run_tests_console(&opts, vec![tests.swap_remove(index)])?;
224             }
225         }
226         Ok(result)
227     }
228
229     let mut config = base_config("ui-toml");
230     config.src_base = config.src_base.canonicalize().unwrap();
231
232     let tests = compiletest::make_tests(&config);
233
234     let res = run_tests(&config, tests);
235     match res {
236         Ok(true) => {},
237         Ok(false) => panic!("Some tests failed"),
238         Err(e) => {
239             panic!("I/O failure during tests: {:?}", e);
240         },
241     }
242 }
243
244 fn run_ui_cargo() {
245     fn run_tests(
246         config: &compiletest::Config,
247         filters: &[String],
248         mut tests: Vec<tester::TestDescAndFn>,
249     ) -> Result<bool, io::Error> {
250         let mut result = true;
251         let opts = compiletest::test_opts(config);
252
253         for dir in fs::read_dir(&config.src_base)? {
254             let dir = dir?;
255             if !dir.file_type()?.is_dir() {
256                 continue;
257             }
258
259             // Use the filter if provided
260             let dir_path = dir.path();
261             for filter in filters {
262                 if !dir_path.ends_with(filter) {
263                     continue;
264                 }
265             }
266
267             for case in fs::read_dir(&dir_path)? {
268                 let case = case?;
269                 if !case.file_type()?.is_dir() {
270                     continue;
271                 }
272
273                 let src_path = case.path().join("src");
274
275                 // When switching between branches, if the previous branch had a test
276                 // that the current branch does not have, the directory is not removed
277                 // because an ignored Cargo.lock file exists.
278                 if !src_path.exists() {
279                     continue;
280                 }
281
282                 env::set_current_dir(&src_path)?;
283                 for file in fs::read_dir(&src_path)? {
284                     let file = file?;
285                     if file.file_type()?.is_dir() {
286                         continue;
287                     }
288
289                     // Search for the main file to avoid running a test for each file in the project
290                     let file_path = file.path();
291                     match file_path.file_name().and_then(OsStr::to_str) {
292                         Some("main.rs") => {},
293                         _ => continue,
294                     }
295                     let _g = VarGuard::set("CLIPPY_CONF_DIR", case.path());
296                     let paths = compiletest::common::TestPaths {
297                         file: file_path,
298                         base: config.src_base.clone(),
299                         relative_dir: src_path.strip_prefix(&config.src_base).unwrap().into(),
300                     };
301                     let test_name = compiletest::make_test_name(config, &paths);
302                     let index = tests
303                         .iter()
304                         .position(|test| test.desc.name == test_name)
305                         .expect("The test should be in there");
306                     result &= tester::run_tests_console(&opts, vec![tests.swap_remove(index)])?;
307                 }
308             }
309         }
310         Ok(result)
311     }
312
313     if IS_RUSTC_TEST_SUITE {
314         return;
315     }
316
317     let mut config = base_config("ui-cargo");
318     config.src_base = config.src_base.canonicalize().unwrap();
319
320     let tests = compiletest::make_tests(&config);
321
322     let current_dir = env::current_dir().unwrap();
323     let res = run_tests(&config, &config.filters, tests);
324     env::set_current_dir(current_dir).unwrap();
325
326     match res {
327         Ok(true) => {},
328         Ok(false) => panic!("Some tests failed"),
329         Err(e) => {
330             panic!("I/O failure during tests: {:?}", e);
331         },
332     }
333 }
334
335 #[test]
336 fn compile_test() {
337     set_var("CLIPPY_DISABLE_DOCS_LINKS", "true");
338     run_ui();
339     run_ui_toml();
340     run_ui_cargo();
341     run_internal_tests();
342 }
343
344 const RUSTFIX_COVERAGE_KNOWN_EXCEPTIONS: &[&str] = &[
345     "assign_ops2.rs",
346     "borrow_deref_ref_unfixable.rs",
347     "cast_size_32bit.rs",
348     "char_lit_as_u8.rs",
349     "cmp_owned/without_suggestion.rs",
350     "dbg_macro.rs",
351     "deref_addrof_double_trigger.rs",
352     "doc/unbalanced_ticks.rs",
353     "eprint_with_newline.rs",
354     "explicit_counter_loop.rs",
355     "iter_skip_next_unfixable.rs",
356     "let_and_return.rs",
357     "literals.rs",
358     "map_flatten.rs",
359     "map_unwrap_or.rs",
360     "match_bool.rs",
361     "mem_replace_macro.rs",
362     "needless_arbitrary_self_type_unfixable.rs",
363     "needless_borrow_pat.rs",
364     "needless_for_each_unfixable.rs",
365     "nonminimal_bool.rs",
366     "print_literal.rs",
367     "print_with_newline.rs",
368     "redundant_static_lifetimes_multiple.rs",
369     "ref_binding_to_reference.rs",
370     "repl_uninit.rs",
371     "result_map_unit_fn_unfixable.rs",
372     "search_is_some.rs",
373     "single_component_path_imports_nested_first.rs",
374     "string_add.rs",
375     "toplevel_ref_arg_non_rustfix.rs",
376     "unit_arg.rs",
377     "unnecessary_clone.rs",
378     "unnecessary_lazy_eval_unfixable.rs",
379     "write_literal.rs",
380     "write_literal_2.rs",
381     "write_with_newline.rs",
382 ];
383
384 fn check_rustfix_coverage() {
385     let missing_coverage_path = Path::new("target/debug/test/ui/rustfix_missing_coverage.txt");
386
387     if let Ok(missing_coverage_contents) = std::fs::read_to_string(missing_coverage_path) {
388         assert!(RUSTFIX_COVERAGE_KNOWN_EXCEPTIONS.iter().is_sorted_by_key(Path::new));
389
390         for rs_path in missing_coverage_contents.lines() {
391             if Path::new(rs_path).starts_with("tests/ui/crashes") {
392                 continue;
393             }
394             let filename = Path::new(rs_path).strip_prefix("tests/ui/").unwrap();
395             assert!(
396                 RUSTFIX_COVERAGE_KNOWN_EXCEPTIONS
397                     .binary_search_by_key(&filename, Path::new)
398                     .is_ok(),
399                 "`{}` runs `MachineApplicable` diagnostics but is missing a `run-rustfix` annotation. \
400                 Please either add `// run-rustfix` at the top of the file or add the file to \
401                 `RUSTFIX_COVERAGE_KNOWN_EXCEPTIONS` in `tests/compile-test.rs`.",
402                 rs_path,
403             );
404         }
405     }
406 }
407
408 #[test]
409 fn rustfix_coverage_known_exceptions_accuracy() {
410     for filename in RUSTFIX_COVERAGE_KNOWN_EXCEPTIONS {
411         let rs_path = Path::new("tests/ui").join(filename);
412         assert!(
413             rs_path.exists(),
414             "`{}` does not exists",
415             rs_path.strip_prefix(env!("CARGO_MANIFEST_DIR")).unwrap().display()
416         );
417         let fixed_path = rs_path.with_extension("fixed");
418         assert!(
419             !fixed_path.exists(),
420             "`{}` exists",
421             fixed_path.strip_prefix(env!("CARGO_MANIFEST_DIR")).unwrap().display()
422         );
423     }
424 }
425
426 /// Restores an env var on drop
427 #[must_use]
428 struct VarGuard {
429     key: &'static str,
430     value: Option<OsString>,
431 }
432
433 impl VarGuard {
434     fn set(key: &'static str, val: impl AsRef<OsStr>) -> Self {
435         let value = var_os(key);
436         set_var(key, val);
437         Self { key, value }
438     }
439 }
440
441 impl Drop for VarGuard {
442     fn drop(&mut self) {
443         match self.value.as_deref() {
444             None => remove_var(self.key),
445             Some(value) => set_var(self.key, value),
446         }
447     }
448 }