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