]> git.lizzy.rs Git - rust.git/blob - clippy_dev/src/lib.rs
Typo
[rust.git] / clippy_dev / src / lib.rs
1 #![cfg_attr(feature = "deny-warnings", deny(warnings))]
2 #![feature(once_cell)]
3
4 use itertools::Itertools;
5 use regex::Regex;
6 use std::collections::HashMap;
7 use std::ffi::OsStr;
8 use std::fs;
9 use std::lazy::SyncLazy;
10 use std::path::{Path, PathBuf};
11 use walkdir::WalkDir;
12
13 pub mod bless;
14 pub mod fmt;
15 pub mod lintcheck;
16 pub mod new_lint;
17 pub mod ra_setup;
18 pub mod serve;
19 pub mod stderr_length_check;
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         .map(PathBuf::from)
190         .or_else(|_| {
191             path_buf
192                 .strip_prefix(clippy_project_root().join("clippy_utils/src"))
193                 .map(|c| Path::new("utils").join(c))
194         })
195         .expect("only files in `clippy_lints/src` or `clippy_utils/src` should be looked at");
196     // If the lints are stored in mod.rs, we get the module name from
197     // the containing directory:
198     if filename == "mod" {
199         rel_path = rel_path.parent().unwrap().to_path_buf();
200     }
201
202     let module = rel_path
203         .components()
204         .map(|c| c.as_os_str().to_str().unwrap())
205         .collect::<Vec<_>>()
206         .join("::");
207
208     parse_contents(&content, &module)
209 }
210
211 fn parse_contents(content: &str, module: &str) -> impl Iterator<Item = Lint> {
212     let lints = DEC_CLIPPY_LINT_RE
213         .captures_iter(content)
214         .map(|m| Lint::new(&m["name"], &m["cat"], &m["desc"], None, module));
215     let deprecated = DEC_DEPRECATED_LINT_RE
216         .captures_iter(content)
217         .map(|m| Lint::new(&m["name"], "Deprecated", &m["desc"], Some(&m["desc"]), module));
218     // Removing the `.collect::<Vec<Lint>>().into_iter()` causes some lifetime issues due to the map
219     lints.chain(deprecated).collect::<Vec<Lint>>().into_iter()
220 }
221
222 /// Collects all .rs files in the `clippy_lints/src` and `clippy_utils/src` directories
223 fn lint_files() -> impl Iterator<Item = walkdir::DirEntry> {
224     // We use `WalkDir` instead of `fs::read_dir` here in order to recurse into subdirectories.
225     // Otherwise we would not collect all the lints, for example in `clippy_lints/src/methods/`.
226     let clippy_lints_path = clippy_project_root().join("clippy_lints/src");
227     let clippy_utils_path = clippy_project_root().join("clippy_utils/src");
228     WalkDir::new(clippy_lints_path)
229         .into_iter()
230         .chain(WalkDir::new(clippy_utils_path).into_iter())
231         .filter_map(Result::ok)
232         .filter(|f| f.path().extension() == Some(OsStr::new("rs")))
233 }
234
235 /// Whether a file has had its text changed or not
236 #[derive(PartialEq, Debug)]
237 pub struct FileChange {
238     pub changed: bool,
239     pub new_lines: String,
240 }
241
242 /// Replaces a region in a file delimited by two lines matching regexes.
243 ///
244 /// `path` is the relative path to the file on which you want to perform the replacement.
245 ///
246 /// See `replace_region_in_text` for documentation of the other options.
247 ///
248 /// # Panics
249 ///
250 /// Panics if the path could not read or then written
251 pub fn replace_region_in_file<F>(
252     path: &Path,
253     start: &str,
254     end: &str,
255     replace_start: bool,
256     write_back: bool,
257     replacements: F,
258 ) -> FileChange
259 where
260     F: FnOnce() -> Vec<String>,
261 {
262     let contents = fs::read_to_string(path).unwrap_or_else(|e| panic!("Cannot read from {}: {}", path.display(), e));
263     let file_change = replace_region_in_text(&contents, start, end, replace_start, replacements);
264
265     if write_back {
266         if let Err(e) = fs::write(path, file_change.new_lines.as_bytes()) {
267             panic!("Cannot write to {}: {}", path.display(), e);
268         }
269     }
270     file_change
271 }
272
273 /// Replaces a region in a text delimited by two lines matching regexes.
274 ///
275 /// * `text` is the input text on which you want to perform the replacement
276 /// * `start` is a `&str` that describes the delimiter line before the region you want to replace.
277 ///   As the `&str` will be converted to a `Regex`, this can contain regex syntax, too.
278 /// * `end` is a `&str` that describes the delimiter line until where the replacement should happen.
279 ///   As the `&str` will be converted to a `Regex`, this can contain regex syntax, too.
280 /// * If `replace_start` is true, the `start` delimiter line is replaced as well. The `end`
281 ///   delimiter line is never replaced.
282 /// * `replacements` is a closure that has to return a `Vec<String>` which contains the new text.
283 ///
284 /// If you want to perform the replacement on files instead of already parsed text,
285 /// use `replace_region_in_file`.
286 ///
287 /// # Example
288 ///
289 /// ```
290 /// let the_text = "replace_start\nsome text\nthat will be replaced\nreplace_end";
291 /// let result =
292 ///     clippy_dev::replace_region_in_text(the_text, "replace_start", "replace_end", false, || {
293 ///         vec!["a different".to_string(), "text".to_string()]
294 ///     })
295 ///     .new_lines;
296 /// assert_eq!("replace_start\na different\ntext\nreplace_end", result);
297 /// ```
298 ///
299 /// # Panics
300 ///
301 /// Panics if start or end is not valid regex
302 pub fn replace_region_in_text<F>(text: &str, start: &str, end: &str, replace_start: bool, replacements: F) -> FileChange
303 where
304     F: FnOnce() -> Vec<String>,
305 {
306     let replace_it = replacements();
307     let mut in_old_region = false;
308     let mut found = false;
309     let mut new_lines = vec![];
310     let start = Regex::new(start).unwrap();
311     let end = Regex::new(end).unwrap();
312
313     for line in text.lines() {
314         if in_old_region {
315             if end.is_match(line) {
316                 in_old_region = false;
317                 new_lines.extend(replace_it.clone());
318                 new_lines.push(line.to_string());
319             }
320         } else if start.is_match(line) {
321             if !replace_start {
322                 new_lines.push(line.to_string());
323             }
324             in_old_region = true;
325             found = true;
326         } else {
327             new_lines.push(line.to_string());
328         }
329     }
330
331     if !found {
332         // This happens if the provided regex in `clippy_dev/src/main.rs` does not match in the
333         // given text or file. Most likely this is an error on the programmer's side and the Regex
334         // is incorrect.
335         eprintln!("error: regex \n{:?}\ndoesn't match. You may have to update it.", start);
336         std::process::exit(1);
337     }
338
339     let mut new_lines = new_lines.join("\n");
340     if text.ends_with('\n') {
341         new_lines.push('\n');
342     }
343     let changed = new_lines != text;
344     FileChange { changed, new_lines }
345 }
346
347 /// Returns the path to the Clippy project directory
348 ///
349 /// # Panics
350 ///
351 /// Panics if the current directory could not be retrieved, there was an error reading any of the
352 /// Cargo.toml files or ancestor directory is the clippy root directory
353 #[must_use]
354 pub fn clippy_project_root() -> PathBuf {
355     let current_dir = std::env::current_dir().unwrap();
356     for path in current_dir.ancestors() {
357         let result = std::fs::read_to_string(path.join("Cargo.toml"));
358         if let Err(err) = &result {
359             if err.kind() == std::io::ErrorKind::NotFound {
360                 continue;
361             }
362         }
363
364         let content = result.unwrap();
365         if content.contains("[package]\nname = \"clippy\"") {
366             return path.to_path_buf();
367         }
368     }
369     panic!("error: Can't determine root of project. Please run inside a Clippy working dir.");
370 }
371
372 #[test]
373 fn test_parse_contents() {
374     let result: Vec<Lint> = parse_contents(
375         r#"
376 declare_clippy_lint! {
377     pub PTR_ARG,
378     style,
379     "really long \
380      text"
381 }
382
383 declare_clippy_lint!{
384     pub DOC_MARKDOWN,
385     pedantic,
386     "single line"
387 }
388
389 /// some doc comment
390 declare_deprecated_lint! {
391     pub SHOULD_ASSERT_EQ,
392     "`assert!()` will be more flexible with RFC 2011"
393 }
394     "#,
395         "module_name",
396     )
397     .collect();
398
399     let expected = vec![
400         Lint::new("ptr_arg", "style", "really long text", None, "module_name"),
401         Lint::new("doc_markdown", "pedantic", "single line", None, "module_name"),
402         Lint::new(
403             "should_assert_eq",
404             "Deprecated",
405             "`assert!()` will be more flexible with RFC 2011",
406             Some("`assert!()` will be more flexible with RFC 2011"),
407             "module_name",
408         ),
409     ];
410     assert_eq!(expected, result);
411 }
412
413 #[test]
414 fn test_replace_region() {
415     let text = "\nabc\n123\n789\ndef\nghi";
416     let expected = FileChange {
417         changed: true,
418         new_lines: "\nabc\nhello world\ndef\nghi".to_string(),
419     };
420     let result = replace_region_in_text(text, r#"^\s*abc$"#, r#"^\s*def"#, false, || {
421         vec!["hello world".to_string()]
422     });
423     assert_eq!(expected, result);
424 }
425
426 #[test]
427 fn test_replace_region_with_start() {
428     let text = "\nabc\n123\n789\ndef\nghi";
429     let expected = FileChange {
430         changed: true,
431         new_lines: "\nhello world\ndef\nghi".to_string(),
432     };
433     let result = replace_region_in_text(text, r#"^\s*abc$"#, r#"^\s*def"#, true, || {
434         vec!["hello world".to_string()]
435     });
436     assert_eq!(expected, result);
437 }
438
439 #[test]
440 fn test_replace_region_no_changes() {
441     let text = "123\n456\n789";
442     let expected = FileChange {
443         changed: false,
444         new_lines: "123\n456\n789".to_string(),
445     };
446     let result = replace_region_in_text(text, r#"^\s*123$"#, r#"^\s*456"#, false, Vec::new);
447     assert_eq!(expected, result);
448 }
449
450 #[test]
451 fn test_usable_lints() {
452     let lints = vec![
453         Lint::new("should_assert_eq", "Deprecated", "abc", Some("Reason"), "module_name"),
454         Lint::new("should_assert_eq2", "Not Deprecated", "abc", None, "module_name"),
455         Lint::new("should_assert_eq2", "internal", "abc", None, "module_name"),
456         Lint::new("should_assert_eq2", "internal_style", "abc", None, "module_name"),
457     ];
458     let expected = vec![Lint::new(
459         "should_assert_eq2",
460         "Not Deprecated",
461         "abc",
462         None,
463         "module_name",
464     )];
465     assert_eq!(expected, Lint::usable_lints(&lints));
466 }
467
468 #[test]
469 fn test_by_lint_group() {
470     let lints = vec![
471         Lint::new("should_assert_eq", "group1", "abc", None, "module_name"),
472         Lint::new("should_assert_eq2", "group2", "abc", None, "module_name"),
473         Lint::new("incorrect_match", "group1", "abc", None, "module_name"),
474     ];
475     let mut expected: HashMap<String, Vec<Lint>> = HashMap::new();
476     expected.insert(
477         "group1".to_string(),
478         vec![
479             Lint::new("should_assert_eq", "group1", "abc", None, "module_name"),
480             Lint::new("incorrect_match", "group1", "abc", None, "module_name"),
481         ],
482     );
483     expected.insert(
484         "group2".to_string(),
485         vec![Lint::new("should_assert_eq2", "group2", "abc", None, "module_name")],
486     );
487     assert_eq!(expected, Lint::by_lint_group(lints.into_iter()));
488 }
489
490 #[test]
491 fn test_gen_changelog_lint_list() {
492     let lints = vec![
493         Lint::new("should_assert_eq", "group1", "abc", None, "module_name"),
494         Lint::new("should_assert_eq2", "group2", "abc", None, "module_name"),
495     ];
496     let expected = vec![
497         format!("[`should_assert_eq`]: {}#should_assert_eq", DOCS_LINK.to_string()),
498         format!("[`should_assert_eq2`]: {}#should_assert_eq2", DOCS_LINK.to_string()),
499     ];
500     assert_eq!(expected, gen_changelog_lint_list(lints.iter()));
501 }
502
503 #[test]
504 fn test_gen_deprecated() {
505     let lints = vec![
506         Lint::new(
507             "should_assert_eq",
508             "group1",
509             "abc",
510             Some("has been superseded by should_assert_eq2"),
511             "module_name",
512         ),
513         Lint::new(
514             "another_deprecated",
515             "group2",
516             "abc",
517             Some("will be removed"),
518             "module_name",
519         ),
520     ];
521     let expected: Vec<String> = vec![
522         "    store.register_removed(",
523         "        \"clippy::should_assert_eq\",",
524         "        \"has been superseded by should_assert_eq2\",",
525         "    );",
526         "    store.register_removed(",
527         "        \"clippy::another_deprecated\",",
528         "        \"will be removed\",",
529         "    );",
530     ]
531     .into_iter()
532     .map(String::from)
533     .collect();
534     assert_eq!(expected, gen_deprecated(lints.iter()));
535 }
536
537 #[test]
538 #[should_panic]
539 fn test_gen_deprecated_fail() {
540     let lints = vec![Lint::new("should_assert_eq2", "group2", "abc", None, "module_name")];
541     let _ = gen_deprecated(lints.iter());
542 }
543
544 #[test]
545 fn test_gen_modules_list() {
546     let lints = vec![
547         Lint::new("should_assert_eq", "group1", "abc", None, "module_name"),
548         Lint::new("incorrect_stuff", "group3", "abc", None, "another_module"),
549     ];
550     let expected = vec!["mod another_module;".to_string(), "mod module_name;".to_string()];
551     assert_eq!(expected, gen_modules_list(lints.iter()));
552 }
553
554 #[test]
555 fn test_gen_lint_group_list() {
556     let lints = vec![
557         Lint::new("abc", "group1", "abc", None, "module_name"),
558         Lint::new("should_assert_eq", "group1", "abc", None, "module_name"),
559         Lint::new("internal", "internal_style", "abc", None, "module_name"),
560     ];
561     let expected = vec![
562         "        LintId::of(&module_name::ABC),".to_string(),
563         "        LintId::of(&module_name::INTERNAL),".to_string(),
564         "        LintId::of(&module_name::SHOULD_ASSERT_EQ),".to_string(),
565     ];
566     assert_eq!(expected, gen_lint_group_list(lints.iter()));
567 }