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