]> git.lizzy.rs Git - rust.git/blob - src/tools/clippy/clippy_dev/src/lintcheck.rs
Rollup merge of #82484 - bugadani:docfix, r=jyn514
[rust.git] / src / tools / clippy / clippy_dev / src / lintcheck.rs
1 // Run clippy on a fixed set of crates and collect the warnings.
2 // This helps observing the impact clippy changs have on a set of real-world code.
3 //
4 // When a new lint is introduced, we can search the results for new warnings and check for false
5 // positives.
6
7 #![cfg(feature = "lintcheck")]
8 #![allow(clippy::filter_map)]
9
10 use crate::clippy_project_root;
11
12 use std::collections::HashMap;
13 use std::process::Command;
14 use std::sync::atomic::{AtomicUsize, Ordering};
15 use std::{env, fmt, fs::write, path::PathBuf};
16
17 use clap::ArgMatches;
18 use rayon::prelude::*;
19 use serde::{Deserialize, Serialize};
20 use serde_json::Value;
21
22 /// List of sources to check, loaded from a .toml file
23 #[derive(Debug, Serialize, Deserialize)]
24 struct SourceList {
25     crates: HashMap<String, TomlCrate>,
26 }
27
28 /// A crate source stored inside the .toml
29 /// will be translated into on one of the `CrateSource` variants
30 #[derive(Debug, Serialize, Deserialize)]
31 struct TomlCrate {
32     name: String,
33     versions: Option<Vec<String>>,
34     git_url: Option<String>,
35     git_hash: Option<String>,
36     path: Option<String>,
37     options: Option<Vec<String>>,
38 }
39
40 /// Represents an archive we download from crates.io, or a git repo, or a local repo/folder
41 /// Once processed (downloaded/extracted/cloned/copied...), this will be translated into a `Crate`
42 #[derive(Debug, Serialize, Deserialize, Eq, Hash, PartialEq, Ord, PartialOrd)]
43 enum CrateSource {
44     CratesIo {
45         name: String,
46         version: String,
47         options: Option<Vec<String>>,
48     },
49     Git {
50         name: String,
51         url: String,
52         commit: String,
53         options: Option<Vec<String>>,
54     },
55     Path {
56         name: String,
57         path: PathBuf,
58         options: Option<Vec<String>>,
59     },
60 }
61
62 /// Represents the actual source code of a crate that we ran "cargo clippy" on
63 #[derive(Debug)]
64 struct Crate {
65     version: String,
66     name: String,
67     // path to the extracted sources that clippy can check
68     path: PathBuf,
69     options: Option<Vec<String>>,
70 }
71
72 /// A single warning that clippy issued while checking a `Crate`
73 #[derive(Debug)]
74 struct ClippyWarning {
75     crate_name: String,
76     crate_version: String,
77     file: String,
78     line: String,
79     column: String,
80     linttype: String,
81     message: String,
82     is_ice: bool,
83 }
84
85 impl std::fmt::Display for ClippyWarning {
86     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
87         writeln!(
88             f,
89             r#"{}-{}/{}:{}:{} {} "{}""#,
90             &self.crate_name, &self.crate_version, &self.file, &self.line, &self.column, &self.linttype, &self.message
91         )
92     }
93 }
94
95 impl CrateSource {
96     /// Makes the sources available on the disk for clippy to check.
97     /// Clones a git repo and checks out the specified commit or downloads a crate from crates.io or
98     /// copies a local folder
99     fn download_and_extract(&self) -> Crate {
100         match self {
101             CrateSource::CratesIo { name, version, options } => {
102                 let extract_dir = PathBuf::from("target/lintcheck/crates");
103                 let krate_download_dir = PathBuf::from("target/lintcheck/downloads");
104
105                 // url to download the crate from crates.io
106                 let url = format!("https://crates.io/api/v1/crates/{}/{}/download", name, version);
107                 println!("Downloading and extracting {} {} from {}", name, version, url);
108                 let _ = std::fs::create_dir("target/lintcheck/");
109                 let _ = std::fs::create_dir(&krate_download_dir);
110                 let _ = std::fs::create_dir(&extract_dir);
111
112                 let krate_file_path = krate_download_dir.join(format!("{}-{}.crate.tar.gz", name, version));
113                 // don't download/extract if we already have done so
114                 if !krate_file_path.is_file() {
115                     // create a file path to download and write the crate data into
116                     let mut krate_dest = std::fs::File::create(&krate_file_path).unwrap();
117                     let mut krate_req = ureq::get(&url).call().unwrap().into_reader();
118                     // copy the crate into the file
119                     std::io::copy(&mut krate_req, &mut krate_dest).unwrap();
120
121                     // unzip the tarball
122                     let ungz_tar = flate2::read::GzDecoder::new(std::fs::File::open(&krate_file_path).unwrap());
123                     // extract the tar archive
124                     let mut archive = tar::Archive::new(ungz_tar);
125                     archive.unpack(&extract_dir).expect("Failed to extract!");
126                 }
127                 // crate is extracted, return a new Krate object which contains the path to the extracted
128                 // sources that clippy can check
129                 Crate {
130                     version: version.clone(),
131                     name: name.clone(),
132                     path: extract_dir.join(format!("{}-{}/", name, version)),
133                     options: options.clone(),
134                 }
135             },
136             CrateSource::Git {
137                 name,
138                 url,
139                 commit,
140                 options,
141             } => {
142                 let repo_path = {
143                     let mut repo_path = PathBuf::from("target/lintcheck/crates");
144                     // add a -git suffix in case we have the same crate from crates.io and a git repo
145                     repo_path.push(format!("{}-git", name));
146                     repo_path
147                 };
148                 // clone the repo if we have not done so
149                 if !repo_path.is_dir() {
150                     println!("Cloning {} and checking out {}", url, commit);
151                     if !Command::new("git")
152                         .arg("clone")
153                         .arg(url)
154                         .arg(&repo_path)
155                         .status()
156                         .expect("Failed to clone git repo!")
157                         .success()
158                     {
159                         eprintln!("Failed to clone {} into {}", url, repo_path.display())
160                     }
161                 }
162                 // check out the commit/branch/whatever
163                 if !Command::new("git")
164                     .arg("checkout")
165                     .arg(commit)
166                     .current_dir(&repo_path)
167                     .status()
168                     .expect("Failed to check out commit")
169                     .success()
170                 {
171                     eprintln!("Failed to checkout {} of repo at {}", commit, repo_path.display())
172                 }
173
174                 Crate {
175                     version: commit.clone(),
176                     name: name.clone(),
177                     path: repo_path,
178                     options: options.clone(),
179                 }
180             },
181             CrateSource::Path { name, path, options } => {
182                 use fs_extra::dir;
183
184                 // simply copy the entire directory into our target dir
185                 let copy_dest = PathBuf::from("target/lintcheck/crates/");
186
187                 // the source path of the crate we copied,  ${copy_dest}/crate_name
188                 let crate_root = copy_dest.join(name); // .../crates/local_crate
189
190                 if !crate_root.exists() {
191                     println!("Copying {} to {}", path.display(), copy_dest.display());
192
193                     dir::copy(path, &copy_dest, &dir::CopyOptions::new()).expect(&format!(
194                         "Failed to copy from {}, to  {}",
195                         path.display(),
196                         crate_root.display()
197                     ));
198                 } else {
199                     println!(
200                         "Not copying {} to {}, destination already exists",
201                         path.display(),
202                         crate_root.display()
203                     );
204                 }
205
206                 Crate {
207                     version: String::from("local"),
208                     name: name.clone(),
209                     path: crate_root,
210                     options: options.clone(),
211                 }
212             },
213         }
214     }
215 }
216
217 impl Crate {
218     /// Run `cargo clippy` on the `Crate` and collect and return all the lint warnings that clippy
219     /// issued
220     fn run_clippy_lints(
221         &self,
222         cargo_clippy_path: &PathBuf,
223         target_dir_index: &AtomicUsize,
224         thread_limit: usize,
225         total_crates_to_lint: usize,
226     ) -> Vec<ClippyWarning> {
227         // advance the atomic index by one
228         let index = target_dir_index.fetch_add(1, Ordering::SeqCst);
229         // "loop" the index within 0..thread_limit
230         let target_dir_index = index % thread_limit;
231         let perc = ((index * 100) as f32 / total_crates_to_lint as f32) as u8;
232
233         if thread_limit == 1 {
234             println!(
235                 "{}/{} {}% Linting {} {}",
236                 index, total_crates_to_lint, perc, &self.name, &self.version
237             );
238         } else {
239             println!(
240                 "{}/{} {}% Linting {} {} in target dir {:?}",
241                 index, total_crates_to_lint, perc, &self.name, &self.version, target_dir_index
242             );
243         }
244
245         let cargo_clippy_path = std::fs::canonicalize(cargo_clippy_path).unwrap();
246
247         let shared_target_dir = clippy_project_root().join("target/lintcheck/shared_target_dir");
248
249         let mut args = vec!["--", "--message-format=json", "--", "--cap-lints=warn"];
250
251         if let Some(options) = &self.options {
252             for opt in options {
253                 args.push(opt);
254             }
255         } else {
256             args.extend(&["-Wclippy::pedantic", "-Wclippy::cargo"])
257         }
258
259         let all_output = std::process::Command::new(&cargo_clippy_path)
260             // use the looping index to create individual target dirs
261             .env(
262                 "CARGO_TARGET_DIR",
263                 shared_target_dir.join(format!("_{:?}", target_dir_index)),
264             )
265             // lint warnings will look like this:
266             // src/cargo/ops/cargo_compile.rs:127:35: warning: usage of `FromIterator::from_iter`
267             .args(&args)
268             .current_dir(&self.path)
269             .output()
270             .unwrap_or_else(|error| {
271                 panic!(
272                     "Encountered error:\n{:?}\ncargo_clippy_path: {}\ncrate path:{}\n",
273                     error,
274                     &cargo_clippy_path.display(),
275                     &self.path.display()
276                 );
277             });
278         let stdout = String::from_utf8_lossy(&all_output.stdout);
279         let output_lines = stdout.lines();
280         let warnings: Vec<ClippyWarning> = output_lines
281             .into_iter()
282             // get all clippy warnings and ICEs
283             .filter(|line| filter_clippy_warnings(&line))
284             .map(|json_msg| parse_json_message(json_msg, &self))
285             .collect();
286         warnings
287     }
288 }
289
290 /// takes a single json-formatted clippy warnings and returns true (we are interested in that line)
291 /// or false (we aren't)
292 fn filter_clippy_warnings(line: &str) -> bool {
293     // we want to collect ICEs because clippy might have crashed.
294     // these are summarized later
295     if line.contains("internal compiler error: ") {
296         return true;
297     }
298     // in general, we want all clippy warnings
299     // however due to some kind of bug, sometimes there are absolute paths
300     // to libcore files inside the message
301     // or we end up with cargo-metadata output (https://github.com/rust-lang/rust-clippy/issues/6508)
302
303     // filter out these message to avoid unnecessary noise in the logs
304     if line.contains("clippy::")
305         && !(line.contains("could not read cargo metadata")
306             || (line.contains(".rustup") && line.contains("toolchains")))
307     {
308         return true;
309     }
310     false
311 }
312
313 /// get the path to lintchecks crate sources .toml file, check LINTCHECK_TOML first but if it's
314 /// empty use the default path
315 fn lintcheck_config_toml(toml_path: Option<&str>) -> PathBuf {
316     PathBuf::from(
317         env::var("LINTCHECK_TOML").unwrap_or(
318             toml_path
319                 .clone()
320                 .unwrap_or("clippy_dev/lintcheck_crates.toml")
321                 .to_string(),
322         ),
323     )
324 }
325
326 /// Builds clippy inside the repo to make sure we have a clippy executable we can use.
327 fn build_clippy() {
328     let status = Command::new("cargo")
329         .arg("build")
330         .status()
331         .expect("Failed to build clippy!");
332     if !status.success() {
333         eprintln!("Error: Failed to compile Clippy!");
334         std::process::exit(1);
335     }
336 }
337
338 /// Read a `toml` file and return a list of `CrateSources` that we want to check with clippy
339 fn read_crates(toml_path: Option<&str>) -> (String, Vec<CrateSource>) {
340     let toml_path = lintcheck_config_toml(toml_path);
341     // save it so that we can use the name of the sources.toml as name for the logfile later.
342     let toml_filename = toml_path.file_stem().unwrap().to_str().unwrap().to_string();
343     let toml_content: String =
344         std::fs::read_to_string(&toml_path).unwrap_or_else(|_| panic!("Failed to read {}", toml_path.display()));
345     let crate_list: SourceList =
346         toml::from_str(&toml_content).unwrap_or_else(|e| panic!("Failed to parse {}: \n{}", toml_path.display(), e));
347     // parse the hashmap of the toml file into a list of crates
348     let tomlcrates: Vec<TomlCrate> = crate_list
349         .crates
350         .into_iter()
351         .map(|(_cratename, tomlcrate)| tomlcrate)
352         .collect();
353
354     // flatten TomlCrates into CrateSources (one TomlCrates may represent several versions of a crate =>
355     // multiple Cratesources)
356     let mut crate_sources = Vec::new();
357     tomlcrates.into_iter().for_each(|tk| {
358         if let Some(ref path) = tk.path {
359             crate_sources.push(CrateSource::Path {
360                 name: tk.name.clone(),
361                 path: PathBuf::from(path),
362                 options: tk.options.clone(),
363             });
364         }
365
366         // if we have multiple versions, save each one
367         if let Some(ref versions) = tk.versions {
368             versions.iter().for_each(|ver| {
369                 crate_sources.push(CrateSource::CratesIo {
370                     name: tk.name.clone(),
371                     version: ver.to_string(),
372                     options: tk.options.clone(),
373                 });
374             })
375         }
376         // otherwise, we should have a git source
377         if tk.git_url.is_some() && tk.git_hash.is_some() {
378             crate_sources.push(CrateSource::Git {
379                 name: tk.name.clone(),
380                 url: tk.git_url.clone().unwrap(),
381                 commit: tk.git_hash.clone().unwrap(),
382                 options: tk.options.clone(),
383             });
384         }
385         // if we have a version as well as a git data OR only one git data, something is funky
386         if tk.versions.is_some() && (tk.git_url.is_some() || tk.git_hash.is_some())
387             || tk.git_hash.is_some() != tk.git_url.is_some()
388         {
389             eprintln!("tomlkrate: {:?}", tk);
390             if tk.git_hash.is_some() != tk.git_url.is_some() {
391                 panic!("Error: Encountered TomlCrate with only one of git_hash and git_url!");
392             }
393             if tk.path.is_some() && (tk.git_hash.is_some() || tk.versions.is_some()) {
394                 panic!("Error: TomlCrate can only have one of 'git_.*', 'version' or 'path' fields");
395             }
396             unreachable!("Failed to translate TomlCrate into CrateSource!");
397         }
398     });
399     // sort the crates
400     crate_sources.sort();
401
402     (toml_filename, crate_sources)
403 }
404
405 /// Parse the json output of clippy and return a `ClippyWarning`
406 fn parse_json_message(json_message: &str, krate: &Crate) -> ClippyWarning {
407     let jmsg: Value = serde_json::from_str(&json_message).unwrap_or_else(|e| panic!("Failed to parse json:\n{:?}", e));
408
409     ClippyWarning {
410         crate_name: krate.name.to_string(),
411         crate_version: krate.version.to_string(),
412         file: jmsg["message"]["spans"][0]["file_name"]
413             .to_string()
414             .trim_matches('"')
415             .into(),
416         line: jmsg["message"]["spans"][0]["line_start"]
417             .to_string()
418             .trim_matches('"')
419             .into(),
420         column: jmsg["message"]["spans"][0]["text"][0]["highlight_start"]
421             .to_string()
422             .trim_matches('"')
423             .into(),
424         linttype: jmsg["message"]["code"]["code"].to_string().trim_matches('"').into(),
425         message: jmsg["message"]["message"].to_string().trim_matches('"').into(),
426         is_ice: json_message.contains("internal compiler error: "),
427     }
428 }
429
430 /// Generate a short list of occuring lints-types and their count
431 fn gather_stats(clippy_warnings: &[ClippyWarning]) -> String {
432     // count lint type occurrences
433     let mut counter: HashMap<&String, usize> = HashMap::new();
434     clippy_warnings
435         .iter()
436         .for_each(|wrn| *counter.entry(&wrn.linttype).or_insert(0) += 1);
437
438     // collect into a tupled list for sorting
439     let mut stats: Vec<(&&String, &usize)> = counter.iter().map(|(lint, count)| (lint, count)).collect();
440     // sort by "000{count} {clippy::lintname}"
441     // to not have a lint with 200 and 2 warnings take the same spot
442     stats.sort_by_key(|(lint, count)| format!("{:0>4}, {}", count, lint));
443
444     stats
445         .iter()
446         .map(|(lint, count)| format!("{} {}\n", lint, count))
447         .collect::<String>()
448 }
449
450 /// check if the latest modification of the logfile is older than the modification date of the
451 /// clippy binary, if this is true, we should clean the lintchec shared target directory and recheck
452 fn lintcheck_needs_rerun(toml_path: Option<&str>) -> bool {
453     let clippy_modified: std::time::SystemTime = {
454         let mut times = ["target/debug/clippy-driver", "target/debug/cargo-clippy"]
455             .iter()
456             .map(|p| {
457                 std::fs::metadata(p)
458                     .expect("failed to get metadata of file")
459                     .modified()
460                     .expect("failed to get modification date")
461             });
462         // the lates modification of either of the binaries
463         std::cmp::max(times.next().unwrap(), times.next().unwrap())
464     };
465
466     let logs_modified: std::time::SystemTime = std::fs::metadata(lintcheck_config_toml(toml_path))
467         .expect("failed to get metadata of file")
468         .modified()
469         .expect("failed to get modification date");
470
471     // if clippys modification time is bigger (older) than the logs mod time, we need to rerun lintcheck
472     clippy_modified > logs_modified
473 }
474
475 /// lintchecks `main()` function
476 pub fn run(clap_config: &ArgMatches) {
477     println!("Compiling clippy...");
478     build_clippy();
479     println!("Done compiling");
480
481     let clap_toml_path = clap_config.value_of("crates-toml");
482
483     // if the clippy bin is newer than our logs, throw away target dirs to force clippy to
484     // refresh the logs
485     if lintcheck_needs_rerun(clap_toml_path) {
486         let shared_target_dir = "target/lintcheck/shared_target_dir";
487         match std::fs::metadata(&shared_target_dir) {
488             Ok(metadata) => {
489                 if metadata.is_dir() {
490                     println!("Clippy is newer than lint check logs, clearing lintcheck shared target dir...");
491                     std::fs::remove_dir_all(&shared_target_dir)
492                         .expect("failed to remove target/lintcheck/shared_target_dir");
493                 }
494             },
495             Err(_) => { // dir probably does not exist, don't remove anything
496             },
497         }
498     }
499
500     let cargo_clippy_path: PathBuf = PathBuf::from("target/debug/cargo-clippy")
501         .canonicalize()
502         .expect("failed to canonicalize path to clippy binary");
503
504     // assert that clippy is found
505     assert!(
506         cargo_clippy_path.is_file(),
507         "target/debug/cargo-clippy binary not found! {}",
508         cargo_clippy_path.display()
509     );
510
511     let clippy_ver = std::process::Command::new("target/debug/cargo-clippy")
512         .arg("--version")
513         .output()
514         .map(|o| String::from_utf8_lossy(&o.stdout).into_owned())
515         .expect("could not get clippy version!");
516
517     // download and extract the crates, then run clippy on them and collect clippys warnings
518     // flatten into one big list of warnings
519
520     let (filename, crates) = read_crates(clap_toml_path);
521
522     let clippy_warnings: Vec<ClippyWarning> = if let Some(only_one_crate) = clap_config.value_of("only") {
523         // if we don't have the specified crate in the .toml, throw an error
524         if !crates.iter().any(|krate| {
525             let name = match krate {
526                 CrateSource::CratesIo { name, .. } => name,
527                 CrateSource::Git { name, .. } => name,
528                 CrateSource::Path { name, .. } => name,
529             };
530             name == only_one_crate
531         }) {
532             eprintln!(
533                 "ERROR: could not find crate '{}' in clippy_dev/lintcheck_crates.toml",
534                 only_one_crate
535             );
536             std::process::exit(1);
537         }
538
539         // only check a single crate that was passed via cmdline
540         crates
541             .into_iter()
542             .map(|krate| krate.download_and_extract())
543             .filter(|krate| krate.name == only_one_crate)
544             .map(|krate| krate.run_clippy_lints(&cargo_clippy_path, &AtomicUsize::new(0), 1, 1))
545             .flatten()
546             .collect()
547     } else {
548         let counter = std::sync::atomic::AtomicUsize::new(0);
549
550         // Ask rayon for thread count. Assume that half of that is the number of physical cores
551         // Use one target dir for each core so that we can run N clippys in parallel.
552         // We need to use different target dirs because cargo would lock them for a single build otherwise,
553         // killing the parallelism. However this also means that deps will only be reused half/a
554         // quarter of the time which might result in a longer wall clock runtime
555
556         // This helps when we check many small crates with dep-trees that don't have a lot of branches in
557         // order to achive some kind of parallelism
558
559         // by default, use a single thread
560         let num_cpus = match clap_config.value_of("threads") {
561             Some(threads) => {
562                 let threads: usize = threads
563                     .parse()
564                     .expect(&format!("Failed to parse '{}' to a digit", threads));
565                 if threads == 0 {
566                     // automatic choice
567                     // Rayon seems to return thread count so half that for core count
568                     (rayon::current_num_threads() / 2) as usize
569                 } else {
570                     threads
571                 }
572             },
573             // no -j passed, use a single thread
574             None => 1,
575         };
576
577         let num_crates = crates.len();
578
579         // check all crates (default)
580         crates
581             .into_par_iter()
582             .map(|krate| krate.download_and_extract())
583             .map(|krate| krate.run_clippy_lints(&cargo_clippy_path, &counter, num_cpus, num_crates))
584             .flatten()
585             .collect()
586     };
587
588     // generate some stats
589     let stats_formatted = gather_stats(&clippy_warnings);
590
591     // grab crashes/ICEs, save the crate name and the ice message
592     let ices: Vec<(&String, &String)> = clippy_warnings
593         .iter()
594         .filter(|warning| warning.is_ice)
595         .map(|w| (&w.crate_name, &w.message))
596         .collect();
597
598     let mut all_msgs: Vec<String> = clippy_warnings.iter().map(|warning| warning.to_string()).collect();
599     all_msgs.sort();
600     all_msgs.push("\n\n\n\nStats\n\n".into());
601     all_msgs.push(stats_formatted);
602
603     // save the text into lintcheck-logs/logs.txt
604     let mut text = clippy_ver; // clippy version number on top
605     text.push_str(&format!("\n{}", all_msgs.join("")));
606     text.push_str("ICEs:\n");
607     ices.iter()
608         .for_each(|(cratename, msg)| text.push_str(&format!("{}: '{}'", cratename, msg)));
609
610     let file = format!("lintcheck-logs/{}_logs.txt", filename);
611     println!("Writing logs to {}", file);
612     write(file, text).unwrap();
613 }