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