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