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