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