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