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