]> git.lizzy.rs Git - rust.git/blob - src/tools/clippy/clippy_dev/src/lib.rs
Auto merge of #79780 - camelid:use-summary_opts, r=GuillaumeGomez
[rust.git] / src / tools / clippy / clippy_dev / src / lib.rs
1 #![cfg_attr(feature = "deny-warnings", deny(warnings))]
2 #![feature(once_cell)]
3
4 use itertools::Itertools;
5 use regex::Regex;
6 use std::collections::HashMap;
7 use std::ffi::OsStr;
8 use std::fs;
9 use std::lazy::SyncLazy;
10 use std::path::{Path, PathBuf};
11 use walkdir::WalkDir;
12
13 pub mod fmt;
14 pub mod new_lint;
15 pub mod ra_setup;
16 pub mod serve;
17 pub mod stderr_length_check;
18 pub mod update_lints;
19
20 static DEC_CLIPPY_LINT_RE: SyncLazy<Regex> = SyncLazy::new(|| {
21     Regex::new(
22         r#"(?x)
23     declare_clippy_lint!\s*[\{(]
24     (?:\s+///.*)*
25     \s+pub\s+(?P<name>[A-Z_][A-Z_0-9]*)\s*,\s*
26     (?P<cat>[a-z_]+)\s*,\s*
27     "(?P<desc>(?:[^"\\]+|\\(?s).(?-s))*)"\s*[})]
28 "#,
29     )
30     .unwrap()
31 });
32
33 static DEC_DEPRECATED_LINT_RE: SyncLazy<Regex> = SyncLazy::new(|| {
34     Regex::new(
35         r#"(?x)
36     declare_deprecated_lint!\s*[{(]\s*
37     (?:\s+///.*)*
38     \s+pub\s+(?P<name>[A-Z_][A-Z_0-9]*)\s*,\s*
39     "(?P<desc>(?:[^"\\]+|\\(?s).(?-s))*)"\s*[})]
40 "#,
41     )
42     .unwrap()
43 });
44 static NL_ESCAPE_RE: SyncLazy<Regex> = SyncLazy::new(|| Regex::new(r#"\\\n\s*"#).unwrap());
45
46 pub static DOCS_LINK: &str = "https://rust-lang.github.io/rust-clippy/master/index.html";
47
48 /// Lint data parsed from the Clippy source code.
49 #[derive(Clone, PartialEq, Debug)]
50 pub struct Lint {
51     pub name: String,
52     pub group: String,
53     pub desc: String,
54     pub deprecation: Option<String>,
55     pub module: String,
56 }
57
58 impl Lint {
59     #[must_use]
60     pub fn new(name: &str, group: &str, desc: &str, deprecation: Option<&str>, module: &str) -> Self {
61         Self {
62             name: name.to_lowercase(),
63             group: group.to_string(),
64             desc: NL_ESCAPE_RE.replace(&desc.replace("\\\"", "\""), "").to_string(),
65             deprecation: deprecation.map(ToString::to_string),
66             module: module.to_string(),
67         }
68     }
69
70     /// Returns all non-deprecated lints and non-internal lints
71     #[must_use]
72     pub fn usable_lints(lints: &[Self]) -> Vec<Self> {
73         lints
74             .iter()
75             .filter(|l| l.deprecation.is_none() && !l.group.starts_with("internal"))
76             .cloned()
77             .collect()
78     }
79
80     /// Returns all internal lints (not `internal_warn` lints)
81     #[must_use]
82     pub fn internal_lints(lints: &[Self]) -> Vec<Self> {
83         lints.iter().filter(|l| l.group == "internal").cloned().collect()
84     }
85
86     /// Returns all deprecated lints
87     #[must_use]
88     pub fn deprecated_lints(lints: &[Self]) -> Vec<Self> {
89         lints.iter().filter(|l| l.deprecation.is_some()).cloned().collect()
90     }
91
92     /// Returns the lints in a `HashMap`, grouped by the different lint groups
93     #[must_use]
94     pub fn by_lint_group(lints: impl Iterator<Item = Self>) -> HashMap<String, Vec<Self>> {
95         lints.map(|lint| (lint.group.to_string(), lint)).into_group_map()
96     }
97 }
98
99 /// Generates the Vec items for `register_lint_group` calls in `clippy_lints/src/lib.rs`.
100 #[must_use]
101 pub fn gen_lint_group_list<'a>(lints: impl Iterator<Item = &'a Lint>) -> Vec<String> {
102     lints
103         .map(|l| format!("        LintId::of(&{}::{}),", l.module, l.name.to_uppercase()))
104         .sorted()
105         .collect::<Vec<String>>()
106 }
107
108 /// Generates the `pub mod module_name` list in `clippy_lints/src/lib.rs`.
109 #[must_use]
110 pub fn gen_modules_list<'a>(lints: impl Iterator<Item = &'a Lint>) -> Vec<String> {
111     lints
112         .map(|l| &l.module)
113         .unique()
114         .map(|module| format!("mod {};", module))
115         .sorted()
116         .collect::<Vec<String>>()
117 }
118
119 /// Generates the list of lint links at the bottom of the README
120 #[must_use]
121 pub fn gen_changelog_lint_list<'a>(lints: impl Iterator<Item = &'a Lint>) -> Vec<String> {
122     lints
123         .sorted_by_key(|l| &l.name)
124         .map(|l| format!("[`{}`]: {}#{}", l.name, DOCS_LINK, l.name))
125         .collect()
126 }
127
128 /// Generates the `register_removed` code in `./clippy_lints/src/lib.rs`.
129 #[must_use]
130 pub fn gen_deprecated<'a>(lints: impl Iterator<Item = &'a Lint>) -> Vec<String> {
131     lints
132         .flat_map(|l| {
133             l.deprecation
134                 .clone()
135                 .map(|depr_text| {
136                     vec![
137                         "    store.register_removed(".to_string(),
138                         format!("        \"clippy::{}\",", l.name),
139                         format!("        \"{}\",", depr_text),
140                         "    );".to_string(),
141                     ]
142                 })
143                 .expect("only deprecated lints should be passed")
144         })
145         .collect::<Vec<String>>()
146 }
147
148 #[must_use]
149 pub fn gen_register_lint_list<'a>(
150     internal_lints: impl Iterator<Item = &'a Lint>,
151     usable_lints: impl Iterator<Item = &'a Lint>,
152 ) -> Vec<String> {
153     let header = "    store.register_lints(&[".to_string();
154     let footer = "    ]);".to_string();
155     let internal_lints = internal_lints
156         .sorted_by_key(|l| format!("        &{}::{},", l.module, l.name.to_uppercase()))
157         .map(|l| {
158             format!(
159                 "        #[cfg(feature = \"internal-lints\")]\n        &{}::{},",
160                 l.module,
161                 l.name.to_uppercase()
162             )
163         });
164     let other_lints = usable_lints
165         .sorted_by_key(|l| format!("        &{}::{},", l.module, l.name.to_uppercase()))
166         .map(|l| format!("        &{}::{},", l.module, l.name.to_uppercase()))
167         .sorted();
168     let mut lint_list = vec![header];
169     lint_list.extend(internal_lints);
170     lint_list.extend(other_lints);
171     lint_list.push(footer);
172     lint_list
173 }
174
175 /// Gathers all files in `src/clippy_lints` and gathers all lints inside
176 pub fn gather_all() -> impl Iterator<Item = Lint> {
177     lint_files().flat_map(|f| gather_from_file(&f))
178 }
179
180 fn gather_from_file(dir_entry: &walkdir::DirEntry) -> impl Iterator<Item = Lint> {
181     let content = fs::read_to_string(dir_entry.path()).unwrap();
182     let path = dir_entry.path();
183     let filename = path.file_stem().unwrap();
184     let path_buf = path.with_file_name(filename);
185     let mut rel_path = path_buf
186         .strip_prefix(clippy_project_root().join("clippy_lints/src"))
187         .expect("only files in `clippy_lints/src` should be looked at");
188     // If the lints are stored in mod.rs, we get the module name from
189     // the containing directory:
190     if filename == "mod" {
191         rel_path = rel_path.parent().unwrap();
192     }
193
194     let module = rel_path
195         .components()
196         .map(|c| c.as_os_str().to_str().unwrap())
197         .collect::<Vec<_>>()
198         .join("::");
199
200     parse_contents(&content, &module)
201 }
202
203 fn parse_contents(content: &str, module: &str) -> impl Iterator<Item = Lint> {
204     let lints = DEC_CLIPPY_LINT_RE
205         .captures_iter(content)
206         .map(|m| Lint::new(&m["name"], &m["cat"], &m["desc"], None, module));
207     let deprecated = DEC_DEPRECATED_LINT_RE
208         .captures_iter(content)
209         .map(|m| Lint::new(&m["name"], "Deprecated", &m["desc"], Some(&m["desc"]), module));
210     // Removing the `.collect::<Vec<Lint>>().into_iter()` causes some lifetime issues due to the map
211     lints.chain(deprecated).collect::<Vec<Lint>>().into_iter()
212 }
213
214 /// Collects all .rs files in the `clippy_lints/src` directory
215 fn lint_files() -> impl Iterator<Item = walkdir::DirEntry> {
216     // We use `WalkDir` instead of `fs::read_dir` here in order to recurse into subdirectories.
217     // Otherwise we would not collect all the lints, for example in `clippy_lints/src/methods/`.
218     let path = clippy_project_root().join("clippy_lints/src");
219     WalkDir::new(path)
220         .into_iter()
221         .filter_map(Result::ok)
222         .filter(|f| f.path().extension() == Some(OsStr::new("rs")))
223 }
224
225 /// Whether a file has had its text changed or not
226 #[derive(PartialEq, Debug)]
227 pub struct FileChange {
228     pub changed: bool,
229     pub new_lines: String,
230 }
231
232 /// Replaces a region in a file delimited by two lines matching regexes.
233 ///
234 /// `path` is the relative path to the file on which you want to perform the replacement.
235 ///
236 /// See `replace_region_in_text` for documentation of the other options.
237 pub fn replace_region_in_file<F>(
238     path: &Path,
239     start: &str,
240     end: &str,
241     replace_start: bool,
242     write_back: bool,
243     replacements: F,
244 ) -> FileChange
245 where
246     F: FnOnce() -> Vec<String>,
247 {
248     let contents = fs::read_to_string(path).unwrap_or_else(|e| panic!("Cannot read from {}: {}", path.display(), e));
249     let file_change = replace_region_in_text(&contents, start, end, replace_start, replacements);
250
251     if write_back {
252         if let Err(e) = fs::write(path, file_change.new_lines.as_bytes()) {
253             panic!("Cannot write to {}: {}", path.display(), e);
254         }
255     }
256     file_change
257 }
258
259 /// Replaces a region in a text delimited by two lines matching regexes.
260 ///
261 /// * `text` is the input text on which you want to perform the replacement
262 /// * `start` is a `&str` that describes the delimiter line before the region you want to replace.
263 ///   As the `&str` will be converted to a `Regex`, this can contain regex syntax, too.
264 /// * `end` is a `&str` that describes the delimiter line until where the replacement should happen.
265 ///   As the `&str` will be converted to a `Regex`, this can contain regex syntax, too.
266 /// * If `replace_start` is true, the `start` delimiter line is replaced as well. The `end`
267 ///   delimiter line is never replaced.
268 /// * `replacements` is a closure that has to return a `Vec<String>` which contains the new text.
269 ///
270 /// If you want to perform the replacement on files instead of already parsed text,
271 /// use `replace_region_in_file`.
272 ///
273 /// # Example
274 ///
275 /// ```
276 /// let the_text = "replace_start\nsome text\nthat will be replaced\nreplace_end";
277 /// let result =
278 ///     clippy_dev::replace_region_in_text(the_text, "replace_start", "replace_end", false, || {
279 ///         vec!["a different".to_string(), "text".to_string()]
280 ///     })
281 ///     .new_lines;
282 /// assert_eq!("replace_start\na different\ntext\nreplace_end", result);
283 /// ```
284 pub fn replace_region_in_text<F>(text: &str, start: &str, end: &str, replace_start: bool, replacements: F) -> FileChange
285 where
286     F: FnOnce() -> Vec<String>,
287 {
288     let replace_it = replacements();
289     let mut in_old_region = false;
290     let mut found = false;
291     let mut new_lines = vec![];
292     let start = Regex::new(start).unwrap();
293     let end = Regex::new(end).unwrap();
294
295     for line in text.lines() {
296         if in_old_region {
297             if end.is_match(line) {
298                 in_old_region = false;
299                 new_lines.extend(replace_it.clone());
300                 new_lines.push(line.to_string());
301             }
302         } else if start.is_match(line) {
303             if !replace_start {
304                 new_lines.push(line.to_string());
305             }
306             in_old_region = true;
307             found = true;
308         } else {
309             new_lines.push(line.to_string());
310         }
311     }
312
313     if !found {
314         // This happens if the provided regex in `clippy_dev/src/main.rs` does not match in the
315         // given text or file. Most likely this is an error on the programmer's side and the Regex
316         // is incorrect.
317         eprintln!("error: regex \n{:?}\ndoesn't match. You may have to update it.", start);
318         std::process::exit(1);
319     }
320
321     let mut new_lines = new_lines.join("\n");
322     if text.ends_with('\n') {
323         new_lines.push('\n');
324     }
325     let changed = new_lines != text;
326     FileChange { changed, new_lines }
327 }
328
329 /// Returns the path to the Clippy project directory
330 #[must_use]
331 pub fn clippy_project_root() -> PathBuf {
332     let current_dir = std::env::current_dir().unwrap();
333     for path in current_dir.ancestors() {
334         let result = std::fs::read_to_string(path.join("Cargo.toml"));
335         if let Err(err) = &result {
336             if err.kind() == std::io::ErrorKind::NotFound {
337                 continue;
338             }
339         }
340
341         let content = result.unwrap();
342         if content.contains("[package]\nname = \"clippy\"") {
343             return path.to_path_buf();
344         }
345     }
346     panic!("error: Can't determine root of project. Please run inside a Clippy working dir.");
347 }
348
349 #[test]
350 fn test_parse_contents() {
351     let result: Vec<Lint> = parse_contents(
352         r#"
353 declare_clippy_lint! {
354     pub PTR_ARG,
355     style,
356     "really long \
357      text"
358 }
359
360 declare_clippy_lint!{
361     pub DOC_MARKDOWN,
362     pedantic,
363     "single line"
364 }
365
366 /// some doc comment
367 declare_deprecated_lint! {
368     pub SHOULD_ASSERT_EQ,
369     "`assert!()` will be more flexible with RFC 2011"
370 }
371     "#,
372         "module_name",
373     )
374     .collect();
375
376     let expected = vec![
377         Lint::new("ptr_arg", "style", "really long text", None, "module_name"),
378         Lint::new("doc_markdown", "pedantic", "single line", None, "module_name"),
379         Lint::new(
380             "should_assert_eq",
381             "Deprecated",
382             "`assert!()` will be more flexible with RFC 2011",
383             Some("`assert!()` will be more flexible with RFC 2011"),
384             "module_name",
385         ),
386     ];
387     assert_eq!(expected, result);
388 }
389
390 #[test]
391 fn test_replace_region() {
392     let text = "\nabc\n123\n789\ndef\nghi";
393     let expected = FileChange {
394         changed: true,
395         new_lines: "\nabc\nhello world\ndef\nghi".to_string(),
396     };
397     let result = replace_region_in_text(text, r#"^\s*abc$"#, r#"^\s*def"#, false, || {
398         vec!["hello world".to_string()]
399     });
400     assert_eq!(expected, result);
401 }
402
403 #[test]
404 fn test_replace_region_with_start() {
405     let text = "\nabc\n123\n789\ndef\nghi";
406     let expected = FileChange {
407         changed: true,
408         new_lines: "\nhello world\ndef\nghi".to_string(),
409     };
410     let result = replace_region_in_text(text, r#"^\s*abc$"#, r#"^\s*def"#, true, || {
411         vec!["hello world".to_string()]
412     });
413     assert_eq!(expected, result);
414 }
415
416 #[test]
417 fn test_replace_region_no_changes() {
418     let text = "123\n456\n789";
419     let expected = FileChange {
420         changed: false,
421         new_lines: "123\n456\n789".to_string(),
422     };
423     let result = replace_region_in_text(text, r#"^\s*123$"#, r#"^\s*456"#, false, Vec::new);
424     assert_eq!(expected, result);
425 }
426
427 #[test]
428 fn test_usable_lints() {
429     let lints = vec![
430         Lint::new("should_assert_eq", "Deprecated", "abc", Some("Reason"), "module_name"),
431         Lint::new("should_assert_eq2", "Not Deprecated", "abc", None, "module_name"),
432         Lint::new("should_assert_eq2", "internal", "abc", None, "module_name"),
433         Lint::new("should_assert_eq2", "internal_style", "abc", None, "module_name"),
434     ];
435     let expected = vec![Lint::new(
436         "should_assert_eq2",
437         "Not Deprecated",
438         "abc",
439         None,
440         "module_name",
441     )];
442     assert_eq!(expected, Lint::usable_lints(&lints));
443 }
444
445 #[test]
446 fn test_by_lint_group() {
447     let lints = vec![
448         Lint::new("should_assert_eq", "group1", "abc", None, "module_name"),
449         Lint::new("should_assert_eq2", "group2", "abc", None, "module_name"),
450         Lint::new("incorrect_match", "group1", "abc", None, "module_name"),
451     ];
452     let mut expected: HashMap<String, Vec<Lint>> = HashMap::new();
453     expected.insert(
454         "group1".to_string(),
455         vec![
456             Lint::new("should_assert_eq", "group1", "abc", None, "module_name"),
457             Lint::new("incorrect_match", "group1", "abc", None, "module_name"),
458         ],
459     );
460     expected.insert(
461         "group2".to_string(),
462         vec![Lint::new("should_assert_eq2", "group2", "abc", None, "module_name")],
463     );
464     assert_eq!(expected, Lint::by_lint_group(lints.into_iter()));
465 }
466
467 #[test]
468 fn test_gen_changelog_lint_list() {
469     let lints = vec![
470         Lint::new("should_assert_eq", "group1", "abc", None, "module_name"),
471         Lint::new("should_assert_eq2", "group2", "abc", None, "module_name"),
472     ];
473     let expected = vec![
474         format!("[`should_assert_eq`]: {}#should_assert_eq", DOCS_LINK.to_string()),
475         format!("[`should_assert_eq2`]: {}#should_assert_eq2", DOCS_LINK.to_string()),
476     ];
477     assert_eq!(expected, gen_changelog_lint_list(lints.iter()));
478 }
479
480 #[test]
481 fn test_gen_deprecated() {
482     let lints = vec![
483         Lint::new(
484             "should_assert_eq",
485             "group1",
486             "abc",
487             Some("has been superseded by should_assert_eq2"),
488             "module_name",
489         ),
490         Lint::new(
491             "another_deprecated",
492             "group2",
493             "abc",
494             Some("will be removed"),
495             "module_name",
496         ),
497     ];
498     let expected: Vec<String> = vec![
499         "    store.register_removed(",
500         "        \"clippy::should_assert_eq\",",
501         "        \"has been superseded by should_assert_eq2\",",
502         "    );",
503         "    store.register_removed(",
504         "        \"clippy::another_deprecated\",",
505         "        \"will be removed\",",
506         "    );",
507     ]
508     .into_iter()
509     .map(String::from)
510     .collect();
511     assert_eq!(expected, gen_deprecated(lints.iter()));
512 }
513
514 #[test]
515 #[should_panic]
516 fn test_gen_deprecated_fail() {
517     let lints = vec![Lint::new("should_assert_eq2", "group2", "abc", None, "module_name")];
518     let _ = gen_deprecated(lints.iter());
519 }
520
521 #[test]
522 fn test_gen_modules_list() {
523     let lints = vec![
524         Lint::new("should_assert_eq", "group1", "abc", None, "module_name"),
525         Lint::new("incorrect_stuff", "group3", "abc", None, "another_module"),
526     ];
527     let expected = vec!["mod another_module;".to_string(), "mod module_name;".to_string()];
528     assert_eq!(expected, gen_modules_list(lints.iter()));
529 }
530
531 #[test]
532 fn test_gen_lint_group_list() {
533     let lints = vec![
534         Lint::new("abc", "group1", "abc", None, "module_name"),
535         Lint::new("should_assert_eq", "group1", "abc", None, "module_name"),
536         Lint::new("internal", "internal_style", "abc", None, "module_name"),
537     ];
538     let expected = vec![
539         "        LintId::of(&module_name::ABC),".to_string(),
540         "        LintId::of(&module_name::INTERNAL),".to_string(),
541         "        LintId::of(&module_name::SHOULD_ASSERT_EQ),".to_string(),
542     ];
543     assert_eq!(expected, gen_lint_group_list(lints.iter()));
544 }