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