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