• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 #![feature(test)] // compiletest_rs requires this attribute
2 #![feature(lazy_cell)]
3 #![feature(is_sorted)]
4 #![cfg_attr(feature = "deny-warnings", deny(warnings))]
5 #![warn(rust_2018_idioms, unused_lifetimes)]
6 
7 use compiletest::{status_emitter, CommandBuilder};
8 use ui_test as compiletest;
9 use ui_test::Mode as TestMode;
10 
11 use std::env::{self, remove_var, set_var, var_os};
12 use std::ffi::{OsStr, OsString};
13 use std::fs;
14 use std::path::{Path, PathBuf};
15 use test_utils::IS_RUSTC_TEST_SUITE;
16 
17 mod test_utils;
18 
19 // whether to run internal tests or not
20 const RUN_INTERNAL_TESTS: bool = cfg!(feature = "internal");
21 
base_config(test_dir: &str) -> compiletest::Config22 fn base_config(test_dir: &str) -> compiletest::Config {
23     let mut config = compiletest::Config {
24         mode: TestMode::Yolo,
25         stderr_filters: vec![],
26         stdout_filters: vec![],
27         output_conflict_handling: if var_os("BLESS").is_some() || env::args().any(|arg| arg == "--bless") {
28             compiletest::OutputConflictHandling::Bless
29         } else {
30             compiletest::OutputConflictHandling::Error("cargo test -- -- --bless".into())
31         },
32         dependencies_crate_manifest_path: Some("clippy_test_deps/Cargo.toml".into()),
33         target: None,
34         out_dir: PathBuf::from(std::env::var_os("CARGO_TARGET_DIR").unwrap_or("target".into())).join("ui_test"),
35         ..compiletest::Config::rustc(Path::new("tests").join(test_dir))
36     };
37 
38     if let Some(_path) = option_env!("RUSTC_LIB_PATH") {
39         //let path = PathBuf::from(path);
40         //config.run_lib_path = path.clone();
41         //config.compile_lib_path = path;
42     }
43     let current_exe_path = env::current_exe().unwrap();
44     let deps_path = current_exe_path.parent().unwrap();
45     let profile_path = deps_path.parent().unwrap();
46 
47     config.program.args.push("--emit=metadata".into());
48     config.program.args.push("-Aunused".into());
49     config.program.args.push("-Zui-testing".into());
50     config.program.args.push("-Dwarnings".into());
51 
52     // Normalize away slashes in windows paths.
53     config.stderr_filter(r"\\", "/");
54 
55     //config.build_base = profile_path.join("test").join(test_dir);
56     config.program.program = profile_path.join(if cfg!(windows) {
57         "clippy-driver.exe"
58     } else {
59         "clippy-driver"
60     });
61     config
62 }
63 
test_filter() -> Box<dyn Sync + Fn(&Path) -> bool>64 fn test_filter() -> Box<dyn Sync + Fn(&Path) -> bool> {
65     if let Ok(filters) = env::var("TESTNAME") {
66         let filters: Vec<_> = filters.split(',').map(ToString::to_string).collect();
67         Box::new(move |path| filters.iter().any(|f| path.to_string_lossy().contains(f)))
68     } else {
69         Box::new(|_| true)
70     }
71 }
72 
run_ui()73 fn run_ui() {
74     let config = base_config("ui");
75     //config.rustfix_coverage = true;
76     // use tests/clippy.toml
77     let _g = VarGuard::set("CARGO_MANIFEST_DIR", fs::canonicalize("tests").unwrap());
78     let _threads = VarGuard::set(
79         "RUST_TEST_THREADS",
80         // if RUST_TEST_THREADS is set, adhere to it, otherwise override it
81         env::var("RUST_TEST_THREADS").unwrap_or_else(|_| {
82             std::thread::available_parallelism()
83                 .map_or(1, std::num::NonZeroUsize::get)
84                 .to_string()
85         }),
86     );
87     eprintln!("   Compiler: {}", config.program.display());
88 
89     let name = config.root_dir.display().to_string();
90 
91     let test_filter = test_filter();
92 
93     compiletest::run_tests_generic(
94         config,
95         move |path| compiletest::default_file_filter(path) && test_filter(path),
96         compiletest::default_per_file_config,
97         (status_emitter::Text, status_emitter::Gha::<true> { name }),
98     )
99     .unwrap();
100     check_rustfix_coverage();
101 }
102 
run_internal_tests()103 fn run_internal_tests() {
104     // only run internal tests with the internal-tests feature
105     if !RUN_INTERNAL_TESTS {
106         return;
107     }
108     let mut config = base_config("ui-internal");
109     config.dependency_builder.args.push("--features".into());
110     config.dependency_builder.args.push("internal".into());
111     compiletest::run_tests(config).unwrap();
112 }
113 
run_ui_toml()114 fn run_ui_toml() {
115     let mut config = base_config("ui-toml");
116 
117     config.stderr_filter(
118         &regex::escape(
119             &fs::canonicalize("tests")
120                 .unwrap()
121                 .parent()
122                 .unwrap()
123                 .display()
124                 .to_string()
125                 .replace('\\', "/"),
126         ),
127         "$$DIR",
128     );
129 
130     let name = config.root_dir.display().to_string();
131 
132     let test_filter = test_filter();
133 
134     ui_test::run_tests_generic(
135         config,
136         |path| test_filter(path) && path.extension() == Some("rs".as_ref()),
137         |config, path| {
138             let mut config = config.clone();
139             config
140                 .program
141                 .envs
142                 .push(("CLIPPY_CONF_DIR".into(), Some(path.parent().unwrap().into())));
143             Some(config)
144         },
145         (status_emitter::Text, status_emitter::Gha::<true> { name }),
146     )
147     .unwrap();
148 }
149 
run_ui_cargo()150 fn run_ui_cargo() {
151     if IS_RUSTC_TEST_SUITE {
152         return;
153     }
154 
155     let mut config = base_config("ui-cargo");
156     config.program.input_file_flag = CommandBuilder::cargo().input_file_flag;
157     config.program.out_dir_flag = CommandBuilder::cargo().out_dir_flag;
158     config.program.args = vec!["clippy".into(), "--color".into(), "never".into(), "--quiet".into()];
159     config
160         .program
161         .envs
162         .push(("RUSTFLAGS".into(), Some("-Dwarnings".into())));
163     // We need to do this while we still have a rustc in the `program` field.
164     config.fill_host_and_target().unwrap();
165     config.dependencies_crate_manifest_path = None;
166     config.program.program.set_file_name(if cfg!(windows) {
167         "cargo-clippy.exe"
168     } else {
169         "cargo-clippy"
170     });
171     config.edition = None;
172 
173     config.stderr_filter(
174         &regex::escape(
175             &fs::canonicalize("tests")
176                 .unwrap()
177                 .parent()
178                 .unwrap()
179                 .display()
180                 .to_string()
181                 .replace('\\', "/"),
182         ),
183         "$$DIR",
184     );
185 
186     let name = config.root_dir.display().to_string();
187 
188     let test_filter = test_filter();
189 
190     ui_test::run_tests_generic(
191         config,
192         |path| test_filter(path) && path.ends_with("Cargo.toml"),
193         |config, path| {
194             let mut config = config.clone();
195             config.out_dir = PathBuf::from("target/ui_test_cargo/").join(path.parent().unwrap());
196             Some(config)
197         },
198         (status_emitter::Text, status_emitter::Gha::<true> { name }),
199     )
200     .unwrap();
201 }
202 
main()203 fn main() {
204     // Support being run by cargo nextest - https://nexte.st/book/custom-test-harnesses.html
205     if env::args().any(|arg| arg == "--list") {
206         if !env::args().any(|arg| arg == "--ignored") {
207             println!("compile_test: test");
208         }
209 
210         return;
211     }
212 
213     set_var("CLIPPY_DISABLE_DOCS_LINKS", "true");
214     run_ui();
215     run_ui_toml();
216     run_ui_cargo();
217     run_internal_tests();
218     rustfix_coverage_known_exceptions_accuracy();
219     ui_cargo_toml_metadata();
220 }
221 
222 const RUSTFIX_COVERAGE_KNOWN_EXCEPTIONS: &[&str] = &[
223     "assign_ops2.rs",
224     "borrow_deref_ref_unfixable.rs",
225     "cast_size_32bit.rs",
226     "char_lit_as_u8.rs",
227     "cmp_owned/without_suggestion.rs",
228     "dbg_macro.rs",
229     "deref_addrof_double_trigger.rs",
230     "doc/unbalanced_ticks.rs",
231     "eprint_with_newline.rs",
232     "explicit_counter_loop.rs",
233     "iter_skip_next_unfixable.rs",
234     "let_and_return.rs",
235     "literals.rs",
236     "map_flatten.rs",
237     "map_unwrap_or.rs",
238     "match_bool.rs",
239     "mem_replace_macro.rs",
240     "needless_arbitrary_self_type_unfixable.rs",
241     "needless_borrow_pat.rs",
242     "needless_for_each_unfixable.rs",
243     "nonminimal_bool.rs",
244     "print_literal.rs",
245     "redundant_static_lifetimes_multiple.rs",
246     "ref_binding_to_reference.rs",
247     "repl_uninit.rs",
248     "result_map_unit_fn_unfixable.rs",
249     "search_is_some.rs",
250     "single_component_path_imports_nested_first.rs",
251     "string_add.rs",
252     "suspicious_to_owned.rs",
253     "toplevel_ref_arg_non_rustfix.rs",
254     "unit_arg.rs",
255     "unnecessary_clone.rs",
256     "unnecessary_lazy_eval_unfixable.rs",
257     "write_literal.rs",
258     "write_literal_2.rs",
259 ];
260 
check_rustfix_coverage()261 fn check_rustfix_coverage() {
262     let missing_coverage_path = Path::new("debug/test/ui/rustfix_missing_coverage.txt");
263     let missing_coverage_path = if let Ok(target_dir) = std::env::var("CARGO_TARGET_DIR") {
264         PathBuf::from(target_dir).join(missing_coverage_path)
265     } else {
266         missing_coverage_path.to_path_buf()
267     };
268 
269     if let Ok(missing_coverage_contents) = std::fs::read_to_string(missing_coverage_path) {
270         assert!(RUSTFIX_COVERAGE_KNOWN_EXCEPTIONS.iter().is_sorted_by_key(Path::new));
271 
272         for rs_file in missing_coverage_contents.lines() {
273             let rs_path = Path::new(rs_file);
274             if rs_path.starts_with("tests/ui/crashes") {
275                 continue;
276             }
277             assert!(rs_path.starts_with("tests/ui/"), "{rs_file:?}");
278             let filename = rs_path.strip_prefix("tests/ui/").unwrap();
279             assert!(
280                 RUSTFIX_COVERAGE_KNOWN_EXCEPTIONS
281                     .binary_search_by_key(&filename, Path::new)
282                     .is_ok(),
283                 "`{rs_file}` runs `MachineApplicable` diagnostics but is missing a `run-rustfix` annotation. \
284                 Please either add `//@run-rustfix` at the top of the file or add the file to \
285                 `RUSTFIX_COVERAGE_KNOWN_EXCEPTIONS` in `tests/compile-test.rs`.",
286             );
287         }
288     }
289 }
290 
rustfix_coverage_known_exceptions_accuracy()291 fn rustfix_coverage_known_exceptions_accuracy() {
292     for filename in RUSTFIX_COVERAGE_KNOWN_EXCEPTIONS {
293         let rs_path = Path::new("tests/ui").join(filename);
294         assert!(rs_path.exists(), "`{}` does not exist", rs_path.display());
295         let fixed_path = rs_path.with_extension("fixed");
296         assert!(!fixed_path.exists(), "`{}` exists", fixed_path.display());
297     }
298 }
299 
ui_cargo_toml_metadata()300 fn ui_cargo_toml_metadata() {
301     let ui_cargo_path = Path::new("tests/ui-cargo");
302     let cargo_common_metadata_path = ui_cargo_path.join("cargo_common_metadata");
303     let publish_exceptions =
304         ["fail_publish", "fail_publish_true", "pass_publish_empty"].map(|path| cargo_common_metadata_path.join(path));
305 
306     for entry in walkdir::WalkDir::new(ui_cargo_path) {
307         let entry = entry.unwrap();
308         let path = entry.path();
309         if path.file_name() != Some(OsStr::new("Cargo.toml")) {
310             continue;
311         }
312 
313         let toml = fs::read_to_string(path).unwrap().parse::<toml::Value>().unwrap();
314 
315         let package = toml.as_table().unwrap().get("package").unwrap().as_table().unwrap();
316 
317         let name = package.get("name").unwrap().as_str().unwrap().replace('-', "_");
318         assert!(
319             path.parent()
320                 .unwrap()
321                 .components()
322                 .map(|component| component.as_os_str().to_string_lossy().replace('-', "_"))
323                 .any(|s| *s == name)
324                 || path.starts_with(&cargo_common_metadata_path),
325             "{path:?} has incorrect package name"
326         );
327 
328         let publish = package.get("publish").and_then(toml::Value::as_bool).unwrap_or(true);
329         assert!(
330             !publish || publish_exceptions.contains(&path.parent().unwrap().to_path_buf()),
331             "{path:?} lacks `publish = false`"
332         );
333     }
334 }
335 
336 /// Restores an env var on drop
337 #[must_use]
338 struct VarGuard {
339     key: &'static str,
340     value: Option<OsString>,
341 }
342 
343 impl VarGuard {
set(key: &'static str, val: impl AsRef<OsStr>) -> Self344     fn set(key: &'static str, val: impl AsRef<OsStr>) -> Self {
345         let value = var_os(key);
346         set_var(key, val);
347         Self { key, value }
348     }
349 }
350 
351 impl Drop for VarGuard {
drop(&mut self)352     fn drop(&mut self) {
353         match self.value.as_deref() {
354             None => remove_var(self.key),
355             Some(value) => set_var(self.key, value),
356         }
357     }
358 }
359