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